traceWaterfall.tsx 31 KB

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