index.tsx 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191
  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 {Button} from 'sentry/components/button';
  17. import useFeedbackWidget from 'sentry/components/feedback/widget/useFeedbackWidget';
  18. import LoadingIndicator from 'sentry/components/loadingIndicator';
  19. import NoProjectMessage from 'sentry/components/noProjectMessage';
  20. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  21. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  22. import {ALL_ACCESS_PROJECTS} from 'sentry/constants/pageFilters';
  23. import {t} from 'sentry/locale';
  24. import {space} from 'sentry/styles/space';
  25. import type {EventTransaction} from 'sentry/types/event';
  26. import type {Organization} from 'sentry/types/organization';
  27. import type {Project} from 'sentry/types/project';
  28. import {trackAnalytics} from 'sentry/utils/analytics';
  29. import {browserHistory} from 'sentry/utils/browserHistory';
  30. import EventView from 'sentry/utils/discover/eventView';
  31. import type {TraceSplitResults} from 'sentry/utils/performance/quickTrace/types';
  32. import {
  33. cancelAnimationTimeout,
  34. requestAnimationTimeout,
  35. } from 'sentry/utils/profiling/hooks/useVirtualizedTree/virtualizedTreeUtils';
  36. import type {UseApiQueryResult} from 'sentry/utils/queryClient';
  37. import {decodeScalar} from 'sentry/utils/queryString';
  38. import type RequestError from 'sentry/utils/requestError/requestError';
  39. import {capitalize} from 'sentry/utils/string/capitalize';
  40. import useApi from 'sentry/utils/useApi';
  41. import type {DispatchingReducerMiddleware} from 'sentry/utils/useDispatchingReducer';
  42. import useOrganization from 'sentry/utils/useOrganization';
  43. import usePageFilters from 'sentry/utils/usePageFilters';
  44. import {useParams} from 'sentry/utils/useParams';
  45. import useProjects from 'sentry/utils/useProjects';
  46. import {traceAnalytics} from 'sentry/views/performance/newTraceDetails/traceAnalytics';
  47. import {
  48. TraceEventPriority,
  49. type TraceEvents,
  50. TraceScheduler,
  51. } from 'sentry/views/performance/newTraceDetails/traceRenderers/traceScheduler';
  52. import {TraceView as TraceViewModel} from 'sentry/views/performance/newTraceDetails/traceRenderers/traceView';
  53. import {
  54. type ViewManagerScrollAnchor,
  55. VirtualizedViewManager,
  56. } from 'sentry/views/performance/newTraceDetails/traceRenderers/virtualizedViewManager';
  57. import {
  58. searchInTraceTreeText,
  59. searchInTraceTreeTokens,
  60. } from 'sentry/views/performance/newTraceDetails/traceSearch/traceSearchEvaluator';
  61. import {parseTraceSearch} from 'sentry/views/performance/newTraceDetails/traceSearch/traceTokenConverter';
  62. import {TraceShortcuts} from 'sentry/views/performance/newTraceDetails/traceShortcutsModal';
  63. import {
  64. TraceStateProvider,
  65. useTraceState,
  66. useTraceStateDispatch,
  67. useTraceStateEmitter,
  68. } from 'sentry/views/performance/newTraceDetails/traceState/traceStateProvider';
  69. import type {ReplayTrace} from 'sentry/views/replays/detail/trace/useReplayTraces';
  70. import type {ReplayRecord} from 'sentry/views/replays/types';
  71. import {useTrace} from './traceApi/useTrace';
  72. import {type TraceMetaQueryResults, useTraceMeta} from './traceApi/useTraceMeta';
  73. import {useTraceRootEvent} from './traceApi/useTraceRootEvent';
  74. import {TraceDrawer} from './traceDrawer/traceDrawer';
  75. import {
  76. traceNodeAdjacentAnalyticsProperties,
  77. traceNodeAnalyticsName,
  78. TraceTree,
  79. type TraceTreeNode,
  80. } from './traceModels/traceTree';
  81. import {TraceSearchInput} from './traceSearch/traceSearchInput';
  82. import {
  83. DEFAULT_TRACE_VIEW_PREFERENCES,
  84. loadTraceViewPreferences,
  85. } from './traceState/tracePreferences';
  86. import {isTraceNode} from './guards';
  87. import {Trace} from './trace';
  88. import {TraceMetadataHeader} from './traceMetadataHeader';
  89. import type {TraceReducer, TraceReducerState} from './traceState';
  90. import {TraceType} from './traceType';
  91. import {useTraceQueryParamStateSync} from './useTraceQueryParamStateSync';
  92. function decodeScrollQueue(maybePath: unknown): TraceTree.NodePath[] | null {
  93. if (Array.isArray(maybePath)) {
  94. return maybePath;
  95. }
  96. if (typeof maybePath === 'string') {
  97. return [maybePath as TraceTree.NodePath];
  98. }
  99. return null;
  100. }
  101. function logTraceMetadata(
  102. tree: TraceTree,
  103. projects: Project[],
  104. organization: Organization
  105. ) {
  106. switch (tree.shape) {
  107. case TraceType.BROKEN_SUBTRACES:
  108. case TraceType.EMPTY_TRACE:
  109. case TraceType.MULTIPLE_ROOTS:
  110. case TraceType.ONE_ROOT:
  111. case TraceType.NO_ROOT:
  112. case TraceType.ONLY_ERRORS:
  113. case TraceType.BROWSER_MULTIPLE_ROOTS:
  114. traceAnalytics.trackTraceMetadata(tree, projects, organization);
  115. break;
  116. default: {
  117. Sentry.captureMessage('Unknown trace type');
  118. }
  119. }
  120. }
  121. export function TraceView() {
  122. const params = useParams<{traceSlug?: string}>();
  123. const organization = useOrganization();
  124. const traceSlug = useMemo(() => {
  125. const slug = params.traceSlug?.trim() ?? '';
  126. // null and undefined are not valid trace slugs, but they can be passed
  127. // in the URL and need to check for their string coerced values.
  128. if (!slug || slug === 'null' || slug === 'undefined') {
  129. Sentry.withScope(scope => {
  130. scope.setFingerprint(['trace-null-slug']);
  131. Sentry.captureMessage(`Trace slug is empty`);
  132. });
  133. }
  134. return slug;
  135. }, [params.traceSlug]);
  136. const queryParams = useMemo(() => {
  137. const normalizedParams = normalizeDateTimeParams(qs.parse(location.search), {
  138. allowAbsolutePageDatetime: true,
  139. });
  140. const start = decodeScalar(normalizedParams.start);
  141. const timestamp: string | undefined = decodeScalar(normalizedParams.timestamp);
  142. const end = decodeScalar(normalizedParams.end);
  143. const statsPeriod = decodeScalar(normalizedParams.statsPeriod);
  144. const numberTimestamp = timestamp ? Number(timestamp) : undefined;
  145. return {start, end, statsPeriod, timestamp: numberTimestamp, useSpans: 1};
  146. }, []);
  147. const traceEventView = useMemo(() => {
  148. const {start, end, statsPeriod, timestamp} = queryParams;
  149. let startTimeStamp = start;
  150. let endTimeStamp = end;
  151. // If timestamp exists in the query params, we want to use it to set the start and end time
  152. // with a buffer of 1.5 days, for retrieving events belonging to the trace.
  153. if (typeof timestamp === 'number') {
  154. const buffer = 36 * 60 * 60 * 1000; // 1.5 days in milliseconds
  155. const dateFromTimestamp = new Date(timestamp * 1000);
  156. startTimeStamp = new Date(dateFromTimestamp.getTime() - buffer).toISOString();
  157. endTimeStamp = new Date(dateFromTimestamp.getTime() + buffer).toISOString();
  158. }
  159. return EventView.fromSavedQuery({
  160. id: undefined,
  161. name: `Events with Trace ID ${traceSlug}`,
  162. fields: ['title', 'event.type', 'project', 'timestamp'],
  163. orderby: '-timestamp',
  164. query: `trace:${traceSlug}`,
  165. projects: [ALL_ACCESS_PROJECTS],
  166. version: 2,
  167. start: startTimeStamp,
  168. end: endTimeStamp,
  169. range: !(startTimeStamp || endTimeStamp) ? statsPeriod : undefined,
  170. });
  171. }, [queryParams, traceSlug]);
  172. const meta = useTraceMeta([traceSlug]);
  173. const preferences = useMemo(
  174. () =>
  175. loadTraceViewPreferences('trace-view-preferences') ||
  176. DEFAULT_TRACE_VIEW_PREFERENCES,
  177. []
  178. );
  179. const trace = useTrace({traceSlug, timestamp: queryParams.timestamp});
  180. const rootEvent = useTraceRootEvent(trace.data ?? null);
  181. return (
  182. <SentryDocumentTitle
  183. title={`${t('Trace Details')} - ${traceSlug}`}
  184. orgSlug={organization.slug}
  185. >
  186. <TraceStateProvider
  187. initialPreferences={preferences}
  188. preferencesStorageKey="trace-view-preferences"
  189. >
  190. <NoProjectMessage organization={organization}>
  191. <TraceExternalLayout>
  192. <TraceMetadataHeader
  193. organization={organization}
  194. traceSlug={traceSlug}
  195. traceEventView={traceEventView}
  196. />
  197. <TraceInnerLayout>
  198. <TraceViewWaterfall
  199. traceSlug={traceSlug}
  200. trace={trace.data ?? null}
  201. status={trace.status}
  202. organization={organization}
  203. rootEvent={rootEvent}
  204. traceEventView={traceEventView}
  205. metaResults={meta}
  206. replayRecord={null}
  207. source="performance"
  208. />
  209. </TraceInnerLayout>
  210. </TraceExternalLayout>
  211. </NoProjectMessage>
  212. </TraceStateProvider>
  213. </SentryDocumentTitle>
  214. );
  215. }
  216. const TRACE_TAB: TraceReducerState['tabs']['tabs'][0] = {
  217. node: 'trace',
  218. label: t('Trace'),
  219. };
  220. const VITALS_TAB: TraceReducerState['tabs']['tabs'][0] = {
  221. node: 'vitals',
  222. label: t('Vitals'),
  223. };
  224. type TraceViewWaterfallProps = {
  225. metaResults: TraceMetaQueryResults;
  226. organization: Organization;
  227. replayRecord: ReplayRecord | null;
  228. rootEvent: UseApiQueryResult<EventTransaction, RequestError>;
  229. source: string;
  230. status: UseApiQueryResult<any, any>['status'];
  231. trace: TraceSplitResults<TraceTree.Transaction> | null;
  232. traceEventView: EventView;
  233. traceSlug: string | undefined;
  234. replayTraces?: ReplayTrace[];
  235. };
  236. export function TraceViewWaterfall(props: TraceViewWaterfallProps) {
  237. const api = useApi();
  238. const {projects} = useProjects();
  239. const organization = useOrganization();
  240. const loadingTraceRef = useRef<TraceTree | null>(null);
  241. const [forceRender, rerender] = useReducer(x => (x + 1) % Number.MAX_SAFE_INTEGER, 0);
  242. const traceState = useTraceState();
  243. const traceDispatch = useTraceStateDispatch();
  244. const traceStateEmitter = useTraceStateEmitter();
  245. const filters = usePageFilters();
  246. const traceScheduler = useMemo(() => new TraceScheduler(), []);
  247. const traceView = useMemo(() => new TraceViewModel(), []);
  248. const forceRerender = useCallback(() => {
  249. flushSync(rerender);
  250. }, []);
  251. useEffect(() => {
  252. trackAnalytics('performance_views.trace_view_v1_page_load', {
  253. organization: props.organization,
  254. source: props.source,
  255. });
  256. }, [props.organization, props.source]);
  257. const initializedRef = useRef(false);
  258. const scrollQueueRef = useRef<
  259. {eventId?: string; path?: TraceTree.NodePath[]} | null | undefined
  260. >(undefined);
  261. if (scrollQueueRef.current === undefined) {
  262. const queryParams = qs.parse(location.search);
  263. const maybeQueue = decodeScrollQueue(queryParams.node);
  264. if (maybeQueue || queryParams.eventId) {
  265. scrollQueueRef.current = {
  266. eventId: queryParams.eventId as string,
  267. path: maybeQueue as TraceTreeNode<TraceTree.NodeValue>['path'],
  268. };
  269. } else {
  270. scrollQueueRef.current = null;
  271. }
  272. }
  273. const previouslyFocusedNodeRef = useRef<TraceTreeNode<TraceTree.NodeValue> | null>(
  274. null
  275. );
  276. const previouslyScrolledToNodeRef = useRef<TraceTreeNode<TraceTree.NodeValue> | null>(
  277. null
  278. );
  279. const tree = useMemo(() => {
  280. if (props.status === 'error') {
  281. const errorTree = TraceTree.Error(
  282. {
  283. project_slug: projects?.[0]?.slug ?? '',
  284. event_id: props.traceSlug,
  285. },
  286. loadingTraceRef.current
  287. );
  288. return errorTree;
  289. }
  290. if (
  291. props.trace?.transactions.length === 0 &&
  292. props.trace?.orphan_errors.length === 0
  293. ) {
  294. return TraceTree.Empty();
  295. }
  296. if (props.status === 'loading') {
  297. const loadingTrace =
  298. loadingTraceRef.current ??
  299. TraceTree.Loading(
  300. {
  301. project_slug: projects?.[0]?.slug ?? '',
  302. event_id: props.traceSlug,
  303. },
  304. loadingTraceRef.current
  305. );
  306. loadingTraceRef.current = loadingTrace;
  307. return loadingTrace;
  308. }
  309. if (props.trace) {
  310. return TraceTree.FromTrace(props.trace, props.replayRecord);
  311. }
  312. throw new Error('Invalid trace state');
  313. }, [props.traceSlug, props.trace, props.status, projects, props.replayRecord]);
  314. useEffect(() => {
  315. if (!props.replayTraces?.length || tree.type !== 'trace') {
  316. return undefined;
  317. }
  318. const cleanup = tree.fetchAdditionalTraces({
  319. api,
  320. filters,
  321. replayTraces: props.replayTraces,
  322. organization: props.organization,
  323. urlParams: qs.parse(location.search),
  324. rerender: forceRerender,
  325. });
  326. return () => cleanup();
  327. // eslint-disable-next-line react-hooks/exhaustive-deps
  328. }, [tree, props.replayTraces]);
  329. // Assign the trace state to a ref so we can access it without re-rendering
  330. const traceStateRef = useRef<TraceReducerState>(traceState);
  331. traceStateRef.current = traceState;
  332. // Initialize the view manager right after the state reducer
  333. const viewManager = useMemo(() => {
  334. return new VirtualizedViewManager(
  335. {
  336. list: {width: traceState.preferences.list.width},
  337. span_list: {width: 1 - traceState.preferences.list.width},
  338. },
  339. traceScheduler,
  340. traceView
  341. );
  342. // We only care about initial state when we initialize the view manager
  343. // eslint-disable-next-line react-hooks/exhaustive-deps
  344. }, []);
  345. useLayoutEffect(() => {
  346. const onTraceViewChange: TraceEvents['set trace view'] = view => {
  347. traceView.setTraceView(view);
  348. viewManager.enqueueFOVQueryParamSync(traceView);
  349. };
  350. const onPhysicalSpaceChange: TraceEvents['set container physical space'] =
  351. container => {
  352. traceView.setTracePhysicalSpace(container, [
  353. 0,
  354. 0,
  355. container[2] * viewManager.columns.span_list.width,
  356. container[3],
  357. ]);
  358. };
  359. const onTraceSpaceChange: TraceEvents['initialize trace space'] = view => {
  360. traceView.setTraceSpace(view);
  361. };
  362. // These handlers have high priority because they are responsible for
  363. // updating the view coordinates. If we update them first, then any components downstream
  364. // that rely on the view coordinates will be in sync with the view.
  365. traceScheduler.on('set trace view', onTraceViewChange, TraceEventPriority.HIGH);
  366. traceScheduler.on('set trace space', onTraceSpaceChange, TraceEventPriority.HIGH);
  367. traceScheduler.on(
  368. 'set container physical space',
  369. onPhysicalSpaceChange,
  370. TraceEventPriority.HIGH
  371. );
  372. traceScheduler.on(
  373. 'initialize trace space',
  374. onTraceSpaceChange,
  375. TraceEventPriority.HIGH
  376. );
  377. return () => {
  378. traceScheduler.off('set trace view', onTraceViewChange);
  379. traceScheduler.off('set trace space', onTraceSpaceChange);
  380. traceScheduler.off('set container physical space', onPhysicalSpaceChange);
  381. traceScheduler.off('initialize trace space', onTraceSpaceChange);
  382. };
  383. }, [traceScheduler, traceView, viewManager]);
  384. // Initialize the tabs reducer when the tree initializes
  385. useLayoutEffect(() => {
  386. return traceDispatch({
  387. type: 'set roving count',
  388. items: tree.list.length - 1,
  389. });
  390. }, [tree.list.length, traceDispatch]);
  391. // Initialize the tabs reducer when the tree initializes
  392. useLayoutEffect(() => {
  393. if (tree.type !== 'trace') {
  394. return;
  395. }
  396. const newTabs = [TRACE_TAB];
  397. if (tree.vitals.size > 0) {
  398. const types = Array.from(tree.vital_types.values());
  399. const label = types.length > 1 ? t('Vitals') : capitalize(types[0]) + ' Vitals';
  400. newTabs.push({
  401. ...VITALS_TAB,
  402. label,
  403. });
  404. }
  405. if (tree.profiled_events.size > 0) {
  406. newTabs.push({
  407. node: 'profiles',
  408. label: 'Profiles',
  409. });
  410. }
  411. traceDispatch({
  412. type: 'initialize tabs reducer',
  413. payload: {
  414. current_tab: traceStateRef?.current?.tabs?.tabs?.[0],
  415. tabs: newTabs,
  416. last_clicked_tab: null,
  417. },
  418. });
  419. // We only want to update the tabs when the tree changes
  420. // eslint-disable-next-line react-hooks/exhaustive-deps
  421. }, [tree]);
  422. const searchingRaf = useRef<{id: number | null} | null>(null);
  423. const onTraceSearch = useCallback(
  424. (
  425. query: string,
  426. activeNode: TraceTreeNode<TraceTree.NodeValue> | null,
  427. behavior: 'track result' | 'persist'
  428. ) => {
  429. if (searchingRaf.current?.id) {
  430. window.cancelAnimationFrame(searchingRaf.current.id);
  431. }
  432. function done([matches, lookup, activeNodeSearchResult]) {
  433. // If the previous node is still in the results set, we want to keep it
  434. if (activeNodeSearchResult) {
  435. traceDispatch({
  436. type: 'set results',
  437. results: matches,
  438. resultsLookup: lookup,
  439. resultIteratorIndex: activeNodeSearchResult?.resultIteratorIndex,
  440. resultIndex: activeNodeSearchResult?.resultIndex,
  441. previousNode: activeNodeSearchResult,
  442. node: activeNode,
  443. });
  444. return;
  445. }
  446. if (activeNode && behavior === 'persist') {
  447. traceDispatch({
  448. type: 'set results',
  449. results: matches,
  450. resultsLookup: lookup,
  451. resultIteratorIndex: undefined,
  452. resultIndex: undefined,
  453. previousNode: activeNodeSearchResult,
  454. node: activeNode,
  455. });
  456. return;
  457. }
  458. const resultIndex: number | undefined = matches?.[0]?.index;
  459. const resultIteratorIndex: number | undefined = matches?.[0] ? 0 : undefined;
  460. const node: TraceTreeNode<TraceTree.NodeValue> | null = matches?.[0]?.value;
  461. traceDispatch({
  462. type: 'set results',
  463. results: matches,
  464. resultsLookup: lookup,
  465. resultIteratorIndex: resultIteratorIndex,
  466. resultIndex: resultIndex,
  467. previousNode: activeNodeSearchResult,
  468. node,
  469. });
  470. }
  471. const tokens = parseTraceSearch(query);
  472. if (tokens) {
  473. searchingRaf.current = searchInTraceTreeTokens(tree, tokens, activeNode, done);
  474. } else {
  475. searchingRaf.current = searchInTraceTreeText(tree, query, activeNode, done);
  476. }
  477. },
  478. [traceDispatch, tree]
  479. );
  480. // We need to heavily debounce query string updates because the rest of the app is so slow
  481. // to rerender that it causes the search to drop frames on every keystroke...
  482. const QUERY_STRING_STATE_DEBOUNCE = 300;
  483. const queryStringAnimationTimeoutRef = useRef<{id: number} | null>(null);
  484. const setRowAsFocused = useCallback(
  485. (
  486. node: TraceTreeNode<TraceTree.NodeValue> | null,
  487. event: React.MouseEvent<HTMLElement> | null,
  488. resultsLookup: Map<TraceTreeNode<TraceTree.NodeValue>, number>,
  489. index: number | null,
  490. debounce: number = QUERY_STRING_STATE_DEBOUNCE
  491. ) => {
  492. // sync query string with the clicked node
  493. if (node) {
  494. if (queryStringAnimationTimeoutRef.current) {
  495. cancelAnimationTimeout(queryStringAnimationTimeoutRef.current);
  496. }
  497. queryStringAnimationTimeoutRef.current = requestAnimationTimeout(() => {
  498. const currentQueryStringPath = qs.parse(location.search).node;
  499. const nextNodePath = node.path;
  500. // Updating the query string with the same path is problematic because it causes
  501. // the entire sentry app to rerender, which is enough to cause jank and drop frames
  502. if (JSON.stringify(currentQueryStringPath) === JSON.stringify(nextNodePath)) {
  503. return;
  504. }
  505. const {eventId: _eventId, ...query} = qs.parse(location.search);
  506. browserHistory.replace({
  507. pathname: location.pathname,
  508. query: {
  509. ...query,
  510. node: nextNodePath,
  511. },
  512. });
  513. queryStringAnimationTimeoutRef.current = null;
  514. }, debounce);
  515. if (resultsLookup.has(node) && typeof index === 'number') {
  516. traceDispatch({
  517. type: 'set search iterator index',
  518. resultIndex: index,
  519. resultIteratorIndex: resultsLookup.get(node)!,
  520. });
  521. }
  522. if (isTraceNode(node)) {
  523. traceDispatch({type: 'activate tab', payload: TRACE_TAB.node});
  524. return;
  525. }
  526. traceDispatch({
  527. type: 'activate tab',
  528. payload: node,
  529. pin_previous: event?.metaKey,
  530. });
  531. }
  532. },
  533. [traceDispatch]
  534. );
  535. const onRowClick = useCallback(
  536. (
  537. node: TraceTreeNode<TraceTree.NodeValue>,
  538. event: React.MouseEvent<HTMLElement>,
  539. index: number
  540. ) => {
  541. trackAnalytics('trace.trace_layout.span_row_click', {
  542. organization,
  543. num_children: node.children.length,
  544. type: traceNodeAnalyticsName(node),
  545. project_platform:
  546. projects.find(p => p.slug === node.metadata.project_slug)?.platform || 'other',
  547. ...traceNodeAdjacentAnalyticsProperties(node),
  548. });
  549. if (traceStateRef.current.preferences.drawer.minimized) {
  550. traceDispatch({type: 'minimize drawer', payload: false});
  551. }
  552. setRowAsFocused(node, event, traceStateRef.current.search.resultsLookup, null, 0);
  553. if (traceStateRef.current.search.resultsLookup.has(node)) {
  554. const idx = traceStateRef.current.search.resultsLookup.get(node)!;
  555. traceDispatch({
  556. type: 'set search iterator index',
  557. resultIndex: index,
  558. resultIteratorIndex: idx,
  559. });
  560. } else if (traceStateRef.current.search.resultIteratorIndex !== null) {
  561. traceDispatch({type: 'clear search iterator index'});
  562. }
  563. traceDispatch({
  564. type: 'set roving index',
  565. action_source: 'click',
  566. index,
  567. node,
  568. });
  569. },
  570. [setRowAsFocused, traceDispatch, organization, projects]
  571. );
  572. const scrollRowIntoView = useCallback(
  573. (
  574. node: TraceTreeNode<TraceTree.NodeValue>,
  575. index: number,
  576. anchor?: ViewManagerScrollAnchor,
  577. force?: boolean
  578. ) => {
  579. // Last node we scrolled to is the same as the node we want to scroll to
  580. if (previouslyScrolledToNodeRef.current === node && !force) {
  581. return;
  582. }
  583. // Always scroll to the row vertically
  584. viewManager.scrollToRow(index, anchor);
  585. if (viewManager.isOutsideOfView(node)) {
  586. viewManager.scrollRowIntoViewHorizontally(node, 0, 48, 'measured');
  587. }
  588. previouslyScrolledToNodeRef.current = node;
  589. },
  590. [viewManager]
  591. );
  592. const onTabScrollToNode = useCallback(
  593. (node: TraceTreeNode<TraceTree.NodeValue>) => {
  594. if (node === null) {
  595. return;
  596. }
  597. // We call expandToNode because we want to ensure that the node is
  598. // visible and may not have been collapsed/hidden by the user
  599. TraceTree.ExpandToPath(tree, node.path, forceRerender, {
  600. api,
  601. organization: props.organization,
  602. }).then(maybeNode => {
  603. if (maybeNode) {
  604. previouslyFocusedNodeRef.current = null;
  605. scrollRowIntoView(maybeNode.node, maybeNode.index, 'center if outside', true);
  606. traceDispatch({
  607. type: 'set roving index',
  608. node: maybeNode.node,
  609. index: maybeNode.index,
  610. action_source: 'click',
  611. });
  612. setRowAsFocused(
  613. maybeNode.node,
  614. null,
  615. traceStateRef.current.search.resultsLookup,
  616. null,
  617. 0
  618. );
  619. if (traceStateRef.current.search.resultsLookup.has(maybeNode.node)) {
  620. traceDispatch({
  621. type: 'set search iterator index',
  622. resultIndex: maybeNode.index,
  623. resultIteratorIndex: traceStateRef.current.search.resultsLookup.get(
  624. maybeNode.node
  625. )!,
  626. });
  627. } else if (traceStateRef.current.search.resultIteratorIndex !== null) {
  628. traceDispatch({type: 'clear search iterator index'});
  629. }
  630. }
  631. });
  632. },
  633. [
  634. api,
  635. props.organization,
  636. setRowAsFocused,
  637. scrollRowIntoView,
  638. tree,
  639. traceDispatch,
  640. forceRerender,
  641. ]
  642. );
  643. // Unlike onTabScrollToNode, this function does not set the node as the current
  644. // focused node, but rather scrolls the node into view and sets the roving index to the node.
  645. const onScrollToNode = useCallback(
  646. (node: TraceTreeNode<TraceTree.NodeValue>) => {
  647. TraceTree.ExpandToPath(tree, node.path, forceRerender, {
  648. api,
  649. organization: props.organization,
  650. }).then(maybeNode => {
  651. if (maybeNode) {
  652. previouslyFocusedNodeRef.current = null;
  653. scrollRowIntoView(maybeNode.node, maybeNode.index, 'center if outside', true);
  654. traceDispatch({
  655. type: 'set roving index',
  656. node: maybeNode.node,
  657. index: maybeNode.index,
  658. action_source: 'click',
  659. });
  660. if (traceStateRef.current.search.resultsLookup.has(maybeNode.node)) {
  661. traceDispatch({
  662. type: 'set search iterator index',
  663. resultIndex: maybeNode.index,
  664. resultIteratorIndex: traceStateRef.current.search.resultsLookup.get(
  665. maybeNode.node
  666. )!,
  667. });
  668. } else if (traceStateRef.current.search.resultIteratorIndex !== null) {
  669. traceDispatch({type: 'clear search iterator index'});
  670. }
  671. }
  672. });
  673. },
  674. [api, props.organization, scrollRowIntoView, tree, traceDispatch, forceRerender]
  675. );
  676. // Callback that is invoked when the trace loads and reaches its initialied state,
  677. // that is when the trace tree data and any data that the trace depends on is loaded,
  678. // but the trace is not yet rendered in the view.
  679. const onTraceLoad = useCallback(
  680. (
  681. _trace: TraceTree,
  682. nodeToScrollTo: TraceTreeNode<TraceTree.NodeValue> | null,
  683. indexOfNodeToScrollTo: number | null
  684. ) => {
  685. scrollQueueRef.current = null;
  686. const query = qs.parse(location.search);
  687. if (query.fov && typeof query.fov === 'string') {
  688. viewManager.maybeInitializeTraceViewFromQS(query.fov);
  689. }
  690. if (nodeToScrollTo !== null && indexOfNodeToScrollTo !== null) {
  691. // At load time, we want to scroll the row into view, but we need to wait for the view
  692. // to initialize before we can do that. We listen for the 'initialize virtualized list' and scroll
  693. // to the row in the view.
  694. traceScheduler.once('initialize virtualized list', () => {
  695. function onTargetRowMeasure() {
  696. if (!nodeToScrollTo || !viewManager.row_measurer.cache.has(nodeToScrollTo)) {
  697. return;
  698. }
  699. viewManager.row_measurer.off('row measure end', onTargetRowMeasure);
  700. if (viewManager.isOutsideOfView(nodeToScrollTo)) {
  701. viewManager.scrollRowIntoViewHorizontally(
  702. nodeToScrollTo!,
  703. 0,
  704. 48,
  705. 'measured'
  706. );
  707. }
  708. }
  709. viewManager.scrollToRow(indexOfNodeToScrollTo, 'center');
  710. viewManager.row_measurer.on('row measure end', onTargetRowMeasure);
  711. previouslyScrolledToNodeRef.current = nodeToScrollTo;
  712. setRowAsFocused(
  713. nodeToScrollTo,
  714. null,
  715. traceStateRef.current.search.resultsLookup,
  716. indexOfNodeToScrollTo
  717. );
  718. traceDispatch({
  719. type: 'set roving index',
  720. node: nodeToScrollTo,
  721. index: indexOfNodeToScrollTo,
  722. action_source: 'load',
  723. });
  724. });
  725. }
  726. if (traceStateRef.current.search.query) {
  727. onTraceSearch(traceStateRef.current.search.query, nodeToScrollTo, 'persist');
  728. }
  729. },
  730. [setRowAsFocused, traceDispatch, onTraceSearch, viewManager, traceScheduler]
  731. );
  732. // Setup the middleware for the trace reducer
  733. useLayoutEffect(() => {
  734. const beforeTraceNextStateDispatch: DispatchingReducerMiddleware<
  735. typeof TraceReducer
  736. >['before next state'] = (prevState, nextState, action) => {
  737. // This effect is responsible fo syncing the keyboard interactions with the search results,
  738. // we observe the changes to the roving tab index and search results and react by syncing the state.
  739. const {node: nextRovingNode, index: nextRovingTabIndex} = nextState.rovingTabIndex;
  740. const {resultIndex: nextSearchResultIndex} = nextState.search;
  741. if (
  742. nextRovingNode &&
  743. action.type === 'set roving index' &&
  744. action.action_source !== 'click' &&
  745. typeof nextRovingTabIndex === 'number' &&
  746. prevState.rovingTabIndex.node !== nextRovingNode
  747. ) {
  748. // When the roving tabIndex updates mark the node as focused and sync search results
  749. setRowAsFocused(
  750. nextRovingNode,
  751. null,
  752. nextState.search.resultsLookup,
  753. nextRovingTabIndex
  754. );
  755. if (action.type === 'set roving index' && action.action_source === 'keyboard') {
  756. scrollRowIntoView(nextRovingNode, nextRovingTabIndex, undefined);
  757. }
  758. if (nextState.search.resultsLookup.has(nextRovingNode)) {
  759. const idx = nextState.search.resultsLookup.get(nextRovingNode)!;
  760. traceDispatch({
  761. type: 'set search iterator index',
  762. resultIndex: nextRovingTabIndex,
  763. resultIteratorIndex: idx,
  764. });
  765. } else if (nextState.search.resultIteratorIndex !== null) {
  766. traceDispatch({type: 'clear search iterator index'});
  767. }
  768. } else if (
  769. typeof nextSearchResultIndex === 'number' &&
  770. prevState.search.resultIndex !== nextSearchResultIndex &&
  771. action.type !== 'set search iterator index'
  772. ) {
  773. // If the search result index changes, mark the node as focused and scroll it into view
  774. const nextNode = tree.list[nextSearchResultIndex];
  775. setRowAsFocused(
  776. nextNode,
  777. null,
  778. nextState.search.resultsLookup,
  779. nextSearchResultIndex
  780. );
  781. scrollRowIntoView(nextNode, nextSearchResultIndex, 'center if outside');
  782. }
  783. };
  784. traceStateEmitter.on('before next state', beforeTraceNextStateDispatch);
  785. return () => {
  786. traceStateEmitter.off('before next state', beforeTraceNextStateDispatch);
  787. };
  788. }, [
  789. tree,
  790. onTraceSearch,
  791. traceStateEmitter,
  792. traceDispatch,
  793. setRowAsFocused,
  794. scrollRowIntoView,
  795. ]);
  796. // Setup the middleware for the view manager and store the list width as a preference
  797. useLayoutEffect(() => {
  798. function onDividerResizeEnd(list_width: number) {
  799. traceDispatch({
  800. type: 'set list width',
  801. payload: list_width,
  802. });
  803. }
  804. traceScheduler.on('divider resize end', onDividerResizeEnd);
  805. return () => {
  806. traceScheduler.off('divider resize end', onDividerResizeEnd);
  807. };
  808. }, [traceScheduler, traceDispatch]);
  809. // Sync part of the state with the URL
  810. const traceQueryStateSync = useMemo(() => {
  811. return {search: traceState.search.query};
  812. }, [traceState.search.query]);
  813. useTraceQueryParamStateSync(traceQueryStateSync);
  814. const [traceGridRef, setTraceGridRef] = useState<HTMLElement | null>(null);
  815. // Memoized because it requires tree traversal
  816. const shape = useMemo(() => tree.shape, [tree]);
  817. useEffect(() => {
  818. if (tree.type !== 'trace') {
  819. return;
  820. }
  821. logTraceMetadata(tree, projects, props.organization);
  822. }, [tree, projects, props.organization]);
  823. useLayoutEffect(() => {
  824. if (tree.type !== 'trace') {
  825. return undefined;
  826. }
  827. traceScheduler.dispatch('initialize trace space', [
  828. tree.root.space[0],
  829. 0,
  830. tree.root.space[1],
  831. 1,
  832. ]);
  833. // Whenever the timeline changes, update the trace space and trigger a redraw
  834. const onTraceTimelineChange = (s: [number, number]) => {
  835. traceScheduler.dispatch('set trace space', [s[0], 0, s[1], 1]);
  836. };
  837. tree.on('trace timeline change', onTraceTimelineChange);
  838. return () => {
  839. tree.off('trace timeline change', onTraceTimelineChange);
  840. };
  841. }, [viewManager, traceScheduler, tree]);
  842. return (
  843. <Fragment>
  844. <TraceToolbar>
  845. <TraceSearchInput onTraceSearch={onTraceSearch} organization={organization} />
  846. <TraceResetZoomButton
  847. viewManager={viewManager}
  848. organization={props.organization}
  849. />
  850. <TraceShortcuts />
  851. </TraceToolbar>
  852. <TraceGrid layout={traceState.preferences.layout} ref={setTraceGridRef}>
  853. <Trace
  854. trace={tree}
  855. rerender={rerender}
  856. trace_id={props.traceSlug}
  857. scrollQueueRef={scrollQueueRef}
  858. initializedRef={initializedRef}
  859. onRowClick={onRowClick}
  860. onTraceLoad={onTraceLoad}
  861. onTraceSearch={onTraceSearch}
  862. previouslyFocusedNodeRef={previouslyFocusedNodeRef}
  863. manager={viewManager}
  864. scheduler={traceScheduler}
  865. forceRerender={forceRender}
  866. />
  867. {tree.type === 'error' ? (
  868. <TraceError />
  869. ) : tree.type === 'empty' ? (
  870. <TraceEmpty />
  871. ) : tree.type === 'loading' ||
  872. (scrollQueueRef.current && tree.type !== 'trace') ? (
  873. <TraceLoading />
  874. ) : null}
  875. <TraceDrawer
  876. replayRecord={props.replayRecord}
  877. metaResults={props.metaResults}
  878. traceType={shape}
  879. trace={tree}
  880. traceGridRef={traceGridRef}
  881. traces={props.trace ?? null}
  882. manager={viewManager}
  883. scheduler={traceScheduler}
  884. onTabScrollToNode={onTabScrollToNode}
  885. onScrollToNode={onScrollToNode}
  886. rootEventResults={props.rootEvent}
  887. traceEventView={props.traceEventView}
  888. />
  889. </TraceGrid>
  890. </Fragment>
  891. );
  892. }
  893. function TraceResetZoomButton(props: {
  894. organization: Organization;
  895. viewManager: VirtualizedViewManager;
  896. }) {
  897. const onResetZoom = useCallback(() => {
  898. traceAnalytics.trackResetZoom(props.organization);
  899. props.viewManager.resetZoom();
  900. }, [props.viewManager, props.organization]);
  901. return (
  902. <ResetZoomButton
  903. size="xs"
  904. onClick={onResetZoom}
  905. ref={props.viewManager.registerResetZoomRef}
  906. >
  907. {t('Reset Zoom')}
  908. </ResetZoomButton>
  909. );
  910. }
  911. const ResetZoomButton = styled(Button)`
  912. transition: opacity 0.2s 0.5s ease-in-out;
  913. &[disabled] {
  914. cursor: not-allowed;
  915. opacity: 0.65;
  916. }
  917. `;
  918. const TraceExternalLayout = styled('div')`
  919. display: flex;
  920. flex-direction: column;
  921. flex: 1 1 100%;
  922. ~ footer {
  923. display: none;
  924. }
  925. `;
  926. const TraceInnerLayout = styled('div')`
  927. display: flex;
  928. flex-direction: column;
  929. flex: 1 1 100%;
  930. padding: ${space(2)};
  931. background-color: ${p => p.theme.background};
  932. `;
  933. const TraceToolbar = styled('div')`
  934. flex-grow: 0;
  935. display: grid;
  936. grid-template-columns: 1fr min-content min-content;
  937. gap: ${space(1)};
  938. `;
  939. const TraceGrid = styled('div')<{
  940. layout: 'drawer bottom' | 'drawer left' | 'drawer right';
  941. }>`
  942. border: 1px solid ${p => p.theme.border};
  943. flex: 1 1 100%;
  944. display: grid;
  945. border-radius: ${p => p.theme.borderRadius};
  946. overflow: hidden;
  947. position: relative;
  948. /* false positive for grid layout */
  949. /* stylelint-disable */
  950. grid-template-areas: ${p =>
  951. p.layout === 'drawer bottom'
  952. ? `
  953. 'trace'
  954. 'drawer'
  955. `
  956. : p.layout === 'drawer left'
  957. ? `'drawer trace'`
  958. : `'trace drawer'`};
  959. grid-template-columns: ${p =>
  960. p.layout === 'drawer bottom'
  961. ? '1fr'
  962. : p.layout === 'drawer left'
  963. ? 'min-content 1fr'
  964. : '1fr min-content'};
  965. grid-template-rows: 1fr auto;
  966. `;
  967. const LoadingContainer = styled('div')<{animate: boolean; error?: boolean}>`
  968. display: flex;
  969. justify-content: center;
  970. align-items: center;
  971. flex-direction: column;
  972. left: 50%;
  973. top: 50%;
  974. position: absolute;
  975. height: auto;
  976. font-size: ${p => p.theme.fontSizeMedium};
  977. color: ${p => p.theme.gray300};
  978. z-index: 30;
  979. padding: 24px;
  980. background-color: ${p => p.theme.background};
  981. border-radius: ${p => p.theme.borderRadius};
  982. border: 1px solid ${p => p.theme.border};
  983. transform-origin: 50% 50%;
  984. transform: translate(-50%, -50%);
  985. animation: ${p =>
  986. p.animate
  987. ? `${p.error ? 'showLoadingContainerShake' : 'showLoadingContainer'} 300ms cubic-bezier(0.61, 1, 0.88, 1) forwards`
  988. : 'none'};
  989. @keyframes showLoadingContainer {
  990. from {
  991. opacity: 0.6;
  992. transform: scale(0.99) translate(-50%, -50%);
  993. }
  994. to {
  995. opacity: 1;
  996. transform: scale(1) translate(-50%, -50%);
  997. }
  998. }
  999. @keyframes showLoadingContainerShake {
  1000. 0% {
  1001. transform: translate(-50%, -50%);
  1002. }
  1003. 25% {
  1004. transform: translate(-51%, -50%);
  1005. }
  1006. 75% {
  1007. transform: translate(-49%, -50%);
  1008. }
  1009. 100% {
  1010. transform: translate(-50%, -50%);
  1011. }
  1012. }
  1013. `;
  1014. function TraceLoading() {
  1015. return (
  1016. // Dont flash the animation on load because it's annoying
  1017. <LoadingContainer animate={false}>
  1018. <NoMarginIndicator size={24}>
  1019. <div>{t('Assembling the trace')}</div>
  1020. </NoMarginIndicator>
  1021. </LoadingContainer>
  1022. );
  1023. }
  1024. function TraceError() {
  1025. const linkref = useRef<HTMLAnchorElement>(null);
  1026. const feedback = useFeedbackWidget({buttonRef: linkref});
  1027. useEffect(() => {
  1028. traceAnalytics.trackFailedToFetchTraceState();
  1029. }, []);
  1030. return (
  1031. <LoadingContainer animate error>
  1032. <div>{t('Ughhhhh, we failed to load your trace...')}</div>
  1033. <div>
  1034. {t('Seeing this often? Send us ')}
  1035. {feedback ? (
  1036. <a href="#" ref={linkref}>
  1037. {t('feedback')}
  1038. </a>
  1039. ) : (
  1040. <a href="mailto:support@sentry.io?subject=Trace%20fails%20to%20load">
  1041. {t('feedback')}
  1042. </a>
  1043. )}
  1044. </div>
  1045. </LoadingContainer>
  1046. );
  1047. }
  1048. function TraceEmpty() {
  1049. const linkref = useRef<HTMLAnchorElement>(null);
  1050. const feedback = useFeedbackWidget({buttonRef: linkref});
  1051. useEffect(() => {
  1052. traceAnalytics.trackEmptyTraceState();
  1053. }, []);
  1054. return (
  1055. <LoadingContainer animate>
  1056. <div>{t('This trace does not contain any data?!')}</div>
  1057. <div>
  1058. {t('Seeing this often? Send us ')}
  1059. {feedback ? (
  1060. <a href="#" ref={linkref}>
  1061. {t('feedback')}
  1062. </a>
  1063. ) : (
  1064. <a href="mailto:support@sentry.io?subject=Trace%20does%20not%20contain%20data">
  1065. {t('feedback')}
  1066. </a>
  1067. )}
  1068. </div>
  1069. </LoadingContainer>
  1070. );
  1071. }
  1072. const NoMarginIndicator = styled(LoadingIndicator)`
  1073. margin: 0;
  1074. `;