differentialFlamegraph.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. import {useCallback, useLayoutEffect, useMemo, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import * as Sentry from '@sentry/react';
  4. import type {mat3} from 'gl-matrix';
  5. import {vec2} from 'gl-matrix';
  6. import {addErrorMessage} from 'sentry/actionCreators/indicator';
  7. import Feature from 'sentry/components/acl/feature';
  8. import {DifferentialFlamegraphLayout} from 'sentry/components/profiling/flamegraph/differentialFlamegraphLayout';
  9. import {FlamegraphContextMenu} from 'sentry/components/profiling/flamegraph/flamegraphContextMenu';
  10. import {DifferentialFlamegraphDrawer} from 'sentry/components/profiling/flamegraph/flamegraphDrawer/differentialFlamegraphDrawer';
  11. import {DifferentialFlamegraphToolbar} from 'sentry/components/profiling/flamegraph/flamegraphToolbar/differentialFlamegraphToolbar';
  12. import {FlamegraphZoomView} from 'sentry/components/profiling/flamegraph/flamegraphZoomView';
  13. import {FlamegraphZoomViewMinimap} from 'sentry/components/profiling/flamegraph/flamegraphZoomViewMinimap';
  14. import {
  15. CanvasPoolManager,
  16. useCanvasScheduler,
  17. } from 'sentry/utils/profiling/canvasScheduler';
  18. import {CanvasView} from 'sentry/utils/profiling/canvasView';
  19. import type {DifferentialFlamegraph as DifferentialFlamegraphModel} from 'sentry/utils/profiling/differentialFlamegraph';
  20. import {FlamegraphStateProvider} from 'sentry/utils/profiling/flamegraph/flamegraphStateProvider/flamegraphContextProvider';
  21. import {FlamegraphThemeProvider} from 'sentry/utils/profiling/flamegraph/flamegraphThemeProvider';
  22. import {useFlamegraphPreferences} from 'sentry/utils/profiling/flamegraph/hooks/useFlamegraphPreferences';
  23. import {useFlamegraphProfiles} from 'sentry/utils/profiling/flamegraph/hooks/useFlamegraphProfiles';
  24. import {useFlamegraphTheme} from 'sentry/utils/profiling/flamegraph/useFlamegraphTheme';
  25. import {FlamegraphCanvas} from 'sentry/utils/profiling/flamegraphCanvas';
  26. import type {FlamegraphFrame} from 'sentry/utils/profiling/flamegraphFrame';
  27. import type {Frame} from 'sentry/utils/profiling/frame';
  28. import {
  29. computeConfigViewWithStrategy,
  30. formatColorForFrame,
  31. initializeFlamegraphRenderer,
  32. useResizeCanvasObserver,
  33. } from 'sentry/utils/profiling/gl/utils';
  34. import {useCurrentProjectFromRouteParam} from 'sentry/utils/profiling/hooks/useCurrentProjectFromRouteParam';
  35. import {useDifferentialFlamegraphModel} from 'sentry/utils/profiling/hooks/useDifferentialFlamegraphModel';
  36. import {useDifferentialFlamegraphQuery} from 'sentry/utils/profiling/hooks/useDifferentialFlamegraphQuery';
  37. import {FlamegraphRenderer2D} from 'sentry/utils/profiling/renderers/flamegraphRenderer2D';
  38. import {FlamegraphRendererWebGL} from 'sentry/utils/profiling/renderers/flamegraphRendererWebGL';
  39. import {Rect} from 'sentry/utils/profiling/speedscope';
  40. import {useLocation} from 'sentry/utils/useLocation';
  41. import usePageFilters from 'sentry/utils/usePageFilters';
  42. import {LOADING_PROFILE_GROUP} from 'sentry/views/profiling/profileGroupProvider';
  43. const noopFormatDuration = () => '';
  44. function applicationFrameOnly(frame: Frame): boolean {
  45. return frame.is_application;
  46. }
  47. function systemFrameOnly(frame: Frame): boolean {
  48. return !frame.is_application;
  49. }
  50. function DifferentialFlamegraphView() {
  51. const location = useLocation();
  52. const selection = usePageFilters();
  53. const flamegraphTheme = useFlamegraphTheme();
  54. const {colorCoding} = useFlamegraphPreferences();
  55. const {selectedRoot} = useFlamegraphProfiles();
  56. const [frameFilterSetting, setFrameFilterSetting] = useState<
  57. 'application' | 'system' | 'all'
  58. >('all');
  59. const frameFilter =
  60. frameFilterSetting === 'application'
  61. ? applicationFrameOnly
  62. : frameFilterSetting === 'system'
  63. ? systemFrameOnly
  64. : undefined;
  65. const project = useCurrentProjectFromRouteParam();
  66. const [negated, setNegated] = useState<boolean>(false);
  67. const canvasPoolManager = useMemo(() => new CanvasPoolManager(), []);
  68. const scheduler = useCanvasScheduler(canvasPoolManager);
  69. const {before, after} = useDifferentialFlamegraphQuery({
  70. projectID: parseInt((project?.id as string) ?? 0, 10),
  71. breakpoint: location.query.breakpoint as unknown as number,
  72. environments: selection.selection.environments,
  73. fingerprint: location.query.fingerprint as unknown as string,
  74. transaction: location.query.transaction as unknown as string,
  75. });
  76. const differentialFlamegraph = useDifferentialFlamegraphModel({
  77. before,
  78. after,
  79. frameFilter,
  80. negated,
  81. });
  82. const [flamegraphCanvasRef, setFlamegraphCanvasRef] =
  83. useState<HTMLCanvasElement | null>(null);
  84. const [flamegraphOverlayCanvasRef, setFlamegraphOverlayCanvasRef] =
  85. useState<HTMLCanvasElement | null>(null);
  86. const [flamegraphMiniMapCanvasRef, setFlamegraphMiniMapCanvasRef] =
  87. useState<HTMLCanvasElement | null>(null);
  88. const [flamegraphMiniMapOverlayCanvasRef, setFlamegraphMiniMapOverlayCanvasRef] =
  89. useState<HTMLCanvasElement | null>(null);
  90. const flamegraphCanvas = useMemo(() => {
  91. if (!flamegraphCanvasRef) {
  92. return null;
  93. }
  94. return new FlamegraphCanvas(flamegraphCanvasRef, vec2.fromValues(0, 0));
  95. }, [flamegraphCanvasRef]);
  96. const flamegraphView = useMemo<CanvasView<DifferentialFlamegraphModel> | null>(
  97. () => {
  98. if (!flamegraphCanvas || !differentialFlamegraph.differentialFlamegraph) {
  99. return null;
  100. }
  101. const newView = new CanvasView({
  102. canvas: flamegraphCanvas,
  103. model: differentialFlamegraph.differentialFlamegraph,
  104. options: {
  105. inverted: differentialFlamegraph.differentialFlamegraph.inverted,
  106. minWidth:
  107. differentialFlamegraph.differentialFlamegraph.profile.minFrameDuration,
  108. barHeight: flamegraphTheme.SIZES.BAR_HEIGHT,
  109. depthOffset: flamegraphTheme.SIZES.AGGREGATE_FLAMEGRAPH_DEPTH_OFFSET,
  110. configSpaceTransform: undefined,
  111. },
  112. });
  113. // Find p75 of the graphtree depth and set the view to 3/4 of that
  114. const depths: number[] = [];
  115. for (const frame of differentialFlamegraph.differentialFlamegraph.frames) {
  116. if (frame.children.length > 0) {
  117. continue;
  118. }
  119. depths.push(frame.depth);
  120. }
  121. if (depths.length > 0) {
  122. depths.sort();
  123. const d = depths[Math.floor(depths.length - 1 * 0.75)];
  124. const depth = Math.max(d, 0);
  125. newView.setConfigView(
  126. newView.configView.withY(depth - (newView.configView.height * 3) / 4)
  127. );
  128. }
  129. return newView;
  130. },
  131. // We skip position.view dependency because it will go into an infinite loop
  132. // eslint-disable-next-line react-hooks/exhaustive-deps
  133. [differentialFlamegraph.differentialFlamegraph, flamegraphCanvas, flamegraphTheme]
  134. );
  135. // Uses a useLayoutEffect to ensure that these top level/global listeners are added before
  136. // any of the children components effects actually run. This way we do not lose events
  137. // when we register/unregister these top level listeners.
  138. useLayoutEffect(() => {
  139. if (!flamegraphCanvas || !flamegraphView) {
  140. return undefined;
  141. }
  142. // This code below manages the synchronization of the config views between spans and flamegraph
  143. // We do so by listening to the config view change event and then updating the other views accordingly which
  144. // allows us to keep the X axis in sync between the two views but keep the Y axis independent
  145. const onConfigViewChange = (rect: Rect, sourceConfigViewChange: CanvasView<any>) => {
  146. if (sourceConfigViewChange === flamegraphView) {
  147. flamegraphView.setConfigView(rect.withHeight(flamegraphView.configView.height));
  148. }
  149. canvasPoolManager.draw();
  150. };
  151. const onTransformConfigView = (
  152. mat: mat3,
  153. sourceTransformConfigView: CanvasView<any>
  154. ) => {
  155. if (sourceTransformConfigView === flamegraphView) {
  156. flamegraphView.transformConfigView(mat);
  157. }
  158. canvasPoolManager.draw();
  159. };
  160. const onResetZoom = () => {
  161. flamegraphView.resetConfigView(flamegraphCanvas);
  162. canvasPoolManager.draw();
  163. };
  164. const onZoomIntoFrame = (frame: FlamegraphFrame, strategy: 'min' | 'exact') => {
  165. const newConfigView = computeConfigViewWithStrategy(
  166. strategy,
  167. flamegraphView.configView,
  168. new Rect(frame.start, frame.depth, frame.end - frame.start, 1)
  169. ).transformRect(flamegraphView.configSpaceTransform);
  170. flamegraphView.setConfigView(newConfigView);
  171. canvasPoolManager.draw();
  172. };
  173. scheduler.on('set config view', onConfigViewChange);
  174. scheduler.on('transform config view', onTransformConfigView);
  175. scheduler.on('reset zoom', onResetZoom);
  176. scheduler.on('zoom at frame', onZoomIntoFrame);
  177. return () => {
  178. scheduler.off('set config view', onConfigViewChange);
  179. scheduler.off('transform config view', onTransformConfigView);
  180. scheduler.off('reset zoom', onResetZoom);
  181. scheduler.off('zoom at frame', onZoomIntoFrame);
  182. };
  183. }, [canvasPoolManager, flamegraphCanvas, flamegraphView, scheduler]);
  184. const flamegraphCanvases = useMemo(() => {
  185. return [flamegraphCanvasRef, flamegraphOverlayCanvasRef];
  186. }, [flamegraphCanvasRef, flamegraphOverlayCanvasRef]);
  187. const flamegraphCanvasBounds = useResizeCanvasObserver(
  188. flamegraphCanvases,
  189. canvasPoolManager,
  190. flamegraphCanvas,
  191. flamegraphView
  192. );
  193. const minimapCanvases = useMemo(() => {
  194. return [flamegraphMiniMapCanvasRef, flamegraphMiniMapOverlayCanvasRef];
  195. }, [flamegraphMiniMapCanvasRef, flamegraphMiniMapOverlayCanvasRef]);
  196. const flamegraphMiniMapCanvas = useMemo(() => {
  197. if (!flamegraphMiniMapCanvasRef) {
  198. return null;
  199. }
  200. return new FlamegraphCanvas(flamegraphMiniMapCanvasRef, vec2.fromValues(0, 0));
  201. }, [flamegraphMiniMapCanvasRef]);
  202. useResizeCanvasObserver(
  203. minimapCanvases,
  204. canvasPoolManager,
  205. flamegraphMiniMapCanvas,
  206. null
  207. );
  208. const flamegraphRenderer = useMemo(() => {
  209. if (!flamegraphCanvasRef || !differentialFlamegraph) {
  210. return null;
  211. }
  212. const renderer = initializeFlamegraphRenderer(
  213. [FlamegraphRendererWebGL, FlamegraphRenderer2D],
  214. [
  215. flamegraphCanvasRef,
  216. differentialFlamegraph.differentialFlamegraph,
  217. flamegraphTheme,
  218. {
  219. colorCoding,
  220. draw_border: true,
  221. },
  222. ]
  223. );
  224. if (renderer === null) {
  225. Sentry.captureException('Failed to initialize a flamegraph renderer');
  226. addErrorMessage('Failed to initialize renderer');
  227. return null;
  228. }
  229. return renderer;
  230. }, [colorCoding, differentialFlamegraph, flamegraphCanvasRef, flamegraphTheme]);
  231. const getFrameColor = useCallback(
  232. (frame: FlamegraphFrame) => {
  233. if (!flamegraphRenderer) {
  234. return '';
  235. }
  236. return formatColorForFrame(frame, flamegraphRenderer);
  237. },
  238. [flamegraphRenderer]
  239. );
  240. const rootNodes = useMemo(() => {
  241. return selectedRoot
  242. ? [selectedRoot]
  243. : differentialFlamegraph.differentialFlamegraph.root.children;
  244. }, [selectedRoot, differentialFlamegraph.differentialFlamegraph.root]);
  245. const referenceNode = useMemo(
  246. () =>
  247. selectedRoot ? selectedRoot : differentialFlamegraph.differentialFlamegraph.root,
  248. [selectedRoot, differentialFlamegraph.differentialFlamegraph.root]
  249. );
  250. return (
  251. <Feature features={['profiling-differential-flamegraph-page']}>
  252. <DifferentialFlamegraphContainer>
  253. <DifferentialFlamegraphToolbar
  254. frameFilter={frameFilterSetting}
  255. onFrameFilterChange={setFrameFilterSetting}
  256. negated={negated}
  257. onNegatedChange={setNegated}
  258. flamegraph={differentialFlamegraph.differentialFlamegraph}
  259. canvasPoolManager={canvasPoolManager}
  260. />
  261. <DifferentialFlamegraphLayout
  262. minimap={
  263. <FlamegraphZoomViewMinimap
  264. canvasPoolManager={canvasPoolManager}
  265. flamegraph={differentialFlamegraph.differentialFlamegraph}
  266. flamegraphMiniMapCanvas={flamegraphMiniMapCanvas}
  267. flamegraphMiniMapCanvasRef={flamegraphMiniMapCanvasRef}
  268. flamegraphMiniMapOverlayCanvasRef={flamegraphMiniMapOverlayCanvasRef}
  269. flamegraphMiniMapView={flamegraphView}
  270. setFlamegraphMiniMapCanvasRef={setFlamegraphMiniMapCanvasRef}
  271. setFlamegraphMiniMapOverlayCanvasRef={setFlamegraphMiniMapOverlayCanvasRef}
  272. />
  273. }
  274. flamegraph={
  275. <FlamegraphZoomView
  276. profileGroup={
  277. differentialFlamegraph.afterProfileGroup ?? LOADING_PROFILE_GROUP
  278. }
  279. disableGrid
  280. disableCallOrderSort
  281. disableColorCoding
  282. canvasBounds={flamegraphCanvasBounds}
  283. canvasPoolManager={canvasPoolManager}
  284. flamegraph={differentialFlamegraph.differentialFlamegraph}
  285. flamegraphRenderer={flamegraphRenderer}
  286. flamegraphCanvas={flamegraphCanvas}
  287. flamegraphCanvasRef={flamegraphCanvasRef}
  288. flamegraphOverlayCanvasRef={flamegraphOverlayCanvasRef}
  289. flamegraphView={flamegraphView}
  290. setFlamegraphCanvasRef={setFlamegraphCanvasRef}
  291. setFlamegraphOverlayCanvasRef={setFlamegraphOverlayCanvasRef}
  292. contextMenu={FlamegraphContextMenu}
  293. />
  294. }
  295. flamegraphDrawer={
  296. <DifferentialFlamegraphDrawer
  297. profileGroup={
  298. differentialFlamegraph.afterProfileGroup ?? LOADING_PROFILE_GROUP
  299. }
  300. getFrameColor={getFrameColor}
  301. referenceNode={referenceNode}
  302. rootNodes={rootNodes}
  303. flamegraph={differentialFlamegraph.differentialFlamegraph}
  304. formatDuration={
  305. differentialFlamegraph.differentialFlamegraph
  306. ? differentialFlamegraph.differentialFlamegraph.formatter
  307. : noopFormatDuration
  308. }
  309. canvasPoolManager={canvasPoolManager}
  310. canvasScheduler={scheduler}
  311. />
  312. }
  313. />
  314. </DifferentialFlamegraphContainer>
  315. </Feature>
  316. );
  317. }
  318. const DifferentialFlamegraphContainer = styled('div')`
  319. display: flex;
  320. flex-direction: column;
  321. flex: 1;
  322. ~ footer {
  323. display: none;
  324. }
  325. `;
  326. function DifferentialFlamegraphWithProviders() {
  327. return (
  328. <FlamegraphThemeProvider>
  329. <FlamegraphStateProvider
  330. initialState={{
  331. preferences: {
  332. sorting: 'alphabetical',
  333. view: 'top down',
  334. },
  335. }}
  336. >
  337. <DifferentialFlamegraphView />
  338. </FlamegraphStateProvider>
  339. </FlamegraphThemeProvider>
  340. );
  341. }
  342. export default DifferentialFlamegraphWithProviders;