index.tsx 37 KB

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