traceWaterfall.tsx 30 KB

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