profilePreview.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. import {Fragment, useMemo, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import emptyStateImg from 'sentry-images/spot/profiling-empty-state.svg';
  4. import {LinkButton} from 'sentry/components/button';
  5. import {SectionHeading} from 'sentry/components/charts/styles';
  6. import InlineDocs from 'sentry/components/events/interfaces/spans/inlineDocs';
  7. import ExternalLink from 'sentry/components/links/externalLink';
  8. import LoadingIndicator from 'sentry/components/loadingIndicator';
  9. import Panel from 'sentry/components/panels/panel';
  10. import PanelBody from 'sentry/components/panels/panelBody';
  11. import {FlamegraphPreview} from 'sentry/components/profiling/flamegraph/flamegraphPreview';
  12. import QuestionTooltip from 'sentry/components/questionTooltip';
  13. import {t, tct} from 'sentry/locale';
  14. import {space} from 'sentry/styles/space';
  15. import type {EventTransaction} from 'sentry/types/event';
  16. import type {Organization} from 'sentry/types/organization';
  17. import {defined} from 'sentry/utils';
  18. import {trackAnalytics} from 'sentry/utils/analytics';
  19. import type {CanvasView} from 'sentry/utils/profiling/canvasView';
  20. import {colorComponentsToRGBA} from 'sentry/utils/profiling/colors/utils';
  21. import {Flamegraph as FlamegraphModel} from 'sentry/utils/profiling/flamegraph';
  22. import {FlamegraphThemeProvider} from 'sentry/utils/profiling/flamegraph/flamegraphThemeProvider';
  23. import {useFlamegraphTheme} from 'sentry/utils/profiling/flamegraph/useFlamegraphTheme';
  24. import {getProfilingDocsForPlatform} from 'sentry/utils/profiling/platforms';
  25. import {generateProfileFlamechartRouteWithQuery} from 'sentry/utils/profiling/routes';
  26. import {Rect} from 'sentry/utils/profiling/speedscope';
  27. import useOrganization from 'sentry/utils/useOrganization';
  28. import useProjects from 'sentry/utils/useProjects';
  29. import {SectionDivider} from 'sentry/views/issueDetails/streamline/foldSection';
  30. import {InterimSection} from 'sentry/views/issueDetails/streamline/interimSection';
  31. import {useProfileGroup} from 'sentry/views/profiling/profileGroupProvider';
  32. import {useProfiles} from 'sentry/views/profiling/profilesProvider';
  33. import type {MissingInstrumentationNode} from '../../../traceModels/missingInstrumentationNode';
  34. import {TraceTree} from '../../../traceModels/traceTree';
  35. import type {TraceTreeNode} from '../../../traceModels/traceTreeNode';
  36. import {useHasTraceNewUi} from '../../../useHasTraceNewUi';
  37. interface SpanProfileProps {
  38. event: Readonly<EventTransaction>;
  39. node: TraceTreeNode<TraceTree.Span> | MissingInstrumentationNode;
  40. }
  41. export function ProfilePreview({event, node}: SpanProfileProps) {
  42. const {projects} = useProjects();
  43. const hasNewTraceUi = useHasTraceNewUi();
  44. const profiles = useProfiles();
  45. const profileGroup = useProfileGroup();
  46. const project = useMemo(
  47. () => projects.find(p => p.id === event.projectID),
  48. [projects, event]
  49. );
  50. const organization = useOrganization();
  51. const [canvasView, setCanvasView] = useState<CanvasView<FlamegraphModel> | null>(null);
  52. const profile = useMemo(() => {
  53. const threadId = profileGroup.profiles[profileGroup.activeProfileIndex]?.threadId;
  54. if (!defined(threadId)) {
  55. return null;
  56. }
  57. return profileGroup.profiles.find(p => p.threadId === threadId) ?? null;
  58. }, [profileGroup.profiles, profileGroup.activeProfileIndex]);
  59. const transactionHasProfile = useMemo(() => {
  60. return (TraceTree.ParentTransaction(node)?.profiles?.length ?? 0) > 0;
  61. }, [node]);
  62. const flamegraph = useMemo(() => {
  63. if (!transactionHasProfile || !profile) {
  64. return FlamegraphModel.Example();
  65. }
  66. return new FlamegraphModel(profile, {});
  67. }, [transactionHasProfile, profile]);
  68. if (!hasNewTraceUi) {
  69. return (
  70. <LegacyProfilePreview event={event} node={node as MissingInstrumentationNode} />
  71. );
  72. }
  73. // The most recent profile formats should contain a timestamp indicating
  74. // the beginning of the profile. This timestamp can be after the start
  75. // timestamp on the transaction, so we need to account for the gap and
  76. // make sure the relative start timestamps we compute for the span is
  77. // relative to the start of the profile.
  78. //
  79. // If the profile does not contain a timestamp, we fall back to using the
  80. // start timestamp on the transaction. This won't be as accurate but it's
  81. // the next best thing.
  82. const startTimestamp = profile?.timestamp ?? event.startTimestamp;
  83. const relativeStartTimestamp = transactionHasProfile
  84. ? node.value.start_timestamp - startTimestamp
  85. : 0;
  86. const relativeStopTimestamp = transactionHasProfile
  87. ? node.value.timestamp - startTimestamp
  88. : flamegraph.configSpace.width;
  89. const profileId = event.contexts.profile?.profile_id || '';
  90. // we want to try to go straight to the same config view as the preview
  91. const query = canvasView?.configView
  92. ? {
  93. // TODO: this assumes that profile start timestamp == transaction timestamp
  94. fov: Rect.encode(canvasView.configView),
  95. // the flamechart persists some preferences to local storage,
  96. // force these settings so the view is the same as the preview
  97. view: 'top down',
  98. type: 'flamechart',
  99. }
  100. : undefined;
  101. const target = generateProfileFlamechartRouteWithQuery({
  102. orgSlug: organization.slug,
  103. projectSlug: event?.projectSlug ?? '',
  104. profileId,
  105. query,
  106. });
  107. function handleGoToProfile() {
  108. trackAnalytics('profiling_views.go_to_flamegraph', {
  109. organization,
  110. source: 'performance.missing_instrumentation',
  111. });
  112. }
  113. const message = (
  114. <TextBlock>{t('Or, see if profiling can provide more context on this:')}</TextBlock>
  115. );
  116. if (transactionHasProfile) {
  117. return (
  118. <FlamegraphThemeProvider>
  119. {message}
  120. <SectionDivider />
  121. <InterimSection
  122. title={t('Related Profile')}
  123. type="no_instrumentation_profile"
  124. initialCollapse={false}
  125. actions={
  126. <LinkButton size="xs" onClick={handleGoToProfile} to={target}>
  127. {t('Open in Profiling')}
  128. </LinkButton>
  129. }
  130. >
  131. {/* If you remove this div, padding between elements will break */}
  132. <div>
  133. <ProfilePreviewLegend />
  134. <FlamegraphContainer>
  135. {profiles.type === 'loading' ? (
  136. <LoadingIndicator />
  137. ) : (
  138. <FlamegraphPreview
  139. flamegraph={flamegraph}
  140. updateFlamegraphView={setCanvasView}
  141. relativeStartTimestamp={relativeStartTimestamp}
  142. relativeStopTimestamp={relativeStopTimestamp}
  143. />
  144. )}
  145. </FlamegraphContainer>
  146. </div>
  147. </InterimSection>
  148. </FlamegraphThemeProvider>
  149. );
  150. }
  151. // The event's platform is more accurate than the project
  152. // so use that first and fall back to the project's platform
  153. const docsLink =
  154. getProfilingDocsForPlatform(event.platform) ??
  155. (project && getProfilingDocsForPlatform(project.platform));
  156. // This project has received a profile before so they've already
  157. // set up profiling. No point showing the profiling setup again.
  158. if (!docsLink || project?.hasProfiles) {
  159. return null;
  160. }
  161. // At this point we must have a project on a supported
  162. // platform that has not setup profiling yet
  163. return (
  164. <Fragment>
  165. {message}
  166. <SetupProfiling link={docsLink} />
  167. </Fragment>
  168. );
  169. }
  170. const TextBlock = styled('div')`
  171. font-size: ${p => p.theme.fontSizeLarge};
  172. line-height: 1.5;
  173. margin-bottom: ${space(2)};
  174. `;
  175. function LegacyProfilePreview({event, node}: SpanProfileProps) {
  176. const {projects} = useProjects();
  177. const profiles = useProfiles();
  178. const profileGroup = useProfileGroup();
  179. const project = useMemo(
  180. () => projects.find(p => p.id === event.projectID),
  181. [projects, event]
  182. );
  183. const organization = useOrganization();
  184. const [canvasView, setCanvasView] = useState<CanvasView<FlamegraphModel> | null>(null);
  185. const profile = useMemo(() => {
  186. const threadId = profileGroup.profiles[profileGroup.activeProfileIndex]?.threadId;
  187. if (!defined(threadId)) {
  188. return null;
  189. }
  190. return profileGroup.profiles.find(p => p.threadId === threadId) ?? null;
  191. }, [profileGroup.profiles, profileGroup.activeProfileIndex]);
  192. const transactionHasProfile = useMemo(() => {
  193. return (TraceTree.ParentTransaction(node)?.profiles?.length ?? 0) > 0;
  194. }, [node]);
  195. const flamegraph = useMemo(() => {
  196. if (!transactionHasProfile || !profile) {
  197. return FlamegraphModel.Example();
  198. }
  199. return new FlamegraphModel(profile, {});
  200. }, [transactionHasProfile, profile]);
  201. // The most recent profile formats should contain a timestamp indicating
  202. // the beginning of the profile. This timestamp can be after the start
  203. // timestamp on the transaction, so we need to account for the gap and
  204. // make sure the relative start timestamps we compute for the span is
  205. // relative to the start of the profile.
  206. //
  207. // If the profile does not contain a timestamp, we fall back to using the
  208. // start timestamp on the transaction. This won't be as accurate but it's
  209. // the next best thing.
  210. const startTimestamp = profile?.timestamp ?? event.startTimestamp;
  211. const relativeStartTimestamp = transactionHasProfile
  212. ? node.value.start_timestamp - startTimestamp
  213. : 0;
  214. const relativeStopTimestamp = transactionHasProfile
  215. ? node.value.timestamp - startTimestamp
  216. : flamegraph.configSpace.width;
  217. if (transactionHasProfile) {
  218. return (
  219. <FlamegraphThemeProvider>
  220. {/* If you remove this div, padding between elements will break */}
  221. <div>
  222. <ProfilePreviewHeader
  223. event={event}
  224. canvasView={canvasView}
  225. organization={organization}
  226. />
  227. <ProfilePreviewLegend />
  228. <FlamegraphContainer>
  229. {profiles.type === 'loading' ? (
  230. <LoadingIndicator />
  231. ) : (
  232. <FlamegraphPreview
  233. flamegraph={flamegraph}
  234. updateFlamegraphView={setCanvasView}
  235. relativeStartTimestamp={relativeStartTimestamp}
  236. relativeStopTimestamp={relativeStopTimestamp}
  237. />
  238. )}
  239. </FlamegraphContainer>
  240. <ManualInstrumentationInstruction />
  241. </div>
  242. </FlamegraphThemeProvider>
  243. );
  244. }
  245. // The event's platform is more accurate than the project
  246. // so use that first and fall back to the project's platform
  247. const docsLink =
  248. getProfilingDocsForPlatform(event.platform) ??
  249. (project && getProfilingDocsForPlatform(project.platform));
  250. // This project has received a profile before so they've already
  251. // set up profiling. No point showing the profiling setup again.
  252. if (!docsLink || project?.hasProfiles) {
  253. return <InlineDocs platform={event.sdk?.name || ''} />;
  254. }
  255. // At this point we must have a project on a supported
  256. // platform that has not setup profiling yet
  257. return <LegacySetupProfiling link={docsLink} />;
  258. }
  259. interface ProfilePreviewProps {
  260. canvasView: CanvasView<FlamegraphModel> | null;
  261. event: Readonly<EventTransaction>;
  262. organization: Organization;
  263. }
  264. function ProfilePreviewHeader({canvasView, event, organization}: ProfilePreviewProps) {
  265. const profileId = event.contexts.profile?.profile_id || '';
  266. // we want to try to go straight to the same config view as the preview
  267. const query = canvasView?.configView
  268. ? {
  269. // TODO: this assumes that profile start timestamp == transaction timestamp
  270. fov: Rect.encode(canvasView.configView),
  271. // the flamechart persists some preferences to local storage,
  272. // force these settings so the view is the same as the preview
  273. view: 'top down',
  274. type: 'flamechart',
  275. }
  276. : undefined;
  277. const target = generateProfileFlamechartRouteWithQuery({
  278. orgSlug: organization.slug,
  279. projectSlug: event?.projectSlug ?? '',
  280. profileId,
  281. query,
  282. });
  283. function handleGoToProfile() {
  284. trackAnalytics('profiling_views.go_to_flamegraph', {
  285. organization,
  286. source: 'performance.missing_instrumentation',
  287. });
  288. }
  289. return (
  290. <HeaderContainer>
  291. <HeaderContainer>
  292. <StyledSectionHeading>{t('Related Profile')}</StyledSectionHeading>
  293. <QuestionTooltip
  294. position="top"
  295. size="sm"
  296. containerDisplayMode="block"
  297. title={t(
  298. 'This profile was collected concurrently with the transaction. It displays the relevant stacks and functions for the duration of this span.'
  299. )}
  300. />
  301. </HeaderContainer>
  302. <LinkButton size="xs" onClick={handleGoToProfile} to={target}>
  303. {t('View Profile')}
  304. </LinkButton>
  305. </HeaderContainer>
  306. );
  307. }
  308. function ProfilePreviewLegend() {
  309. const theme = useFlamegraphTheme();
  310. const applicationFrameColor = colorComponentsToRGBA(
  311. theme.COLORS.FRAME_APPLICATION_COLOR
  312. );
  313. const systemFrameColor = colorComponentsToRGBA(theme.COLORS.FRAME_SYSTEM_COLOR);
  314. return (
  315. <LegendContainer>
  316. <LegendItem>
  317. <LegendMarker color={applicationFrameColor} />
  318. {t('Application Function')}
  319. </LegendItem>
  320. <LegendItem>
  321. <LegendMarker color={systemFrameColor} />
  322. {t('System Function')}
  323. </LegendItem>
  324. </LegendContainer>
  325. );
  326. }
  327. function SetupProfiling({link}: {link: string}) {
  328. return (
  329. <Panel>
  330. <StyledPanelBody>
  331. <span>
  332. <h5>{t('Profiling for a Better Picture')}</h5>
  333. <TextBlock>
  334. {t(
  335. 'Profiles can also give you additional context on which functions are getting sampled at the time of these spans.'
  336. )}
  337. </TextBlock>
  338. <LinkButton size="sm" priority="primary" href={link} external>
  339. {t('Get Started')}
  340. </LinkButton>
  341. </span>
  342. <ImageContainer>
  343. <Image src={emptyStateImg} />
  344. </ImageContainer>
  345. </StyledPanelBody>
  346. </Panel>
  347. );
  348. }
  349. const Image = styled('img')`
  350. user-select: none;
  351. width: 250px;
  352. align-self: center;
  353. `;
  354. const StyledPanelBody = styled(PanelBody)`
  355. display: flex;
  356. gap: ${space(2)};
  357. justify-content: space-between;
  358. padding: ${space(2)};
  359. container-type: inline-size;
  360. `;
  361. const ImageContainer = styled('div')`
  362. display: flex;
  363. min-width: 200px;
  364. justify-content: center;
  365. @container (max-width: 600px) {
  366. display: none;
  367. }
  368. `;
  369. function LegacySetupProfiling({link}: {link: string}) {
  370. return (
  371. <Container>
  372. <LegacyImage src={emptyStateImg} />
  373. <InstructionsContainer>
  374. <h5>{t('With Profiling, we could paint a better picture')}</h5>
  375. <p>
  376. {t(
  377. 'Profiles can give you additional context on which functions are sampled at the same time of these spans.'
  378. )}
  379. </p>
  380. <LinkButton size="sm" priority="primary" href={link} external>
  381. {t('Set Up Profiling')}
  382. </LinkButton>
  383. <ManualInstrumentationInstruction />
  384. </InstructionsContainer>
  385. </Container>
  386. );
  387. }
  388. function ManualInstrumentationInstruction() {
  389. return (
  390. <SubText>
  391. {tct(
  392. `You can also [docLink:manually instrument] certain regions of your code to see span details for future transactions.`,
  393. {
  394. docLink: (
  395. <ExternalLink href="https://docs.sentry.io/product/performance/getting-started/" />
  396. ),
  397. }
  398. )}
  399. </SubText>
  400. );
  401. }
  402. const StyledSectionHeading = styled(SectionHeading)`
  403. color: ${p => p.theme.textColor};
  404. `;
  405. const Container = styled('div')`
  406. display: flex;
  407. gap: ${space(2)};
  408. justify-content: space-between;
  409. flex-direction: column;
  410. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  411. flex-direction: row-reverse;
  412. }
  413. `;
  414. const InstructionsContainer = styled('div')`
  415. > p {
  416. margin: 0;
  417. }
  418. display: flex;
  419. gap: ${space(3)};
  420. flex-direction: column;
  421. align-items: start;
  422. `;
  423. const LegacyImage = styled('img')`
  424. user-select: none;
  425. width: 200px;
  426. align-self: center;
  427. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  428. width: 300px;
  429. }
  430. @media (min-width: ${p => p.theme.breakpoints.large}) {
  431. width: 380px;
  432. }
  433. @media (min-width: ${p => p.theme.breakpoints.xlarge}) {
  434. width: 420px;
  435. }
  436. `;
  437. const FlamegraphContainer = styled('div')`
  438. height: 200px;
  439. margin-top: ${space(1)};
  440. margin-bottom: ${space(1)};
  441. position: relative;
  442. `;
  443. const LegendContainer = styled('div')`
  444. display: flex;
  445. flex-direction: row;
  446. gap: ${space(1.5)};
  447. `;
  448. const LegendItem = styled('span')`
  449. display: flex;
  450. flex-direction: row;
  451. align-items: center;
  452. gap: ${space(0.5)};
  453. color: ${p => p.theme.subText};
  454. font-size: ${p => p.theme.fontSizeSmall};
  455. `;
  456. const LegendMarker = styled('span')<{color: string}>`
  457. display: inline-block;
  458. width: 12px;
  459. height: 12px;
  460. border-radius: 1px;
  461. background-color: ${p => p.color};
  462. `;
  463. const HeaderContainer = styled('div')`
  464. display: flex;
  465. flex-direction: row;
  466. align-items: center;
  467. justify-content: space-between;
  468. gap: ${space(1)};
  469. `;
  470. const SubText = styled('p')`
  471. color: ${p => p.theme.subText};
  472. `;