profilePreview.tsx 19 KB

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