profilePreview.tsx 10 KB

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