traceWaterfall.tsx 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  1. import type React from 'react';
  2. import {
  3. Fragment,
  4. useCallback,
  5. useEffect,
  6. useLayoutEffect,
  7. useMemo,
  8. useReducer,
  9. useRef,
  10. useState,
  11. } from 'react';
  12. import {flushSync} from 'react-dom';
  13. import styled from '@emotion/styled';
  14. import * as Sentry from '@sentry/react';
  15. import * as qs from 'query-string';
  16. import {addSuccessMessage} from 'sentry/actionCreators/indicator';
  17. import {t, tct} from 'sentry/locale';
  18. import {space} from 'sentry/styles/space';
  19. import type {EventTransaction} from 'sentry/types/event';
  20. import type {Organization} from 'sentry/types/organization';
  21. import type {Project} from 'sentry/types/project';
  22. import {trackAnalytics} from 'sentry/utils/analytics';
  23. import {browserHistory} from 'sentry/utils/browserHistory';
  24. import type EventView from 'sentry/utils/discover/eventView';
  25. import type {TraceSplitResults} from 'sentry/utils/performance/quickTrace/types';
  26. import {
  27. cancelAnimationTimeout,
  28. requestAnimationTimeout,
  29. } from 'sentry/utils/profiling/hooks/useVirtualizedTree/virtualizedTreeUtils';
  30. import type {UseApiQueryResult} from 'sentry/utils/queryClient';
  31. import type RequestError from 'sentry/utils/requestError/requestError';
  32. import {capitalize} from 'sentry/utils/string/capitalize';
  33. import useApi from 'sentry/utils/useApi';
  34. import type {DispatchingReducerMiddleware} from 'sentry/utils/useDispatchingReducer';
  35. import useOrganization from 'sentry/utils/useOrganization';
  36. import usePageFilters from 'sentry/utils/usePageFilters';
  37. import useProjects from 'sentry/utils/useProjects';
  38. import {TraceTree} from 'sentry/views/performance/newTraceDetails/traceModels/traceTree';
  39. import {useDividerResizeSync} from 'sentry/views/performance/newTraceDetails/useDividerResizeSync';
  40. import {useTraceSpaceListeners} from 'sentry/views/performance/newTraceDetails/useTraceSpaceListeners';
  41. import type {ReplayTrace} from 'sentry/views/replays/detail/trace/useReplayTraces';
  42. import type {ReplayRecord} from 'sentry/views/replays/types';
  43. import type {TraceMetaQueryResults} from './traceApi/useTraceMeta';
  44. import {TraceDrawer} from './traceDrawer/traceDrawer';
  45. import type {TraceTreeNode} from './traceModels/traceTreeNode';
  46. import {TraceScheduler} from './traceRenderers/traceScheduler';
  47. import {TraceView as TraceViewModel} from './traceRenderers/traceView';
  48. import {
  49. type ViewManagerScrollAnchor,
  50. VirtualizedViewManager,
  51. } from './traceRenderers/virtualizedViewManager';
  52. import {
  53. searchInTraceTreeText,
  54. searchInTraceTreeTokens,
  55. } from './traceSearch/traceSearchEvaluator';
  56. import {TraceSearchInput} from './traceSearch/traceSearchInput';
  57. import {parseTraceSearch} from './traceSearch/traceTokenConverter';
  58. import {
  59. useTraceState,
  60. useTraceStateDispatch,
  61. useTraceStateEmitter,
  62. } from './traceState/traceStateProvider';
  63. import {Trace} from './trace';
  64. import {traceAnalytics} from './traceAnalytics';
  65. import {
  66. isAutogroupedNode,
  67. isParentAutogroupedNode,
  68. isSiblingAutogroupedNode,
  69. isTraceNode,
  70. } from './traceGuards';
  71. import {TracePreferencesDropdown} from './tracePreferencesDropdown';
  72. import {TraceResetZoomButton} from './traceResetZoomButton';
  73. import {TraceShortcuts} from './traceShortcutsModal';
  74. import type {TraceReducer, TraceReducerState} from './traceState';
  75. import {
  76. traceNodeAdjacentAnalyticsProperties,
  77. traceNodeAnalyticsName,
  78. } from './traceTreeAnalytics';
  79. import TraceTypeWarnings from './traceTypeWarnings';
  80. import {TraceWaterfallState} from './traceWaterfallState';
  81. import {useTraceOnLoad} from './useTraceOnLoad';
  82. import {useTraceQueryParamStateSync} from './useTraceQueryParamStateSync';
  83. import {useTraceScrollToPath} from './useTraceScrollToPath';
  84. import {useTraceTimelineChangeSync} from './useTraceTimelineChangeSync';
  85. const TRACE_TAB: TraceReducerState['tabs']['tabs'][0] = {
  86. node: 'trace',
  87. label: t('Trace'),
  88. };
  89. const VITALS_TAB: TraceReducerState['tabs']['tabs'][0] = {
  90. node: 'vitals',
  91. label: t('Vitals'),
  92. };
  93. export interface TraceWaterfallProps {
  94. meta: TraceMetaQueryResults;
  95. organization: Organization;
  96. replay: ReplayRecord | null;
  97. rootEvent: UseApiQueryResult<EventTransaction, RequestError>;
  98. source: string;
  99. trace: UseApiQueryResult<TraceSplitResults<TraceTree.Transaction>, RequestError>;
  100. traceEventView: EventView;
  101. traceSlug: string | undefined;
  102. tree: TraceTree;
  103. replayTraces?: ReplayTrace[];
  104. }
  105. export function TraceWaterfall(props: TraceWaterfallProps) {
  106. const api = useApi();
  107. const filters = usePageFilters();
  108. const {projects} = useProjects();
  109. const organization = useOrganization();
  110. const traceState = useTraceState();
  111. const traceDispatch = useTraceStateDispatch();
  112. const traceStateEmitter = useTraceStateEmitter();
  113. const [forceRender, rerender] = useReducer(x => (x + 1) % Number.MAX_SAFE_INTEGER, 0);
  114. const traceView = useMemo(() => new TraceViewModel(), []);
  115. const traceScheduler = useMemo(() => new TraceScheduler(), []);
  116. const projectsRef = useRef<Project[]>(projects);
  117. projectsRef.current = projects;
  118. const scrollQueueRef = useTraceScrollToPath(undefined);
  119. const forceRerender = useCallback(() => {
  120. flushSync(rerender);
  121. }, []);
  122. useEffect(() => {
  123. trackAnalytics('performance_views.trace_view_v1_page_load', {
  124. organization: props.organization,
  125. source: props.source,
  126. });
  127. }, [props.organization, props.source]);
  128. const previouslyFocusedNodeRef = useRef<TraceTreeNode<TraceTree.NodeValue> | null>(
  129. null
  130. );
  131. const previouslyScrolledToNodeRef = useRef<TraceTreeNode<TraceTree.NodeValue> | null>(
  132. null
  133. );
  134. useEffect(() => {
  135. if (!props.replayTraces?.length || props.tree?.type !== 'trace') {
  136. return undefined;
  137. }
  138. const cleanup = props.tree.fetchAdditionalTraces({
  139. api,
  140. filters,
  141. replayTraces: props.replayTraces,
  142. organization: props.organization,
  143. urlParams: qs.parse(location.search),
  144. rerender: forceRerender,
  145. meta: props.meta,
  146. });
  147. return () => cleanup();
  148. // eslint-disable-next-line react-hooks/exhaustive-deps
  149. }, [props.tree, props.replayTraces]);
  150. // Assign the trace state to a ref so we can access it without re-rendering
  151. const traceStateRef = useRef<TraceReducerState>(traceState);
  152. traceStateRef.current = traceState;
  153. const traceStatePreferencesRef = useRef<
  154. Pick<TraceReducerState['preferences'], 'autogroup' | 'missing_instrumentation'>
  155. >(traceState.preferences);
  156. traceStatePreferencesRef.current = traceState.preferences;
  157. // Initialize the view manager right after the state reducer
  158. const viewManager = useMemo(() => {
  159. return new VirtualizedViewManager(
  160. {
  161. list: {width: traceState.preferences.list.width},
  162. span_list: {width: 1 - traceState.preferences.list.width},
  163. },
  164. traceScheduler,
  165. traceView
  166. );
  167. // We only care about initial state when we initialize the view manager
  168. // eslint-disable-next-line react-hooks/exhaustive-deps
  169. }, []);
  170. // Initialize the tabs reducer when the tree initializes
  171. useLayoutEffect(() => {
  172. return traceDispatch({
  173. type: 'set roving count',
  174. items: props.tree.list.length - 1,
  175. });
  176. }, [props.tree.list.length, traceDispatch]);
  177. // Initialize the tabs reducer when the tree initializes
  178. useLayoutEffect(() => {
  179. if (props.tree.type !== 'trace') {
  180. return;
  181. }
  182. const newTabs = [TRACE_TAB];
  183. if (props.tree.vitals.size > 0) {
  184. const types = Array.from(props.tree.vital_types.values());
  185. const label = types.length > 1 ? t('Vitals') : capitalize(types[0]) + ' Vitals';
  186. newTabs.push({
  187. ...VITALS_TAB,
  188. label,
  189. });
  190. }
  191. if (props.tree.profiled_events.size > 0) {
  192. newTabs.push({
  193. node: 'profiles',
  194. label: 'Profiles',
  195. });
  196. }
  197. traceDispatch({
  198. type: 'initialize tabs reducer',
  199. payload: {
  200. current_tab: traceStateRef?.current?.tabs?.tabs?.[0],
  201. tabs: newTabs,
  202. last_clicked_tab: null,
  203. },
  204. });
  205. // We only want to update the tabs when the tree changes
  206. // eslint-disable-next-line react-hooks/exhaustive-deps
  207. }, [props.tree]);
  208. const searchingRaf = useRef<{id: number | null} | null>(null);
  209. const onTraceSearch = useCallback(
  210. (
  211. query: string,
  212. activeNode: TraceTreeNode<TraceTree.NodeValue> | null,
  213. behavior: 'track result' | 'persist'
  214. ) => {
  215. if (searchingRaf.current?.id) {
  216. window.cancelAnimationFrame(searchingRaf.current.id);
  217. searchingRaf.current = null;
  218. }
  219. function done([matches, lookup, activeNodeSearchResult]) {
  220. // If the previous node is still in the results set, we want to keep it
  221. if (activeNodeSearchResult) {
  222. traceDispatch({
  223. type: 'set results',
  224. results: matches,
  225. resultsLookup: lookup,
  226. resultIteratorIndex: activeNodeSearchResult?.resultIteratorIndex,
  227. resultIndex: activeNodeSearchResult?.resultIndex,
  228. previousNode: activeNodeSearchResult,
  229. node: activeNode,
  230. });
  231. return;
  232. }
  233. if (activeNode && behavior === 'persist') {
  234. traceDispatch({
  235. type: 'set results',
  236. results: matches,
  237. resultsLookup: lookup,
  238. resultIteratorIndex: undefined,
  239. resultIndex: undefined,
  240. previousNode: null,
  241. node: activeNode,
  242. });
  243. return;
  244. }
  245. const resultIndex: number | undefined = matches?.[0]?.index;
  246. const resultIteratorIndex: number | undefined = matches?.[0] ? 0 : undefined;
  247. const node: TraceTreeNode<TraceTree.NodeValue> | null = matches?.[0]?.value;
  248. traceDispatch({
  249. type: 'set results',
  250. results: matches,
  251. resultsLookup: lookup,
  252. resultIteratorIndex: resultIteratorIndex,
  253. resultIndex: resultIndex,
  254. previousNode: activeNodeSearchResult,
  255. node,
  256. });
  257. }
  258. const tokens = parseTraceSearch(query);
  259. if (tokens) {
  260. searchingRaf.current = searchInTraceTreeTokens(
  261. props.tree,
  262. tokens,
  263. activeNode,
  264. done
  265. );
  266. } else {
  267. searchingRaf.current = searchInTraceTreeText(props.tree, query, activeNode, done);
  268. }
  269. },
  270. [traceDispatch, props.tree]
  271. );
  272. // We need to heavily debounce query string updates because the rest of the app is so slow
  273. // to rerender that it causes the search to drop frames on every keystroke...
  274. const QUERY_STRING_STATE_DEBOUNCE = 300;
  275. const queryStringAnimationTimeoutRef = useRef<{id: number} | null>(null);
  276. const setRowAsFocused = useCallback(
  277. (
  278. node: TraceTreeNode<TraceTree.NodeValue> | null,
  279. event: React.MouseEvent<HTMLElement> | null,
  280. resultsLookup: Map<TraceTreeNode<TraceTree.NodeValue>, number>,
  281. index: number | null,
  282. debounce: number = QUERY_STRING_STATE_DEBOUNCE
  283. ) => {
  284. // sync query string with the clicked node
  285. if (node) {
  286. if (queryStringAnimationTimeoutRef.current) {
  287. cancelAnimationTimeout(queryStringAnimationTimeoutRef.current);
  288. }
  289. queryStringAnimationTimeoutRef.current = requestAnimationTimeout(() => {
  290. const currentQueryStringPath = qs.parse(location.search).node;
  291. const nextNodePath = TraceTree.PathToNode(node);
  292. // Updating the query string with the same path is problematic because it causes
  293. // the entire sentry app to rerender, which is enough to cause jank and drop frames
  294. if (JSON.stringify(currentQueryStringPath) === JSON.stringify(nextNodePath)) {
  295. return;
  296. }
  297. const {eventId: _eventId, ...query} = qs.parse(location.search);
  298. browserHistory.replace({
  299. pathname: location.pathname,
  300. query: {
  301. ...query,
  302. node: nextNodePath,
  303. },
  304. });
  305. queryStringAnimationTimeoutRef.current = null;
  306. }, debounce);
  307. if (resultsLookup.has(node) && typeof index === 'number') {
  308. traceDispatch({
  309. type: 'set search iterator index',
  310. resultIndex: index,
  311. resultIteratorIndex: resultsLookup.get(node)!,
  312. });
  313. }
  314. if (isTraceNode(node)) {
  315. traceDispatch({type: 'activate tab', payload: TRACE_TAB.node});
  316. return;
  317. }
  318. traceDispatch({
  319. type: 'activate tab',
  320. payload: node,
  321. pin_previous: event?.metaKey,
  322. });
  323. }
  324. },
  325. [traceDispatch]
  326. );
  327. const onRowClick = useCallback(
  328. (
  329. node: TraceTreeNode<TraceTree.NodeValue>,
  330. event: React.MouseEvent<HTMLElement>,
  331. index: number
  332. ) => {
  333. trackAnalytics('trace.trace_layout.span_row_click', {
  334. organization,
  335. num_children: node.children.length,
  336. type: traceNodeAnalyticsName(node),
  337. project_platform:
  338. projects.find(p => p.slug === node.metadata.project_slug)?.platform || 'other',
  339. ...traceNodeAdjacentAnalyticsProperties(node),
  340. });
  341. if (traceStateRef.current.preferences.drawer.minimized) {
  342. traceDispatch({type: 'minimize drawer', payload: false});
  343. }
  344. setRowAsFocused(node, event, traceStateRef.current.search.resultsLookup, null, 0);
  345. if (traceStateRef.current.search.resultsLookup.has(node)) {
  346. const idx = traceStateRef.current.search.resultsLookup.get(node)!;
  347. traceDispatch({
  348. type: 'set search iterator index',
  349. resultIndex: index,
  350. resultIteratorIndex: idx,
  351. });
  352. } else if (traceStateRef.current.search.resultIteratorIndex !== null) {
  353. traceDispatch({type: 'clear search iterator index'});
  354. }
  355. traceDispatch({
  356. type: 'set roving index',
  357. action_source: 'click',
  358. index,
  359. node,
  360. });
  361. },
  362. [setRowAsFocused, traceDispatch, organization, projects]
  363. );
  364. const scrollRowIntoView = useCallback(
  365. (
  366. node: TraceTreeNode<TraceTree.NodeValue>,
  367. index: number,
  368. anchor?: ViewManagerScrollAnchor,
  369. force?: boolean
  370. ) => {
  371. // Last node we scrolled to is the same as the node we want to scroll to
  372. if (previouslyScrolledToNodeRef.current === node && !force) {
  373. return;
  374. }
  375. // Always scroll to the row vertically
  376. viewManager.scrollToRow(index, anchor);
  377. if (viewManager.isOutsideOfView(node)) {
  378. viewManager.scrollRowIntoViewHorizontally(node, 0, 48, 'measured');
  379. }
  380. previouslyScrolledToNodeRef.current = node;
  381. },
  382. [viewManager]
  383. );
  384. const onScrollToNode = useCallback(
  385. (
  386. node: TraceTreeNode<TraceTree.NodeValue>
  387. ): Promise<TraceTreeNode<TraceTree.NodeValue> | null> => {
  388. return TraceTree.ExpandToPath(props.tree, TraceTree.PathToNode(node), {
  389. api,
  390. organization: props.organization,
  391. preferences: traceStatePreferencesRef.current,
  392. }).then(() => {
  393. const maybeNode = TraceTree.Find(props.tree.root, n => n === node);
  394. if (!maybeNode) {
  395. return null;
  396. }
  397. const index = TraceTree.EnforceVisibility(props.tree, maybeNode);
  398. if (index === -1) {
  399. return null;
  400. }
  401. scrollRowIntoView(maybeNode, index, 'center if outside', true);
  402. traceDispatch({
  403. type: 'set roving index',
  404. node: maybeNode,
  405. index: index,
  406. action_source: 'click',
  407. });
  408. if (traceStateRef.current.search.resultsLookup.has(maybeNode)) {
  409. traceDispatch({
  410. type: 'set search iterator index',
  411. resultIndex: index,
  412. resultIteratorIndex:
  413. traceStateRef.current.search.resultsLookup.get(maybeNode)!,
  414. });
  415. } else if (traceStateRef.current.search.resultIteratorIndex !== null) {
  416. traceDispatch({type: 'clear search iterator index'});
  417. }
  418. return maybeNode;
  419. });
  420. },
  421. [api, props.organization, scrollRowIntoView, props.tree, traceDispatch]
  422. );
  423. const onTabScrollToNode = useCallback(
  424. (
  425. node: TraceTreeNode<TraceTree.NodeValue>
  426. ): Promise<TraceTreeNode<TraceTree.NodeValue> | null> => {
  427. return onScrollToNode(node).then(maybeNode => {
  428. if (maybeNode) {
  429. setRowAsFocused(
  430. maybeNode,
  431. null,
  432. traceStateRef.current.search.resultsLookup,
  433. null,
  434. 0
  435. );
  436. }
  437. return maybeNode;
  438. });
  439. },
  440. [onScrollToNode, setRowAsFocused]
  441. );
  442. // Callback that is invoked when the trace loads and reaches its initialied state,
  443. // that is when the trace tree data and any data that the trace depends on is loaded,
  444. // but the trace is not yet rendered in the view.
  445. const onTraceLoad = useCallback(() => {
  446. traceAnalytics.trackTraceShape(props.tree, projectsRef.current, props.organization);
  447. // The tree has the data fetched, but does not yet respect the user preferences.
  448. // We will autogroup and inject missing instrumentation if the preferences are set.
  449. // and then we will perform a search to find the node the user is interested in.
  450. const query = qs.parse(location.search);
  451. if (query.fov && typeof query.fov === 'string') {
  452. viewManager.maybeInitializeTraceViewFromQS(query.fov);
  453. }
  454. if (traceStateRef.current.preferences.missing_instrumentation) {
  455. TraceTree.DetectMissingInstrumentation(props.tree.root);
  456. }
  457. if (traceStateRef.current.preferences.autogroup.sibling) {
  458. TraceTree.AutogroupSiblingSpanNodes(props.tree.root);
  459. }
  460. if (traceStateRef.current.preferences.autogroup.parent) {
  461. TraceTree.AutogroupDirectChildrenSpanNodes(props.tree.root);
  462. }
  463. // Construct the visual representation of the tree
  464. props.tree.build();
  465. const eventId = scrollQueueRef.current?.eventId;
  466. const [type, path] = scrollQueueRef.current?.path?.[0]?.split('-') ?? [];
  467. scrollQueueRef.current = null;
  468. let node =
  469. (path === 'root' && props.tree.root.children[0]) ||
  470. (path && TraceTree.FindByID(props.tree.root, path)) ||
  471. (eventId && TraceTree.FindByID(props.tree.root, eventId)) ||
  472. null;
  473. // If the node points to a span, but we found an autogrouped node, then
  474. // perform another search inside the autogrouped node to find the more detailed
  475. // location of the span. This is necessary because the id of the autogrouped node
  476. // is in some cases inferred from the spans it contains and searching by the span id
  477. // just gives us the first match which may not be the one the user is looking for.
  478. if (node) {
  479. if (isAutogroupedNode(node) && type !== 'ag') {
  480. if (isParentAutogroupedNode(node)) {
  481. node = TraceTree.FindByID(node.head, eventId ?? path) ?? node;
  482. } else if (isSiblingAutogroupedNode(node)) {
  483. node = node.children.find(n => TraceTree.FindByID(n, eventId ?? path)) ?? node;
  484. }
  485. }
  486. }
  487. const index = node ? TraceTree.EnforceVisibility(props.tree, node) : -1;
  488. if (traceStateRef.current.search.query) {
  489. onTraceSearch(traceStateRef.current.search.query, node, 'persist');
  490. }
  491. if (index === -1 || !node) {
  492. const hasScrollComponent = !!(path || eventId);
  493. if (hasScrollComponent) {
  494. Sentry.withScope(scope => {
  495. scope.setFingerprint(['trace-view-scroll-to-node-error']);
  496. scope.captureMessage('Failed to scroll to node in trace tree');
  497. });
  498. }
  499. return;
  500. }
  501. // At load time, we want to scroll the row into view, but we need to wait for the view
  502. // to initialize before we can do that. We listen for the 'initialize virtualized list' and scroll
  503. // to the row in the view if it is not in view yet. If its in the view, then scroll to it immediately.
  504. traceScheduler.once('initialize virtualized list', () => {
  505. function onTargetRowMeasure() {
  506. if (!node || !viewManager.row_measurer.cache.has(node)) {
  507. return;
  508. }
  509. viewManager.row_measurer.off('row measure end', onTargetRowMeasure);
  510. if (viewManager.isOutsideOfView(node)) {
  511. viewManager.scrollRowIntoViewHorizontally(node!, 0, 48, 'measured');
  512. }
  513. }
  514. viewManager.scrollToRow(index, 'center');
  515. viewManager.row_measurer.on('row measure end', onTargetRowMeasure);
  516. previouslyScrolledToNodeRef.current = node;
  517. setRowAsFocused(node, null, traceStateRef.current.search.resultsLookup, index);
  518. traceDispatch({
  519. type: 'set roving index',
  520. node: node,
  521. index: index,
  522. action_source: 'load',
  523. });
  524. });
  525. }, [
  526. setRowAsFocused,
  527. traceDispatch,
  528. onTraceSearch,
  529. viewManager,
  530. traceScheduler,
  531. scrollQueueRef,
  532. props.tree,
  533. props.organization,
  534. ]);
  535. // Setup the middleware for the trace reducer
  536. useLayoutEffect(() => {
  537. const beforeTraceNextStateDispatch: DispatchingReducerMiddleware<
  538. typeof TraceReducer
  539. >['before next state'] = (prevState, nextState, action) => {
  540. // This effect is responsible fo syncing the keyboard interactions with the search results,
  541. // we observe the changes to the roving tab index and search results and react by syncing the state.
  542. const {node: nextRovingNode, index: nextRovingTabIndex} = nextState.rovingTabIndex;
  543. const {resultIndex: nextSearchResultIndex} = nextState.search;
  544. if (
  545. nextRovingNode &&
  546. action.type === 'set roving index' &&
  547. action.action_source !== 'click' &&
  548. typeof nextRovingTabIndex === 'number' &&
  549. prevState.rovingTabIndex.node !== nextRovingNode
  550. ) {
  551. // When the roving tabIndex updates mark the node as focused and sync search results
  552. setRowAsFocused(
  553. nextRovingNode,
  554. null,
  555. nextState.search.resultsLookup,
  556. nextRovingTabIndex
  557. );
  558. if (action.type === 'set roving index' && action.action_source === 'keyboard') {
  559. scrollRowIntoView(nextRovingNode, nextRovingTabIndex, undefined);
  560. }
  561. if (nextState.search.resultsLookup.has(nextRovingNode)) {
  562. const idx = nextState.search.resultsLookup.get(nextRovingNode)!;
  563. traceDispatch({
  564. type: 'set search iterator index',
  565. resultIndex: nextRovingTabIndex,
  566. resultIteratorIndex: idx,
  567. });
  568. } else if (nextState.search.resultIteratorIndex !== null) {
  569. traceDispatch({type: 'clear search iterator index'});
  570. }
  571. } else if (
  572. typeof nextSearchResultIndex === 'number' &&
  573. prevState.search.resultIndex !== nextSearchResultIndex &&
  574. action.type !== 'set search iterator index'
  575. ) {
  576. // If the search result index changes, mark the node as focused and scroll it into view
  577. const nextNode = props.tree.list[nextSearchResultIndex];
  578. setRowAsFocused(
  579. nextNode,
  580. null,
  581. nextState.search.resultsLookup,
  582. nextSearchResultIndex
  583. );
  584. scrollRowIntoView(nextNode, nextSearchResultIndex, 'center if outside');
  585. }
  586. };
  587. traceStateEmitter.on('before next state', beforeTraceNextStateDispatch);
  588. return () => {
  589. traceStateEmitter.off('before next state', beforeTraceNextStateDispatch);
  590. };
  591. }, [
  592. props.tree,
  593. onTraceSearch,
  594. traceStateEmitter,
  595. traceDispatch,
  596. setRowAsFocused,
  597. scrollRowIntoView,
  598. ]);
  599. const [traceGridRef, setTraceGridRef] = useState<HTMLElement | null>(null);
  600. // Memoized because it requires tree traversal
  601. const shape = useMemo(() => props.tree.shape, [props.tree]);
  602. useTraceTimelineChangeSync({
  603. tree: props.tree,
  604. traceScheduler,
  605. });
  606. useTraceSpaceListeners({
  607. view: traceView,
  608. viewManager,
  609. traceScheduler,
  610. });
  611. useDividerResizeSync(traceScheduler);
  612. const onLoadScrollStatus = useTraceOnLoad({
  613. onTraceLoad,
  614. pathToNodeOrEventId: scrollQueueRef.current,
  615. tree: props.tree,
  616. });
  617. // Sync part of the state with the URL
  618. const traceQueryStateSync = useMemo(() => {
  619. return {search: traceState.search.query};
  620. }, [traceState.search.query]);
  621. useTraceQueryParamStateSync(traceQueryStateSync);
  622. const onAutogroupChange = useCallback(() => {
  623. const value = !traceState.preferences.autogroup.parent;
  624. if (!value) {
  625. let removeCount = 0;
  626. removeCount += TraceTree.RemoveSiblingAutogroupNodes(props.tree.root);
  627. removeCount += TraceTree.RemoveDirectChildrenAutogroupNodes(props.tree.root);
  628. addSuccessMessage(
  629. removeCount > 0
  630. ? tct('Autogrouping disabled, removed [count] autogroup spans', {
  631. count: removeCount,
  632. })
  633. : t('Autogrouping disabled')
  634. );
  635. } else {
  636. let autogroupCount = 0;
  637. autogroupCount += TraceTree.AutogroupSiblingSpanNodes(props.tree.root);
  638. autogroupCount += TraceTree.AutogroupDirectChildrenSpanNodes(props.tree.root);
  639. addSuccessMessage(
  640. autogroupCount > 0
  641. ? tct('Autogrouping enabled, detected [count] autogrouping spans', {
  642. count: autogroupCount,
  643. })
  644. : t('Autogrouping enabled')
  645. );
  646. }
  647. traceAnalytics.trackAutogroupingPreferenceChange(props.organization, value);
  648. props.tree.rebuild();
  649. traceDispatch({
  650. type: 'set autogrouping',
  651. payload: value,
  652. });
  653. }, [traceDispatch, traceState.preferences.autogroup, props.tree, props.organization]);
  654. const onMissingInstrumentationChange = useCallback(() => {
  655. const value = !traceState.preferences.missing_instrumentation;
  656. if (!value) {
  657. const removeCount = TraceTree.RemoveMissingInstrumentationNodes(props.tree.root);
  658. addSuccessMessage(
  659. removeCount > 0
  660. ? tct(
  661. 'Missing instrumentation disabled, removed [count] missing instrumentation spans',
  662. {
  663. count: removeCount,
  664. }
  665. )
  666. : t('Missing instrumentation disabled')
  667. );
  668. } else {
  669. const missingInstrumentationCount = TraceTree.DetectMissingInstrumentation(
  670. props.tree.root
  671. );
  672. addSuccessMessage(
  673. missingInstrumentationCount > 0
  674. ? tct(
  675. 'Missing instrumentation enabled, found [count] missing instrumentation spans',
  676. {
  677. count: missingInstrumentationCount,
  678. }
  679. )
  680. : t('Missing instrumentation enabled')
  681. );
  682. }
  683. traceAnalytics.trackMissingInstrumentationPreferenceChange(props.organization, value);
  684. props.tree.rebuild();
  685. traceDispatch({
  686. type: 'set missing instrumentation',
  687. payload: value,
  688. });
  689. }, [
  690. traceDispatch,
  691. traceState.preferences.missing_instrumentation,
  692. props.tree,
  693. props.organization,
  694. ]);
  695. return (
  696. <Fragment>
  697. <TraceTypeWarnings
  698. tree={props.tree}
  699. traceSlug={props.traceSlug}
  700. organization={organization}
  701. />
  702. <TraceToolbar>
  703. <TraceSearchInput onTraceSearch={onTraceSearch} organization={organization} />
  704. <TraceResetZoomButton
  705. viewManager={viewManager}
  706. organization={props.organization}
  707. />
  708. <TraceShortcuts />
  709. <TracePreferencesDropdown
  710. autogroup={
  711. traceState.preferences.autogroup.parent &&
  712. traceState.preferences.autogroup.sibling
  713. }
  714. missingInstrumentation={traceState.preferences.missing_instrumentation}
  715. onAutogroupChange={onAutogroupChange}
  716. onMissingInstrumentationChange={onMissingInstrumentationChange}
  717. />
  718. </TraceToolbar>
  719. <TraceGrid layout={traceState.preferences.layout} ref={setTraceGridRef}>
  720. <Trace
  721. trace={props.tree}
  722. rerender={rerender}
  723. trace_id={props.traceSlug}
  724. onRowClick={onRowClick}
  725. onTraceSearch={onTraceSearch}
  726. previouslyFocusedNodeRef={previouslyFocusedNodeRef}
  727. manager={viewManager}
  728. scheduler={traceScheduler}
  729. forceRerender={forceRender}
  730. isLoading={props.tree.type === 'loading' || onLoadScrollStatus === 'pending'}
  731. />
  732. {props.tree.type === 'loading' || onLoadScrollStatus === 'pending' ? (
  733. <TraceWaterfallState.Loading />
  734. ) : props.tree.type === 'error' ? (
  735. <TraceWaterfallState.Error />
  736. ) : props.tree.type === 'empty' ? (
  737. <TraceWaterfallState.Empty />
  738. ) : null}
  739. <TraceDrawer
  740. replay={props.replay}
  741. meta={props.meta}
  742. traceType={shape}
  743. trace={props.tree}
  744. traceGridRef={traceGridRef}
  745. manager={viewManager}
  746. scheduler={traceScheduler}
  747. onTabScrollToNode={onTabScrollToNode}
  748. onScrollToNode={onScrollToNode}
  749. rootEventResults={props.rootEvent}
  750. traceEventView={props.traceEventView}
  751. />
  752. </TraceGrid>
  753. </Fragment>
  754. );
  755. }
  756. const TraceToolbar = styled('div')`
  757. flex-grow: 0;
  758. display: grid;
  759. grid-template-columns: 1fr min-content min-content min-content;
  760. gap: ${space(1)};
  761. `;
  762. export const TraceGrid = styled('div')<{
  763. layout: 'drawer bottom' | 'drawer left' | 'drawer right';
  764. }>`
  765. --info: ${p => p.theme.purple400};
  766. --warning: ${p => p.theme.yellow300};
  767. --debug: ${p => p.theme.blue300};
  768. --error: ${p => p.theme.error};
  769. --fatal: ${p => p.theme.error};
  770. --default: ${p => p.theme.gray300};
  771. --unknown: ${p => p.theme.gray300};
  772. --profile: ${p => p.theme.purple300};
  773. --autogrouped: ${p => p.theme.blue300};
  774. --performance-issue: ${p => p.theme.blue300};
  775. border: 1px solid ${p => p.theme.border};
  776. flex: 1 1 100%;
  777. display: grid;
  778. border-radius: ${p => p.theme.borderRadius};
  779. overflow: hidden;
  780. position: relative;
  781. /* false positive for grid layout */
  782. /* stylelint-disable */
  783. grid-template-areas: ${p =>
  784. p.layout === 'drawer bottom'
  785. ? `
  786. 'trace'
  787. 'drawer'
  788. `
  789. : p.layout === 'drawer left'
  790. ? `'drawer trace'`
  791. : `'trace drawer'`};
  792. grid-template-columns: ${p =>
  793. p.layout === 'drawer bottom'
  794. ? '1fr'
  795. : p.layout === 'drawer left'
  796. ? 'min-content 1fr'
  797. : '1fr min-content'};
  798. grid-template-rows: 1fr auto;
  799. `;