index.tsx 38 KB

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