index.tsx 34 KB

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