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. traceNodeAnalyticsName,
  75. TraceTree,
  76. type TraceTreeNode,
  77. } from './traceModels/traceTree';
  78. import {TraceSearchInput} from './traceSearch/traceSearchInput';
  79. import {
  80. DEFAULT_TRACE_VIEW_PREFERENCES,
  81. loadTraceViewPreferences,
  82. } from './traceState/tracePreferences';
  83. import {isTraceNode} from './guards';
  84. import {Trace} from './trace';
  85. import {TraceMetadataHeader} from './traceMetadataHeader';
  86. import type {TraceReducer, TraceReducerState} from './traceState';
  87. import {TraceType} from './traceType';
  88. import {TraceUXChangeAlert} from './traceUXChangeBanner';
  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. <TraceUXChangeAlert />
  194. <TraceMetadataHeader
  195. organization={organization}
  196. projectID={rootEvent?.data?.projectID ?? ''}
  197. title={rootEvent?.data?.title ?? ''}
  198. traceSlug={traceSlug}
  199. traceEventView={traceEventView}
  200. />
  201. <TraceInnerLayout>
  202. <TraceViewWaterfall
  203. status={trace.status}
  204. trace={trace.data ?? null}
  205. traceSlug={traceSlug}
  206. organization={organization}
  207. traceEventView={traceEventView}
  208. metaResults={meta}
  209. rootEvent={rootEvent}
  210. replayRecord={null}
  211. source="performance"
  212. />
  213. </TraceInnerLayout>
  214. </TraceExternalLayout>
  215. </NoProjectMessage>
  216. </TraceStateProvider>
  217. </SentryDocumentTitle>
  218. );
  219. }
  220. const TRACE_TAB: TraceReducerState['tabs']['tabs'][0] = {
  221. node: 'trace',
  222. label: t('Trace'),
  223. };
  224. const VITALS_TAB: TraceReducerState['tabs']['tabs'][0] = {
  225. node: 'vitals',
  226. label: t('Vitals'),
  227. };
  228. type TraceViewWaterfallProps = {
  229. metaResults: TraceMetaQueryResults;
  230. organization: Organization;
  231. replayRecord: ReplayRecord | null;
  232. rootEvent: UseApiQueryResult<EventTransaction, RequestError>;
  233. source: string;
  234. status: UseApiQueryResult<any, any>['status'];
  235. trace: TraceSplitResults<TraceTree.Transaction> | null;
  236. traceEventView: EventView;
  237. traceSlug: string;
  238. };
  239. export function TraceViewWaterfall(props: TraceViewWaterfallProps) {
  240. const api = useApi();
  241. const {projects} = useProjects();
  242. const organization = useOrganization();
  243. const loadingTraceRef = useRef<TraceTree | null>(null);
  244. const [forceRender, rerender] = useReducer(x => (x + 1) % Number.MAX_SAFE_INTEGER, 0);
  245. const traceState = useTraceState();
  246. const traceDispatch = useTraceStateDispatch();
  247. const traceStateEmitter = useTraceStateEmitter();
  248. const traceScheduler = useMemo(() => new TraceScheduler(), []);
  249. const traceView = useMemo(() => new TraceViewModel(), []);
  250. const forceRerender = useCallback(() => {
  251. flushSync(rerender);
  252. }, []);
  253. useEffect(() => {
  254. trackAnalytics('performance_views.trace_view_v1_page_load', {
  255. organization: props.organization,
  256. source: props.source,
  257. });
  258. }, [props.organization, props.source]);
  259. const initializedRef = useRef(false);
  260. const scrollQueueRef = useRef<
  261. {eventId?: string; path?: TraceTree.NodePath[]} | null | undefined
  262. >(undefined);
  263. if (scrollQueueRef.current === undefined) {
  264. const queryParams = qs.parse(location.search);
  265. const maybeQueue = decodeScrollQueue(queryParams.node);
  266. if (maybeQueue || queryParams.eventId) {
  267. scrollQueueRef.current = {
  268. eventId: queryParams.eventId as string,
  269. path: maybeQueue as TraceTreeNode<TraceTree.NodeValue>['path'],
  270. };
  271. } else {
  272. scrollQueueRef.current = null;
  273. }
  274. }
  275. const previouslyFocusedNodeRef = useRef<TraceTreeNode<TraceTree.NodeValue> | null>(
  276. null
  277. );
  278. const previouslyScrolledToNodeRef = useRef<TraceTreeNode<TraceTree.NodeValue> | null>(
  279. null
  280. );
  281. const tree = useMemo(() => {
  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. return errorTree;
  291. }
  292. if (
  293. props.trace?.transactions.length === 0 &&
  294. props.trace?.orphan_errors.length === 0
  295. ) {
  296. return TraceTree.Empty();
  297. }
  298. if (props.status === 'loading') {
  299. const loadingTrace =
  300. loadingTraceRef.current ??
  301. TraceTree.Loading(
  302. {
  303. project_slug: projects?.[0]?.slug ?? '',
  304. event_id: props.traceSlug,
  305. },
  306. loadingTraceRef.current
  307. );
  308. loadingTraceRef.current = loadingTrace;
  309. return loadingTrace;
  310. }
  311. if (props.trace) {
  312. return TraceTree.FromTrace(props.trace, props.replayRecord);
  313. }
  314. throw new Error('Invalid trace state');
  315. }, [props.traceSlug, props.trace, props.status, projects, props.replayRecord]);
  316. // Assign the trace state to a ref so we can access it without re-rendering
  317. const traceStateRef = useRef<TraceReducerState>(traceState);
  318. traceStateRef.current = traceState;
  319. // Initialize the view manager right after the state reducer
  320. const viewManager = useMemo(() => {
  321. return new VirtualizedViewManager(
  322. {
  323. list: {width: traceState.preferences.list.width},
  324. span_list: {width: 1 - traceState.preferences.list.width},
  325. },
  326. traceScheduler,
  327. traceView
  328. );
  329. // We only care about initial state when we initialize the view manager
  330. // eslint-disable-next-line react-hooks/exhaustive-deps
  331. }, []);
  332. useLayoutEffect(() => {
  333. const onTraceViewChange: TraceEvents['set trace view'] = view => {
  334. traceView.setTraceView(view);
  335. viewManager.enqueueFOVQueryParamSync(traceView);
  336. };
  337. const onPhysicalSpaceChange: TraceEvents['set container physical space'] =
  338. container => {
  339. traceView.setTracePhysicalSpace(container, [
  340. 0,
  341. 0,
  342. container[2] * viewManager.columns.span_list.width,
  343. container[3],
  344. ]);
  345. };
  346. const onTraceSpaceChange: TraceEvents['initialize trace space'] = view => {
  347. traceView.setTraceSpace(view);
  348. };
  349. // These handlers have high priority because they are responsible for
  350. // updating the view coordinates. If we update them first, then any components downstream
  351. // that rely on the view coordinates will be in sync with the view.
  352. traceScheduler.on('set trace view', onTraceViewChange, TraceEventPriority.HIGH);
  353. traceScheduler.on('set trace space', onTraceSpaceChange, TraceEventPriority.HIGH);
  354. traceScheduler.on(
  355. 'set container physical space',
  356. onPhysicalSpaceChange,
  357. TraceEventPriority.HIGH
  358. );
  359. traceScheduler.on(
  360. 'initialize trace space',
  361. onTraceSpaceChange,
  362. TraceEventPriority.HIGH
  363. );
  364. return () => {
  365. traceScheduler.off('set trace view', onTraceViewChange);
  366. traceScheduler.off('set trace space', onTraceSpaceChange);
  367. traceScheduler.off('set container physical space', onPhysicalSpaceChange);
  368. traceScheduler.off('initialize trace space', onTraceSpaceChange);
  369. };
  370. }, [traceScheduler, traceView, viewManager]);
  371. // Initialize the tabs reducer when the tree initializes
  372. useLayoutEffect(() => {
  373. return traceDispatch({
  374. type: 'set roving count',
  375. items: tree.list.length - 1,
  376. });
  377. }, [tree.list.length, traceDispatch]);
  378. // Initialize the tabs reducer when the tree initializes
  379. useLayoutEffect(() => {
  380. if (tree.type !== 'trace') {
  381. return;
  382. }
  383. const newTabs = [TRACE_TAB];
  384. if (tree.vitals.size > 0) {
  385. const types = Array.from(tree.vital_types.values());
  386. const label = types.length > 1 ? t('Vitals') : capitalize(types[0]) + ' Vitals';
  387. newTabs.push({
  388. ...VITALS_TAB,
  389. label,
  390. });
  391. }
  392. if (tree.profiled_events.size > 0) {
  393. newTabs.push({
  394. node: 'profiles',
  395. label: 'Profiles',
  396. });
  397. }
  398. traceDispatch({
  399. type: 'initialize tabs reducer',
  400. payload: {
  401. current_tab: traceStateRef?.current?.tabs?.tabs?.[0],
  402. tabs: newTabs,
  403. last_clicked_tab: null,
  404. },
  405. });
  406. // We only want to update the tabs when the tree changes
  407. // eslint-disable-next-line react-hooks/exhaustive-deps
  408. }, [tree]);
  409. const searchingRaf = useRef<{id: number | null} | null>(null);
  410. const onTraceSearch = useCallback(
  411. (
  412. query: string,
  413. activeNode: TraceTreeNode<TraceTree.NodeValue> | null,
  414. behavior: 'track result' | 'persist'
  415. ) => {
  416. if (searchingRaf.current?.id) {
  417. window.cancelAnimationFrame(searchingRaf.current.id);
  418. }
  419. function done([matches, lookup, activeNodeSearchResult]) {
  420. // If the previous node is still in the results set, we want to keep it
  421. if (activeNodeSearchResult) {
  422. traceDispatch({
  423. type: 'set results',
  424. results: matches,
  425. resultsLookup: lookup,
  426. resultIteratorIndex: activeNodeSearchResult?.resultIteratorIndex,
  427. resultIndex: activeNodeSearchResult?.resultIndex,
  428. previousNode: activeNodeSearchResult,
  429. node: activeNode,
  430. });
  431. return;
  432. }
  433. if (activeNode && behavior === 'persist') {
  434. traceDispatch({
  435. type: 'set results',
  436. results: matches,
  437. resultsLookup: lookup,
  438. resultIteratorIndex: undefined,
  439. resultIndex: undefined,
  440. previousNode: activeNodeSearchResult,
  441. node: activeNode,
  442. });
  443. return;
  444. }
  445. const resultIndex: number | undefined = matches?.[0]?.index;
  446. const resultIteratorIndex: number | undefined = matches?.[0] ? 0 : undefined;
  447. const node: TraceTreeNode<TraceTree.NodeValue> | null = matches?.[0]?.value;
  448. traceDispatch({
  449. type: 'set results',
  450. results: matches,
  451. resultsLookup: lookup,
  452. resultIteratorIndex: resultIteratorIndex,
  453. resultIndex: resultIndex,
  454. previousNode: activeNodeSearchResult,
  455. node,
  456. });
  457. }
  458. const tokens = parseTraceSearch(query);
  459. if (tokens) {
  460. searchingRaf.current = searchInTraceTreeTokens(tree, tokens, activeNode, done);
  461. } else {
  462. searchingRaf.current = searchInTraceTreeText(tree, query, activeNode, done);
  463. }
  464. },
  465. [traceDispatch, tree]
  466. );
  467. // We need to heavily debounce query string updates because the rest of the app is so slow
  468. // to rerender that it causes the search to drop frames on every keystroke...
  469. const QUERY_STRING_STATE_DEBOUNCE = 300;
  470. const queryStringAnimationTimeoutRef = useRef<{id: number} | null>(null);
  471. const setRowAsFocused = useCallback(
  472. (
  473. node: TraceTreeNode<TraceTree.NodeValue> | null,
  474. event: React.MouseEvent<HTMLElement> | null,
  475. resultsLookup: Map<TraceTreeNode<TraceTree.NodeValue>, number>,
  476. index: number | null,
  477. debounce: number = QUERY_STRING_STATE_DEBOUNCE
  478. ) => {
  479. // sync query string with the clicked node
  480. if (node) {
  481. if (queryStringAnimationTimeoutRef.current) {
  482. cancelAnimationTimeout(queryStringAnimationTimeoutRef.current);
  483. }
  484. queryStringAnimationTimeoutRef.current = requestAnimationTimeout(() => {
  485. const currentQueryStringPath = qs.parse(location.search).node;
  486. const nextNodePath = node.path;
  487. // Updating the query string with the same path is problematic because it causes
  488. // the entire sentry app to rerender, which is enough to cause jank and drop frames
  489. if (JSON.stringify(currentQueryStringPath) === JSON.stringify(nextNodePath)) {
  490. return;
  491. }
  492. const {eventId: _eventId, ...query} = qs.parse(location.search);
  493. browserHistory.replace({
  494. pathname: location.pathname,
  495. query: {
  496. ...query,
  497. node: nextNodePath,
  498. },
  499. });
  500. queryStringAnimationTimeoutRef.current = null;
  501. }, debounce);
  502. if (resultsLookup.has(node) && typeof index === 'number') {
  503. traceDispatch({
  504. type: 'set search iterator index',
  505. resultIndex: index,
  506. resultIteratorIndex: resultsLookup.get(node)!,
  507. });
  508. }
  509. if (isTraceNode(node)) {
  510. traceDispatch({type: 'activate tab', payload: TRACE_TAB.node});
  511. return;
  512. }
  513. traceDispatch({
  514. type: 'activate tab',
  515. payload: node,
  516. pin_previous: event?.metaKey,
  517. });
  518. }
  519. },
  520. [traceDispatch]
  521. );
  522. const onRowClick = useCallback(
  523. (
  524. node: TraceTreeNode<TraceTree.NodeValue>,
  525. event: React.MouseEvent<HTMLElement>,
  526. index: number
  527. ) => {
  528. trackAnalytics('trace.trace_layout.span_row_click', {
  529. organization,
  530. num_children: node.children.length,
  531. type: traceNodeAnalyticsName(node),
  532. project_platform:
  533. projects.find(p => p.slug === node.metadata.project_slug)?.platform || 'other',
  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. `;