index.tsx 38 KB

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