profilePreview.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. import {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 {FlamegraphPreview} from 'sentry/components/profiling/flamegraph/flamegraphPreview';
  10. import QuestionTooltip from 'sentry/components/questionTooltip';
  11. import {t, tct} from 'sentry/locale';
  12. import {space} from 'sentry/styles/space';
  13. import type {EventTransaction} from 'sentry/types/event';
  14. import type {Organization} from 'sentry/types/organization';
  15. import {defined} from 'sentry/utils';
  16. import {trackAnalytics} from 'sentry/utils/analytics';
  17. import type {CanvasView} from 'sentry/utils/profiling/canvasView';
  18. import {colorComponentsToRGBA} from 'sentry/utils/profiling/colors/utils';
  19. import {Flamegraph as FlamegraphModel} from 'sentry/utils/profiling/flamegraph';
  20. import {FlamegraphThemeProvider} from 'sentry/utils/profiling/flamegraph/flamegraphThemeProvider';
  21. import {useFlamegraphTheme} from 'sentry/utils/profiling/flamegraph/useFlamegraphTheme';
  22. import {getProfilingDocsForPlatform} from 'sentry/utils/profiling/platforms';
  23. import {generateProfileFlamechartRouteWithQuery} from 'sentry/utils/profiling/routes';
  24. import {Rect} from 'sentry/utils/profiling/speedscope';
  25. import useOrganization from 'sentry/utils/useOrganization';
  26. import useProjects from 'sentry/utils/useProjects';
  27. import type {
  28. MissingInstrumentationNode,
  29. TraceTree,
  30. TraceTreeNode,
  31. } from 'sentry/views/performance/newTraceDetails/traceModels/traceTree';
  32. import {useProfileGroup} from 'sentry/views/profiling/profileGroupProvider';
  33. import {useProfiles} from 'sentry/views/profiling/profilesProvider';
  34. interface SpanProfileProps {
  35. event: Readonly<EventTransaction>;
  36. node: TraceTreeNode<TraceTree.Span> | MissingInstrumentationNode;
  37. }
  38. export function ProfilePreview({event, node}: SpanProfileProps) {
  39. const {projects} = useProjects();
  40. const profiles = useProfiles();
  41. const profileGroup = useProfileGroup();
  42. const project = useMemo(
  43. () => projects.find(p => p.id === event.projectID),
  44. [projects, event]
  45. );
  46. const organization = useOrganization();
  47. const [canvasView, setCanvasView] = useState<CanvasView<FlamegraphModel> | null>(null);
  48. const profile = useMemo(() => {
  49. const threadId = profileGroup.profiles[profileGroup.activeProfileIndex]?.threadId;
  50. if (!defined(threadId)) {
  51. return null;
  52. }
  53. return profileGroup.profiles.find(p => p.threadId === threadId) ?? null;
  54. }, [profileGroup.profiles, profileGroup.activeProfileIndex]);
  55. const transactionHasProfile = useMemo(() => {
  56. return (node.parent_transaction?.profiles?.length ?? 0) > 0;
  57. }, [node]);
  58. const flamegraph = useMemo(() => {
  59. if (!transactionHasProfile || !profile) {
  60. return FlamegraphModel.Example();
  61. }
  62. return new FlamegraphModel(profile, {});
  63. }, [transactionHasProfile, profile]);
  64. // The most recent profile formats should contain a timestamp indicating
  65. // the beginning of the profile. This timestamp can be after the start
  66. // timestamp on the transaction, so we need to account for the gap and
  67. // make sure the relative start timestamps we compute for the span is
  68. // relative to the start of the profile.
  69. //
  70. // If the profile does not contain a timestamp, we fall back to using the
  71. // start timestamp on the transaction. This won't be as accurate but it's
  72. // the next best thing.
  73. const startTimestamp = profile?.timestamp ?? event.startTimestamp;
  74. const relativeStartTimestamp = transactionHasProfile
  75. ? node.value.start_timestamp - startTimestamp
  76. : 0;
  77. const relativeStopTimestamp = transactionHasProfile
  78. ? node.value.timestamp - startTimestamp
  79. : flamegraph.configSpace.width;
  80. if (transactionHasProfile) {
  81. return (
  82. <FlamegraphThemeProvider>
  83. {/* If you remove this div, padding between elements will break */}
  84. <div>
  85. <ProfilePreviewHeader
  86. event={event}
  87. canvasView={canvasView}
  88. organization={organization}
  89. />
  90. <ProfilePreviewLegend />
  91. <FlamegraphContainer>
  92. {profiles.type === 'loading' ? (
  93. <LoadingIndicator />
  94. ) : (
  95. <FlamegraphPreview
  96. flamegraph={flamegraph}
  97. updateFlamegraphView={setCanvasView}
  98. relativeStartTimestamp={relativeStartTimestamp}
  99. relativeStopTimestamp={relativeStopTimestamp}
  100. />
  101. )}
  102. </FlamegraphContainer>
  103. <ManualInstrumentationInstruction />
  104. </div>
  105. </FlamegraphThemeProvider>
  106. );
  107. }
  108. // The event's platform is more accurate than the project
  109. // so use that first and fall back to the project's platform
  110. const docsLink =
  111. getProfilingDocsForPlatform(event.platform) ??
  112. (project && getProfilingDocsForPlatform(project.platform));
  113. // This project has received a profile before so they've already
  114. // set up profiling. No point showing the profiling setup again.
  115. if (!docsLink || project?.hasProfiles) {
  116. return (
  117. <InlineDocs
  118. resetCellMeasureCache={() => void 0}
  119. orgSlug={organization.slug}
  120. platform={event.sdk?.name || ''}
  121. projectSlug={event?.projectSlug ?? project?.slug ?? ''}
  122. />
  123. );
  124. }
  125. // At this point we must have a project on a supported
  126. // platform that has not setup profiling yet
  127. return <SetupProfiling link={docsLink} />;
  128. }
  129. interface ProfilePreviewProps {
  130. canvasView: CanvasView<FlamegraphModel> | null;
  131. event: Readonly<EventTransaction>;
  132. organization: Organization;
  133. }
  134. function ProfilePreviewHeader({canvasView, event, organization}: ProfilePreviewProps) {
  135. const profileId = event.contexts.profile?.profile_id || '';
  136. // we want to try to go straight to the same config view as the preview
  137. const query = canvasView?.configView
  138. ? {
  139. // TODO: this assumes that profile start timestamp == transaction timestamp
  140. fov: Rect.encode(canvasView.configView),
  141. // the flamechart persists some preferences to local storage,
  142. // force these settings so the view is the same as the preview
  143. view: 'top down',
  144. type: 'flamechart',
  145. }
  146. : undefined;
  147. const target = generateProfileFlamechartRouteWithQuery({
  148. orgSlug: organization.slug,
  149. projectSlug: event?.projectSlug ?? '',
  150. profileId,
  151. query,
  152. });
  153. function handleGoToProfile() {
  154. trackAnalytics('profiling_views.go_to_flamegraph', {
  155. organization,
  156. source: 'performance.missing_instrumentation',
  157. });
  158. }
  159. return (
  160. <HeaderContainer>
  161. <HeaderContainer>
  162. <StyledSectionHeading>{t('Related Profile')}</StyledSectionHeading>
  163. <QuestionTooltip
  164. position="top"
  165. size="sm"
  166. containerDisplayMode="block"
  167. title={t(
  168. 'This profile was collected concurrently with the transaction. It displays the relevant stacks and functions for the duration of this span.'
  169. )}
  170. />
  171. </HeaderContainer>
  172. <LinkButton size="xs" onClick={handleGoToProfile} to={target}>
  173. {t('View Profile')}
  174. </LinkButton>
  175. </HeaderContainer>
  176. );
  177. }
  178. function ProfilePreviewLegend() {
  179. const theme = useFlamegraphTheme();
  180. const applicationFrameColor = colorComponentsToRGBA(
  181. theme.COLORS.FRAME_APPLICATION_COLOR
  182. );
  183. const systemFrameColor = colorComponentsToRGBA(theme.COLORS.FRAME_SYSTEM_COLOR);
  184. return (
  185. <LegendContainer>
  186. <LegendItem>
  187. <LegendMarker color={applicationFrameColor} />
  188. {t('Application Function')}
  189. </LegendItem>
  190. <LegendItem>
  191. <LegendMarker color={systemFrameColor} />
  192. {t('System Function')}
  193. </LegendItem>
  194. </LegendContainer>
  195. );
  196. }
  197. function SetupProfiling({link}: {link: string}) {
  198. return (
  199. <Container>
  200. <Image src={emptyStateImg} />
  201. <InstructionsContainer>
  202. <h5>{t('With Profiling, we could paint a better picture')}</h5>
  203. <p>
  204. {t(
  205. 'Profiles can give you additional context on which functions are sampled at the same time of these spans.'
  206. )}
  207. </p>
  208. <LinkButton size="sm" priority="primary" href={link} external>
  209. {t('Set Up Profiling')}
  210. </LinkButton>
  211. <ManualInstrumentationInstruction />
  212. </InstructionsContainer>
  213. </Container>
  214. );
  215. }
  216. function ManualInstrumentationInstruction() {
  217. return (
  218. <SubText>
  219. {tct(
  220. `You can also [docLink:manually instrument] certain regions of your code to see span details for future transactions.`,
  221. {
  222. docLink: (
  223. <ExternalLink href="https://docs.sentry.io/product/performance/getting-started/" />
  224. ),
  225. }
  226. )}
  227. </SubText>
  228. );
  229. }
  230. const StyledSectionHeading = styled(SectionHeading)`
  231. color: ${p => p.theme.textColor};
  232. `;
  233. const Container = styled('div')`
  234. display: flex;
  235. gap: ${space(2)};
  236. justify-content: space-between;
  237. flex-direction: column;
  238. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  239. flex-direction: row-reverse;
  240. }
  241. `;
  242. const InstructionsContainer = styled('div')`
  243. > p {
  244. margin: 0;
  245. }
  246. display: flex;
  247. gap: ${space(3)};
  248. flex-direction: column;
  249. align-items: start;
  250. `;
  251. const Image = styled('img')`
  252. user-select: none;
  253. width: 420px;
  254. align-self: center;
  255. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  256. width: 300px;
  257. }
  258. @media (min-width: ${p => p.theme.breakpoints.large}) {
  259. width: 380px;
  260. }
  261. @media (min-width: ${p => p.theme.breakpoints.xlarge}) {
  262. width: 420px;
  263. }
  264. `;
  265. const FlamegraphContainer = styled('div')`
  266. height: 310px;
  267. margin-top: ${space(1)};
  268. margin-bottom: ${space(1)};
  269. position: relative;
  270. `;
  271. const LegendContainer = styled('div')`
  272. display: flex;
  273. flex-direction: row;
  274. gap: ${space(1.5)};
  275. `;
  276. const LegendItem = styled('span')`
  277. display: flex;
  278. flex-direction: row;
  279. align-items: center;
  280. gap: ${space(0.5)};
  281. color: ${p => p.theme.subText};
  282. font-size: ${p => p.theme.fontSizeSmall};
  283. `;
  284. const LegendMarker = styled('span')<{color: string}>`
  285. display: inline-block;
  286. width: 12px;
  287. height: 12px;
  288. border-radius: 1px;
  289. background-color: ${p => p.color};
  290. `;
  291. const HeaderContainer = styled('div')`
  292. display: flex;
  293. flex-direction: row;
  294. align-items: center;
  295. justify-content: space-between;
  296. gap: ${space(1)};
  297. `;
  298. const SubText = styled('p')`
  299. color: ${p => p.theme.subText};
  300. `;