traceTree.tsx 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704
  1. import type {Theme} from '@emotion/react';
  2. import * as Sentry from '@sentry/react';
  3. import type {Location} from 'history';
  4. import qs from 'qs';
  5. import type {Client} from 'sentry/api';
  6. import type {RawSpanType} from 'sentry/components/events/interfaces/spans/types';
  7. import {pickBarColor} from 'sentry/components/performance/waterfall/utils';
  8. import type {Event, EventTransaction, Measurement} from 'sentry/types/event';
  9. import type {Organization} from 'sentry/types/organization';
  10. import type {TracingEventParameters} from 'sentry/utils/analytics/tracingEventMap';
  11. import {MobileVital, WebVital} from 'sentry/utils/fields';
  12. import type {
  13. TraceError as TraceErrorType,
  14. TraceFullDetailed,
  15. TracePerformanceIssue as TracePerformanceIssueType,
  16. TraceSplitResults,
  17. } from 'sentry/utils/performance/quickTrace/types';
  18. import {
  19. isTraceError,
  20. isTraceTransaction,
  21. } from 'sentry/utils/performance/quickTrace/utils';
  22. import {
  23. MOBILE_VITAL_DETAILS,
  24. WEB_VITAL_DETAILS,
  25. } from 'sentry/utils/performance/vitals/constants';
  26. import type {Vital} from 'sentry/utils/performance/vitals/types';
  27. import type {ReplayTrace} from 'sentry/views/replays/detail/trace/useReplayTraces';
  28. import type {ReplayRecord} from 'sentry/views/replays/types';
  29. import {getStylingSliceName} from '../../../traces/utils';
  30. import {isRootTransaction} from '../../traceDetails/utils';
  31. import {
  32. isAutogroupedNode,
  33. isMissingInstrumentationNode,
  34. isNoDataNode,
  35. isParentAutogroupedNode,
  36. isRootNode,
  37. isSiblingAutogroupedNode,
  38. isSpanNode,
  39. isTraceErrorNode,
  40. isTraceNode,
  41. isTransactionNode,
  42. shouldAddMissingInstrumentationSpan,
  43. } from '../guards';
  44. import {getTraceQueryParams} from '../traceApi/useTrace';
  45. import {TraceType} from '../traceType';
  46. /**
  47. *
  48. * This file implements the tree data structure that is used to represent a trace. We do
  49. * this both for performance reasons as well as flexibility. The requirement for a tree
  50. * is to support incremental patching and updates. This is important because we want to
  51. * be able to fetch more data as the user interacts with the tree, and we want to be able
  52. * efficiently update the tree as we receive more data.
  53. *
  54. * The trace is represented as a tree with different node value types (transaction or span)
  55. * Each tree node contains a reference to its parent and a list of references to its children,
  56. * as well as a reference to the value that the node holds. Each node also contains
  57. * some meta data and state about the node, such as if it is expanded or zoomed in. The benefit
  58. * of abstracting parts of the UI state is that the tree will persist user actions such as expanding
  59. * or collapsing nodes which would have otherwise been lost when individual nodes are remounted in the tree.
  60. *
  61. * Each tree holds a list reference, which is a live reference to a flattened representation
  62. * of the tree (used to render the tree in the UI). Since the list is mutable (and we want to keep it that way for performance
  63. * reasons as we want to support mutations on traces with ~100k+ nodes), callers need to manage reactivity themselves.
  64. *
  65. * An alternative, but not recommended approach is to call build() on the tree after each mutation,
  66. * which will iterate over all of the children and build a fresh list reference.
  67. *
  68. * In most cases, the initial tree is a list of transactions containing other transactions. Each transaction can
  69. * then be expanded into a list of spans which can also in some cases be expanded.
  70. *
  71. * - trace - trace
  72. * |- parent transaction --> when expanding |- parent transaction
  73. * |- child transaction |- span
  74. * |- span this used to be a transaction,
  75. * |- child transaction span <- but is now be a list of spans
  76. * |- span belonging to the transaction
  77. * this results in child txns to be lost,
  78. * which is a confusing user experience
  79. *
  80. * The tree supports autogrouping of spans vertically or as siblings. When that happens, a autogrouped node of either a vertical or
  81. * sibling type is inserted as an intermediary node. In the vertical case, the autogrouped node
  82. * holds the reference to the head and tail of the autogrouped sequence. In the sibling case, the autogrouped node
  83. * holds a reference to the children that are part of the autogrouped sequence. When expanding and collapsing these nodes,
  84. * the tree perform a reference swap to either point to the head (when expanded) or tail (when collapsed) of the autogrouped sequence.
  85. *
  86. * In vertical grouping case, the following happens:
  87. *
  88. * - root - root
  89. * - trace - trace
  90. * |- transaction |- transaction
  91. * |- span 1 <-| these become autogrouped |- autogrouped (head=span1, tail=span3, children points to children of tail)
  92. * |- span 2 |- as they are inserted into |- other span (parent points to autogrouped node)
  93. * |- span 3 <-| the tree.
  94. * |- other span
  95. *
  96. * When the autogrouped node is expanded the UI needs to show the entire collapsed chain, so we swap the tail children to point
  97. * back to the tail, and have autogrouped node point to its head as the children.
  98. *
  99. * - root - root
  100. * - trace - trace
  101. * |- transaction |- transaction
  102. * |- autogrouped (head=span1, tail=span3) <- when expanding |- autogrouped (head=span1, tail=span3, children points to head)
  103. * | other span (paren points to autogrouped) |- span 1 (head)
  104. * |- span 2
  105. * |- span 3 (tail)
  106. * |- other span (children of tail, parent points to tail)
  107. *
  108. * Notes and improvements:
  109. * - the notion of expanded and zoomed is confusing, they stand for the same idea from a UI pov
  110. * - there is an annoying thing wrt span and transaction nodes where we either store data on _children or _spanChildren
  111. * this is because we want to be able to store both transaction and span nodes in the same tree, but it makes for an
  112. * annoying API. A better design would have been to create an invisible meta node that just points to the correct children
  113. * - instead of storing span children separately, we should have meta tree nodes that handle pointing to the correct children
  114. */
  115. type ArgumentTypes<F> = F extends (...args: infer A) => any ? A : never;
  116. export declare namespace TraceTree {
  117. interface Transaction extends TraceFullDetailed {
  118. profiler_id: string;
  119. sdk_name: string;
  120. }
  121. interface Span extends RawSpanType {
  122. childTransactions: TraceTreeNode<TraceTree.Transaction>[];
  123. event: EventTransaction;
  124. measurements?: Record<string, Measurement>;
  125. }
  126. type Trace = TraceSplitResults<Transaction>;
  127. type TraceError = TraceErrorType;
  128. type TracePerformanceIssue = TracePerformanceIssueType;
  129. type Profile = {profile_id: string; space: [number, number]};
  130. interface MissingInstrumentationSpan {
  131. start_timestamp: number;
  132. timestamp: number;
  133. type: 'missing_instrumentation';
  134. }
  135. interface SiblingAutogroup extends RawSpanType {
  136. autogrouped_by: {
  137. description: string;
  138. op: string;
  139. };
  140. }
  141. interface ChildrenAutogroup extends RawSpanType {
  142. autogrouped_by: {
  143. op: string;
  144. };
  145. }
  146. type NodeValue =
  147. | Trace
  148. | Transaction
  149. | TraceError
  150. | Span
  151. | MissingInstrumentationSpan
  152. | SiblingAutogroup
  153. | ChildrenAutogroup
  154. | null;
  155. type Node =
  156. | TraceTreeNode<NodeValue>
  157. | ParentAutogroupNode
  158. | SiblingAutogroupNode
  159. | MissingInstrumentationNode;
  160. type NodePath =
  161. `${'txn' | 'span' | 'ag' | 'trace' | 'ms' | 'error' | 'empty'}-${string}`;
  162. type Metadata = {
  163. event_id: string | undefined;
  164. project_slug: string | undefined;
  165. };
  166. type Indicator = {
  167. duration: number;
  168. label: string;
  169. measurement: Measurement;
  170. poor: boolean;
  171. start: number;
  172. type: 'cls' | 'fcp' | 'fp' | 'lcp' | 'ttfb';
  173. };
  174. type CollectedVital = {key: string; measurement: Measurement};
  175. interface TraceTreeEvents {
  176. ['trace timeline change']: (view: [number, number]) => void;
  177. }
  178. type EventStore = {[K in keyof TraceTreeEvents]: Set<TraceTreeEvents[K]>};
  179. }
  180. export type ViewManagerScrollToOptions = {
  181. api: Client;
  182. organization: Organization;
  183. };
  184. function cacheKey(organization: Organization, project_slug: string, event_id: string) {
  185. return organization.slug + ':' + project_slug + ':' + event_id;
  186. }
  187. function fetchTransactionSpans(
  188. api: Client,
  189. organization: Organization,
  190. project_slug: string,
  191. event_id: string
  192. ): Promise<EventTransaction> {
  193. return api.requestPromise(
  194. `/organizations/${organization.slug}/events/${project_slug}:${event_id}/?averageColumn=span.self_time&averageColumn=span.duration`
  195. );
  196. }
  197. function isJavascriptSDKTransaction(transaction: TraceTree.Transaction): boolean {
  198. return /javascript|angular|astro|backbone|ember|gatsby|nextjs|react|remix|svelte|vue/.test(
  199. transaction.sdk_name
  200. );
  201. }
  202. function measurementToTimestamp(
  203. start_timestamp: number,
  204. measurement: number,
  205. unit: string
  206. ) {
  207. if (unit === 'second') {
  208. return start_timestamp + measurement;
  209. }
  210. if (unit === 'millisecond') {
  211. return start_timestamp + measurement / 1e3;
  212. }
  213. if (unit === 'nanosecond') {
  214. return start_timestamp + measurement / 1e9;
  215. }
  216. throw new TypeError(`Unsupported measurement unit', ${unit}`);
  217. }
  218. function maybeInsertMissingInstrumentationSpan(
  219. parent: TraceTreeNode<TraceTree.NodeValue>,
  220. node: TraceTreeNode<TraceTree.Span>
  221. ) {
  222. const previousSpan = parent.spanChildren[parent.spanChildren.length - 1];
  223. if (!previousSpan || !isSpanNode(previousSpan)) {
  224. return;
  225. }
  226. if (node.value.start_timestamp - previousSpan.value.timestamp < 0.1) {
  227. return;
  228. }
  229. const missingInstrumentationSpan = new MissingInstrumentationNode(
  230. parent,
  231. {
  232. type: 'missing_instrumentation',
  233. start_timestamp: previousSpan.value.timestamp,
  234. timestamp: node.value.start_timestamp,
  235. },
  236. {
  237. event_id: undefined,
  238. project_slug: undefined,
  239. },
  240. previousSpan,
  241. node
  242. );
  243. parent.spanChildren.push(missingInstrumentationSpan);
  244. }
  245. export function makeTraceNodeBarColor(
  246. theme: Theme,
  247. node: TraceTreeNode<TraceTree.NodeValue>
  248. ): string {
  249. if (isTransactionNode(node)) {
  250. return pickBarColor(
  251. getStylingSliceName(node.value.project_slug, node.value.sdk_name) ??
  252. node.value['transaction.op']
  253. );
  254. }
  255. if (isSpanNode(node)) {
  256. return pickBarColor(node.value.op);
  257. }
  258. if (isAutogroupedNode(node)) {
  259. if (node.errors.size > 0) {
  260. return theme.red300;
  261. }
  262. return theme.blue300;
  263. }
  264. if (isMissingInstrumentationNode(node)) {
  265. return theme.gray300;
  266. }
  267. if (isNoDataNode(node)) {
  268. return theme.yellow300;
  269. }
  270. if (isTraceErrorNode(node)) {
  271. // Theme defines this as orange, yet everywhere in our product we show red for errors
  272. if (node.value.level === 'error' || node.value.level === 'fatal') {
  273. return theme.red300;
  274. }
  275. if (node.value.level) {
  276. return theme.level[node.value.level] ?? theme.red300;
  277. }
  278. return theme.red300;
  279. }
  280. return pickBarColor('default');
  281. }
  282. function shouldCollapseNodeByDefault(node: TraceTreeNode<TraceTree.NodeValue>) {
  283. if (isSpanNode(node)) {
  284. // Android creates TCP connection spans which are noisy and not useful in most cases.
  285. // Unless the span has a child txn which would indicate a continuaton of the trace, we collapse it.
  286. if (
  287. node.value.op === 'http.client' &&
  288. node.value.origin === 'auto.http.okhttp' &&
  289. !node.value.childTransactions.length
  290. ) {
  291. return true;
  292. }
  293. }
  294. return false;
  295. }
  296. function startTimestamp(node: TraceTreeNode<TraceTree.NodeValue>) {
  297. if (node.space) return node.space[0];
  298. if (isTraceNode(node)) {
  299. return 0;
  300. }
  301. if (isSpanNode(node)) {
  302. return node.value.start_timestamp;
  303. }
  304. if (isTransactionNode(node)) {
  305. return node.value.start_timestamp;
  306. }
  307. if (isMissingInstrumentationNode(node)) {
  308. return node.previous.value.timestamp;
  309. }
  310. return 0;
  311. }
  312. function chronologicalSort(
  313. a: TraceTreeNode<TraceTree.NodeValue>,
  314. b: TraceTreeNode<TraceTree.NodeValue>
  315. ) {
  316. return startTimestamp(a) - startTimestamp(b);
  317. }
  318. // cls is not included as it is a cumulative layout shift and not a single point in time
  319. const RENDERABLE_MEASUREMENTS = [
  320. WebVital.TTFB,
  321. WebVital.FP,
  322. WebVital.FCP,
  323. WebVital.LCP,
  324. MobileVital.TIME_TO_FULL_DISPLAY,
  325. MobileVital.TIME_TO_INITIAL_DISPLAY,
  326. ]
  327. .map(n => n.replace('measurements.', ''))
  328. .reduce((acc, curr) => {
  329. acc[curr] = true;
  330. return acc;
  331. }, {});
  332. const WEB_VITALS = [
  333. WebVital.TTFB,
  334. WebVital.FP,
  335. WebVital.FCP,
  336. WebVital.LCP,
  337. WebVital.CLS,
  338. WebVital.FID,
  339. WebVital.INP,
  340. WebVital.REQUEST_TIME,
  341. ].map(n => n.replace('measurements.', ''));
  342. const MOBILE_VITALS = [
  343. MobileVital.APP_START_COLD,
  344. MobileVital.APP_START_WARM,
  345. MobileVital.TIME_TO_INITIAL_DISPLAY,
  346. MobileVital.TIME_TO_FULL_DISPLAY,
  347. MobileVital.FRAMES_TOTAL,
  348. MobileVital.FRAMES_SLOW,
  349. MobileVital.FRAMES_FROZEN,
  350. MobileVital.FRAMES_SLOW_RATE,
  351. MobileVital.FRAMES_FROZEN_RATE,
  352. MobileVital.STALL_COUNT,
  353. MobileVital.STALL_TOTAL_TIME,
  354. MobileVital.STALL_LONGEST_TIME,
  355. MobileVital.STALL_PERCENTAGE,
  356. ].map(n => n.replace('measurements.', ''));
  357. const WEB_VITALS_LOOKUP = new Set<string>(WEB_VITALS);
  358. const MOBILE_VITALS_LOOKUP = new Set<string>(MOBILE_VITALS);
  359. const COLLECTABLE_MEASUREMENTS = [...WEB_VITALS, ...MOBILE_VITALS].map(n =>
  360. n.replace('measurements.', '')
  361. );
  362. const MEASUREMENT_ACRONYM_MAPPING = {
  363. [MobileVital.TIME_TO_FULL_DISPLAY.replace('measurements.', '')]: 'TTFD',
  364. [MobileVital.TIME_TO_INITIAL_DISPLAY.replace('measurements.', '')]: 'TTID',
  365. };
  366. const MEASUREMENT_THRESHOLDS = {
  367. [WebVital.TTFB.replace('measurements.', '')]: 600,
  368. [WebVital.FP.replace('measurements.', '')]: 3000,
  369. [WebVital.FCP.replace('measurements.', '')]: 3000,
  370. [WebVital.LCP.replace('measurements.', '')]: 4000,
  371. [MobileVital.TIME_TO_INITIAL_DISPLAY.replace('measurements.', '')]: 2000,
  372. };
  373. export const TRACE_MEASUREMENT_LOOKUP: Record<string, Vital> = {};
  374. for (const key in {...MOBILE_VITAL_DETAILS, ...WEB_VITAL_DETAILS}) {
  375. TRACE_MEASUREMENT_LOOKUP[key.replace('measurements.', '')] = {
  376. ...MOBILE_VITAL_DETAILS[key],
  377. ...WEB_VITAL_DETAILS[key],
  378. };
  379. }
  380. type TraceFetchOptions = {
  381. api: Client;
  382. filters: any;
  383. organization: Organization;
  384. replayTraces: ReplayTrace[];
  385. rerender: () => void;
  386. urlParams: Location['query'];
  387. };
  388. function fetchSingleTrace(
  389. api: Client,
  390. params: {
  391. orgSlug: string;
  392. query: string;
  393. traceId: string;
  394. }
  395. ): Promise<TraceSplitResults<TraceTree.Transaction>> {
  396. return api.requestPromise(
  397. `/organizations/${params.orgSlug}/events-trace/${params.traceId}/?${params.query}`
  398. );
  399. }
  400. export class TraceTree {
  401. type: 'loading' | 'empty' | 'error' | 'trace' = 'trace';
  402. root: TraceTreeNode<null> = TraceTreeNode.Root();
  403. indicators: TraceTree.Indicator[] = [];
  404. vitals: Map<TraceTreeNode<TraceTree.NodeValue>, TraceTree.CollectedVital[]> = new Map();
  405. vital_types: Set<'web' | 'mobile'> = new Set();
  406. eventsCount: number = 0;
  407. profiled_events: Set<TraceTreeNode<TraceTree.NodeValue>> = new Set();
  408. private _spanPromises: Map<string, Promise<Event>> = new Map();
  409. private _list: TraceTreeNode<TraceTree.NodeValue>[] = [];
  410. static Empty() {
  411. const tree = new TraceTree().build();
  412. tree.type = 'empty';
  413. return tree;
  414. }
  415. static Loading(metadata: TraceTree.Metadata, tree?: TraceTree | null): TraceTree {
  416. const t = tree ? TraceTree.FromTree(tree) : makeExampleTrace(metadata);
  417. t.type = 'loading';
  418. return t;
  419. }
  420. static Error(metadata: TraceTree.Metadata, tree?: TraceTree | null): TraceTree {
  421. const t = tree ? TraceTree.FromTree(tree) : makeExampleTrace(metadata);
  422. t.type = 'error';
  423. return t;
  424. }
  425. static FromTree(tree: TraceTree): TraceTree {
  426. const newTree = new TraceTree();
  427. newTree.root = tree.root.cloneDeep() as TraceTreeNode<null>;
  428. newTree.indicators = tree.indicators;
  429. newTree._list = tree._list;
  430. return newTree;
  431. }
  432. static FromTrace(trace: TraceTree.Trace, replayRecord: ReplayRecord | null): TraceTree {
  433. const tree = new TraceTree();
  434. let traceStart = Number.POSITIVE_INFINITY;
  435. let traceEnd = Number.NEGATIVE_INFINITY;
  436. const traceNode = new TraceTreeNode(tree.root, trace, {
  437. event_id: undefined,
  438. project_slug: undefined,
  439. });
  440. // Trace is always expanded by default
  441. tree.root.children.push(traceNode);
  442. function visit(
  443. parent: TraceTreeNode<TraceTree.NodeValue | null>,
  444. value: TraceTree.Transaction | TraceTree.TraceError
  445. ) {
  446. const node = new TraceTreeNode(parent, value, {
  447. project_slug: value && 'project_slug' in value ? value.project_slug : undefined,
  448. event_id: value && 'event_id' in value ? value.event_id : undefined,
  449. });
  450. node.canFetch = true;
  451. tree.eventsCount += 1;
  452. if (node.profiles.length > 0) {
  453. tree.profiled_events.add(node);
  454. }
  455. if (isTraceTransaction(value)) {
  456. for (const error of value.errors) {
  457. traceNode.errors.add(error);
  458. }
  459. for (const performanceIssue of value.performance_issues) {
  460. traceNode.performance_issues.add(performanceIssue);
  461. }
  462. } else {
  463. traceNode.errors.add(value);
  464. }
  465. if (parent) {
  466. parent.children.push(node as TraceTreeNode<TraceTree.NodeValue>);
  467. }
  468. if ('start_timestamp' in value && value.start_timestamp < traceStart) {
  469. traceStart = value.start_timestamp;
  470. }
  471. if ('timestamp' in value && typeof value.timestamp === 'number') {
  472. // Errors don't have 'start_timestamp', so we adjust traceStart
  473. // with an errors 'timestamp'
  474. if (isTraceError(value)) {
  475. traceStart = Math.min(value.timestamp, traceStart);
  476. }
  477. traceEnd = Math.max(value.timestamp, traceEnd);
  478. }
  479. if (value && 'measurements' in value) {
  480. tree.collectMeasurements(
  481. node,
  482. traceStart,
  483. value.measurements as Record<string, Measurement>,
  484. tree.vitals,
  485. tree.vital_types,
  486. tree.indicators
  487. );
  488. }
  489. if (value && 'children' in value) {
  490. for (const child of value.children) {
  491. visit(node, child);
  492. }
  493. }
  494. return node;
  495. }
  496. const transactionQueue = trace.transactions ?? [];
  497. const orphanErrorsQueue = trace.orphan_errors ?? [];
  498. let tIdx = 0;
  499. let oIdx = 0;
  500. const tLen = transactionQueue.length;
  501. const oLen = orphanErrorsQueue.length;
  502. // Items in each queue are sorted by timestamp, so we just take
  503. // from the queue with the earliest timestamp which means the final list will be ordered.
  504. while (tIdx < tLen || oIdx < oLen) {
  505. const transaction = transactionQueue[tIdx];
  506. const orphan = orphanErrorsQueue[oIdx];
  507. if (transaction && orphan) {
  508. if (
  509. typeof orphan.timestamp === 'number' &&
  510. transaction.start_timestamp <= orphan.timestamp
  511. ) {
  512. visit(traceNode, transaction);
  513. tIdx++;
  514. } else {
  515. visit(traceNode, orphan);
  516. oIdx++;
  517. }
  518. } else if (transaction) {
  519. visit(traceNode, transaction);
  520. tIdx++;
  521. } else if (orphan) {
  522. visit(traceNode, orphan);
  523. oIdx++;
  524. }
  525. }
  526. if (tree.indicators.length > 0) {
  527. tree.indicators.sort((a, b) => a.start - b.start);
  528. for (const indicator of tree.indicators) {
  529. if (indicator.start > traceEnd) {
  530. traceEnd = indicator.start;
  531. }
  532. indicator.start *= traceNode.multiplier;
  533. }
  534. }
  535. // The sum of all durations of traces that exist under a replay is not always
  536. // equal to the duration of the replay. We need to adjust the traceview bounds
  537. // to ensure that we can see the max of the replay duration and the sum(trace durations). This way, we
  538. // can ensure that the replay timestamp indicators are always visible in the traceview along with all spans from the traces.
  539. if (replayRecord) {
  540. const replayStart = replayRecord.started_at.getTime() / 1000;
  541. const replayEnd = replayRecord.finished_at.getTime() / 1000;
  542. traceStart = Math.min(traceStart, replayStart);
  543. traceEnd = Math.max(traceEnd, replayEnd);
  544. }
  545. traceNode.space = [
  546. traceStart * traceNode.multiplier,
  547. (traceEnd - traceStart) * traceNode.multiplier,
  548. ];
  549. tree.root.space = [
  550. traceStart * traceNode.multiplier,
  551. (traceEnd - traceStart) * traceNode.multiplier,
  552. ];
  553. return tree.build();
  554. }
  555. fetchAdditionalTraces(options: TraceFetchOptions): () => void {
  556. let cancelled = false;
  557. const {organization, api, urlParams, filters, rerender, replayTraces} = options;
  558. const clonedTraceIds = [...replayTraces];
  559. const root = this.root.children[0];
  560. root.fetchStatus = 'loading';
  561. rerender();
  562. (async () => {
  563. while (clonedTraceIds.length > 0) {
  564. const batch = clonedTraceIds.splice(0, 3);
  565. const results = await Promise.allSettled(
  566. batch.map(batchTraceData => {
  567. return fetchSingleTrace(api, {
  568. orgSlug: organization.slug,
  569. query: qs.stringify(
  570. getTraceQueryParams(urlParams, filters.selection, {
  571. timestamp: batchTraceData.timestamp,
  572. })
  573. ),
  574. traceId: batchTraceData.traceSlug,
  575. });
  576. })
  577. );
  578. if (cancelled) return;
  579. const updatedData = results.reduce(
  580. (acc, result) => {
  581. // Ignoring the error case for now
  582. if (result.status === 'fulfilled') {
  583. const {transactions, orphan_errors} = result.value;
  584. acc.transactions.push(...transactions);
  585. acc.orphan_errors.push(...orphan_errors);
  586. }
  587. return acc;
  588. },
  589. {
  590. transactions: [],
  591. orphan_errors: [],
  592. } as TraceSplitResults<TraceTree.Transaction>
  593. );
  594. this.appendTree(TraceTree.FromTrace(updatedData, null));
  595. rerender();
  596. }
  597. root.fetchStatus = 'idle';
  598. rerender();
  599. })();
  600. return () => {
  601. root.fetchStatus = 'idle';
  602. cancelled = true;
  603. };
  604. }
  605. appendTree(tree: TraceTree) {
  606. const baseTraceNode = this.root.children[0];
  607. const additionalTraceNode = tree.root.children[0];
  608. if (!baseTraceNode || !additionalTraceNode) {
  609. throw new Error('No trace node found in tree');
  610. }
  611. for (const child of additionalTraceNode.children) {
  612. child.parent = baseTraceNode;
  613. baseTraceNode.children.push(child);
  614. }
  615. for (const error of additionalTraceNode.errors) {
  616. baseTraceNode.errors.add(error);
  617. }
  618. for (const performanceIssue of additionalTraceNode.performance_issues) {
  619. baseTraceNode.performance_issues.add(performanceIssue);
  620. }
  621. for (const profile of additionalTraceNode.profiles) {
  622. baseTraceNode.profiles.push(profile);
  623. }
  624. for (const [node, vitals] of tree.vitals) {
  625. this.vitals.set(node, vitals);
  626. }
  627. for (const [node, _] of tree.vitals) {
  628. if (
  629. baseTraceNode.space?.[0] &&
  630. node.value &&
  631. 'start_timestamp' in node.value &&
  632. 'measurements' in node.value
  633. ) {
  634. this.collectMeasurements(
  635. node,
  636. baseTraceNode.space[0],
  637. node.value.measurements as Record<string, Measurement>,
  638. this.vitals,
  639. this.vital_types,
  640. this.indicators
  641. );
  642. }
  643. }
  644. // We need to invalidate the data in the last node of the tree
  645. // so that the connectors are updated and pointing to the sibling nodes
  646. const last = this.root.children[this.root.children.length - 1];
  647. last.invalidate(last);
  648. for (const child of tree.root.children) {
  649. this._list = this._list.concat(child.getVisibleChildren());
  650. }
  651. }
  652. get shape(): TraceType {
  653. const trace = this.root.children[0];
  654. if (!trace) {
  655. return TraceType.EMPTY_TRACE;
  656. }
  657. if (!isTraceNode(trace)) {
  658. throw new TypeError('Not trace node');
  659. }
  660. const {transactions, orphan_errors} = trace.value;
  661. const traceStats = transactions?.reduce<{
  662. javascriptRootTransactions: TraceTree.Transaction[];
  663. orphans: number;
  664. roots: number;
  665. }>(
  666. (stats, transaction) => {
  667. if (isRootTransaction(transaction)) {
  668. stats.roots++;
  669. if (isJavascriptSDKTransaction(transaction)) {
  670. stats.javascriptRootTransactions.push(transaction);
  671. }
  672. } else {
  673. stats.orphans++;
  674. }
  675. return stats;
  676. },
  677. {roots: 0, orphans: 0, javascriptRootTransactions: []}
  678. ) ?? {roots: 0, orphans: 0, javascriptRootTransactions: []};
  679. if (traceStats.roots === 0) {
  680. if (traceStats.orphans > 0) {
  681. return TraceType.NO_ROOT;
  682. }
  683. if (orphan_errors && orphan_errors.length > 0) {
  684. return TraceType.ONLY_ERRORS;
  685. }
  686. return TraceType.EMPTY_TRACE;
  687. }
  688. if (traceStats.roots === 1) {
  689. if (traceStats.orphans > 0) {
  690. return TraceType.BROKEN_SUBTRACES;
  691. }
  692. return TraceType.ONE_ROOT;
  693. }
  694. if (traceStats.roots > 1) {
  695. if (traceStats.javascriptRootTransactions.length > 0) {
  696. return TraceType.BROWSER_MULTIPLE_ROOTS;
  697. }
  698. return TraceType.MULTIPLE_ROOTS;
  699. }
  700. throw new Error('Unknown trace type');
  701. }
  702. static FromSpans(
  703. parent: TraceTreeNode<TraceTree.NodeValue>,
  704. data: Event,
  705. spans: RawSpanType[],
  706. options: {sdk: string | undefined} | undefined
  707. ): [TraceTreeNode<TraceTree.NodeValue>, [number, number] | null] {
  708. parent.invalidate(parent);
  709. const platformHasMissingSpans = shouldAddMissingInstrumentationSpan(options?.sdk);
  710. let min_span_start = Number.POSITIVE_INFINITY;
  711. let min_span_end = Number.NEGATIVE_INFINITY;
  712. const parentIsSpan = isSpanNode(parent);
  713. const lookuptable: Record<
  714. RawSpanType['span_id'],
  715. TraceTreeNode<TraceTree.Span | TraceTree.Transaction>
  716. > = {};
  717. // If we've already fetched children, the tree is already assembled
  718. if (parent.spanChildren.length > 0) {
  719. parent.zoomedIn = true;
  720. return [parent, null];
  721. }
  722. // If we have no spans, insert an empty node to indicate that there is no data
  723. if (!spans.length && !parent.children.length) {
  724. parent.zoomedIn = true;
  725. parent.spanChildren.push(new NoDataNode(parent));
  726. return [parent, null];
  727. }
  728. if (parentIsSpan) {
  729. if (parent.value && 'span_id' in parent.value) {
  730. lookuptable[parent.value.span_id] = parent as TraceTreeNode<TraceTree.Span>;
  731. }
  732. }
  733. const transactionsToSpanMap = new Map<
  734. string,
  735. TraceTreeNode<TraceTree.Transaction>[]
  736. >();
  737. for (const child of parent.children) {
  738. if (isTransactionNode(child)) {
  739. // keep track of the transaction nodes that should be reparented under the newly fetched spans.
  740. const key =
  741. 'parent_span_id' in child.value &&
  742. typeof child.value.parent_span_id === 'string'
  743. ? child.value.parent_span_id
  744. : // This should be unique, but unreachable at lookup time.
  745. `unreachable-${child.value.event_id}`;
  746. const list = transactionsToSpanMap.get(key) ?? [];
  747. list.push(child);
  748. transactionsToSpanMap.set(key, list);
  749. }
  750. }
  751. const remappedTransactionParents = new Set<TraceTreeNode<TraceTree.NodeValue>>();
  752. for (const span of spans) {
  753. const childTransactions = transactionsToSpanMap.get(span.span_id) ?? [];
  754. const spanNodeValue: TraceTree.Span = {
  755. ...span,
  756. event: data as EventTransaction,
  757. childTransactions,
  758. };
  759. const node: TraceTreeNode<TraceTree.Span> = new TraceTreeNode(null, spanNodeValue, {
  760. event_id: undefined,
  761. project_slug: undefined,
  762. });
  763. if (
  764. typeof span.start_timestamp === 'number' &&
  765. span.start_timestamp < min_span_start
  766. ) {
  767. min_span_start = span.start_timestamp;
  768. }
  769. if (typeof span.timestamp === 'number' && span.timestamp > min_span_end) {
  770. min_span_end = span.timestamp;
  771. }
  772. for (const error of getRelatedSpanErrorsFromTransaction(span, parent)) {
  773. node.errors.add(error);
  774. }
  775. for (const performanceIssue of getRelatedPerformanceIssuesFromTransaction(
  776. span,
  777. parent
  778. )) {
  779. node.performance_issues.add(performanceIssue);
  780. }
  781. // This is the case where the current span is the parent of a transaction.
  782. // When zooming into the parent of the txn, we want to place a copy
  783. // of the txn as a child of the parenting span.
  784. if (childTransactions) {
  785. for (const childTransaction of childTransactions) {
  786. const clonedChildTxn = childTransaction.cloneDeep();
  787. node.spanChildren.push(clonedChildTxn);
  788. clonedChildTxn.parent = node;
  789. remappedTransactionParents.add(node);
  790. // Delete the transaction from the lookup table so that we don't
  791. // duplicate the transaction in the tree.
  792. }
  793. transactionsToSpanMap.delete(span.span_id);
  794. }
  795. lookuptable[span.span_id] = node;
  796. if (span.parent_span_id) {
  797. const spanParentNode = lookuptable[span.parent_span_id];
  798. if (spanParentNode) {
  799. node.parent = spanParentNode;
  800. if (platformHasMissingSpans) {
  801. maybeInsertMissingInstrumentationSpan(spanParentNode, node);
  802. }
  803. spanParentNode.spanChildren.push(node);
  804. continue;
  805. }
  806. }
  807. if (platformHasMissingSpans) {
  808. maybeInsertMissingInstrumentationSpan(parent, node);
  809. }
  810. parent.spanChildren.push(node);
  811. node.parent = parent;
  812. }
  813. // Whatever remains is transaction nodes that we failed to reparent under the spans.
  814. for (const [_, transactions] of transactionsToSpanMap) {
  815. for (const transaction of transactions) {
  816. if ('parent_span_id' in transaction.value && !!transaction.value.parent_span_id) {
  817. Sentry.withScope(scope => {
  818. scope.setFingerprint(['trace-view-reparenting']);
  819. scope.captureMessage(
  820. 'Failed to reparent transaction under span. None of the spans we fetched had a span_id matching the parent_span_id of the transaction.'
  821. );
  822. });
  823. }
  824. const cloned = transaction.cloneDeep();
  825. parent.spanChildren.push(cloned);
  826. cloned.parent = parent;
  827. }
  828. }
  829. for (const c of remappedTransactionParents) {
  830. c.spanChildren.sort(chronologicalSort);
  831. }
  832. parent.zoomedIn = true;
  833. TraceTree.AutogroupSiblingSpanNodes(parent);
  834. TraceTree.AutogroupDirectChildrenSpanNodes(parent);
  835. return [parent, [min_span_start, min_span_end]];
  836. }
  837. static AutogroupDirectChildrenSpanNodes(
  838. root: TraceTreeNode<TraceTree.NodeValue>
  839. ): void {
  840. const queue = [root];
  841. while (queue.length > 0) {
  842. const node = queue.pop()!;
  843. if (node.children.length > 1 || !isSpanNode(node)) {
  844. for (const child of node.children) {
  845. queue.push(child);
  846. }
  847. continue;
  848. }
  849. const head = node;
  850. let tail = node;
  851. let groupMatchCount = 0;
  852. const errors: TraceErrorType[] = [];
  853. const performance_issues: TraceTree.TracePerformanceIssue[] = [];
  854. let start = head.value.start_timestamp;
  855. let end = head.value.timestamp;
  856. while (
  857. tail &&
  858. tail.children.length === 1 &&
  859. isSpanNode(tail.children[0]) &&
  860. tail.children[0].value.op === head.value.op
  861. ) {
  862. if ((tail?.errors?.size ?? 0) > 0) {
  863. errors.push(...tail?.errors);
  864. }
  865. if ((tail?.performance_issues?.size ?? 0) > 0) {
  866. performance_issues.push(...tail.performance_issues);
  867. }
  868. // Collect start/end of all nodes in the list
  869. // so that we can properly render a autogrouped bar that
  870. // encapsulates all the nodes in the list
  871. if (tail.value.start_timestamp < start) {
  872. start = tail.value.start_timestamp;
  873. }
  874. if (tail.value.timestamp > end) {
  875. end = tail.value.timestamp;
  876. }
  877. groupMatchCount++;
  878. tail = tail.children[0];
  879. }
  880. // Checking the tail node for errors as it is not included in the grouping
  881. // while loop, but is hidden when the autogrouped node is collapsed
  882. if ((tail?.errors?.size ?? 0) > 0) {
  883. errors.push(...tail?.errors);
  884. }
  885. if ((tail?.performance_issues?.size ?? 0) > 0) {
  886. performance_issues.push(...tail.performance_issues);
  887. }
  888. if (groupMatchCount < 1) {
  889. for (const child of head.children) {
  890. queue.push(child);
  891. }
  892. continue;
  893. }
  894. const autoGroupedNode = new ParentAutogroupNode(
  895. node.parent,
  896. {
  897. ...head.value,
  898. start_timestamp: start,
  899. timestamp: end,
  900. autogrouped_by: {
  901. op: head.value && 'op' in head.value ? head.value.op ?? '' : '',
  902. },
  903. },
  904. {
  905. event_id: undefined,
  906. project_slug: undefined,
  907. },
  908. head,
  909. tail
  910. );
  911. if (!node.parent) {
  912. throw new Error('Parent node is missing, this should be unreachable code');
  913. }
  914. const index = node.parent.children.indexOf(node);
  915. node.parent.children[index] = autoGroupedNode;
  916. autoGroupedNode.head.parent = autoGroupedNode;
  917. autoGroupedNode.groupCount = groupMatchCount + 1;
  918. autoGroupedNode.space = [
  919. start * autoGroupedNode.multiplier,
  920. (end - start) * autoGroupedNode.multiplier,
  921. ];
  922. for (const error of errors) {
  923. autoGroupedNode.errors.add(error);
  924. }
  925. for (const performanceIssue of performance_issues) {
  926. autoGroupedNode.performance_issues.add(performanceIssue);
  927. }
  928. for (const c of tail.children) {
  929. c.parent = autoGroupedNode;
  930. queue.push(c);
  931. }
  932. }
  933. }
  934. static AutogroupSiblingSpanNodes(root: TraceTreeNode<TraceTree.NodeValue>): void {
  935. const queue = [root];
  936. while (queue.length > 0) {
  937. const node = queue.pop()!;
  938. for (const child of node.children) {
  939. queue.push(child);
  940. }
  941. if (isAutogroupedNode(node)) {
  942. continue;
  943. }
  944. if (node.children.length < 5) {
  945. continue;
  946. }
  947. let index = 0;
  948. let matchCount = 0;
  949. while (index < node.children.length) {
  950. if (!isSpanNode(node.children[index])) {
  951. index++;
  952. matchCount = 0;
  953. continue;
  954. }
  955. const current = node.children[index] as TraceTreeNode<TraceTree.Span>;
  956. const next = node.children[index + 1] as TraceTreeNode<TraceTree.Span>;
  957. if (
  958. next &&
  959. isSpanNode(next) &&
  960. next.children.length === 0 &&
  961. current.children.length === 0 &&
  962. next.value.op === current.value.op &&
  963. next.value.description === current.value.description
  964. ) {
  965. matchCount++;
  966. // If the next node is the last node in the list, we keep iterating
  967. if (index + 1 < node.children.length) {
  968. index++;
  969. continue;
  970. }
  971. }
  972. if (matchCount >= 4) {
  973. const autoGroupedNode = new SiblingAutogroupNode(
  974. node,
  975. {
  976. ...current.value,
  977. autogrouped_by: {
  978. op: current.value.op ?? '',
  979. description: current.value.description ?? '',
  980. },
  981. },
  982. {
  983. event_id: undefined,
  984. project_slug: undefined,
  985. }
  986. );
  987. autoGroupedNode.groupCount = matchCount + 1;
  988. const start = index - matchCount;
  989. let start_timestamp = Number.MAX_SAFE_INTEGER;
  990. let timestamp = Number.MIN_SAFE_INTEGER;
  991. for (let j = start; j < start + matchCount + 1; j++) {
  992. const child = node.children[j];
  993. if (
  994. child.value &&
  995. 'timestamp' in child.value &&
  996. typeof child.value.timestamp === 'number' &&
  997. child.value.timestamp > timestamp
  998. ) {
  999. timestamp = child.value.timestamp;
  1000. }
  1001. if (
  1002. child.value &&
  1003. 'start_timestamp' in child.value &&
  1004. typeof child.value.start_timestamp === 'number' &&
  1005. child.value.start_timestamp < start_timestamp
  1006. ) {
  1007. start_timestamp = child.value.start_timestamp;
  1008. }
  1009. if (child.has_errors) {
  1010. for (const error of child.errors) {
  1011. autoGroupedNode.errors.add(error);
  1012. }
  1013. for (const performanceIssue of child.performance_issues) {
  1014. autoGroupedNode.performance_issues.add(performanceIssue);
  1015. }
  1016. }
  1017. autoGroupedNode.children.push(node.children[j]);
  1018. autoGroupedNode.children[autoGroupedNode.children.length - 1].parent =
  1019. autoGroupedNode;
  1020. }
  1021. autoGroupedNode.space = [
  1022. start_timestamp * autoGroupedNode.multiplier,
  1023. (timestamp - start_timestamp) * autoGroupedNode.multiplier,
  1024. ];
  1025. node.children.splice(start, matchCount + 1, autoGroupedNode);
  1026. index = start + 1;
  1027. matchCount = 0;
  1028. } else {
  1029. index++;
  1030. matchCount = 0;
  1031. }
  1032. }
  1033. }
  1034. }
  1035. collectMeasurements(
  1036. node: TraceTreeNode<TraceTree.NodeValue>,
  1037. start_timestamp: number,
  1038. measurements: Record<string, Measurement>,
  1039. vitals: Map<TraceTreeNode<TraceTree.NodeValue>, TraceTree.CollectedVital[]>,
  1040. vital_types: Set<'web' | 'mobile'>,
  1041. indicators: TraceTree.Indicator[]
  1042. ): void {
  1043. for (const measurement of COLLECTABLE_MEASUREMENTS) {
  1044. const value = measurements[measurement];
  1045. if (!value || typeof value.value !== 'number') {
  1046. continue;
  1047. }
  1048. if (!vitals.has(node)) {
  1049. vitals.set(node, []);
  1050. }
  1051. WEB_VITALS_LOOKUP.has(measurement) && vital_types.add('web');
  1052. MOBILE_VITALS_LOOKUP.has(measurement) && vital_types.add('mobile');
  1053. const vital = vitals.get(node)!;
  1054. vital.push({
  1055. key: measurement,
  1056. measurement: value,
  1057. });
  1058. if (!RENDERABLE_MEASUREMENTS[measurement]) {
  1059. continue;
  1060. }
  1061. const timestamp = measurementToTimestamp(
  1062. start_timestamp,
  1063. value.value,
  1064. value.unit ?? 'millisecond'
  1065. );
  1066. indicators.push({
  1067. start: timestamp,
  1068. duration: 0,
  1069. measurement: value,
  1070. poor: MEASUREMENT_THRESHOLDS[measurement]
  1071. ? value.value > MEASUREMENT_THRESHOLDS[measurement]
  1072. : false,
  1073. type: measurement as TraceTree.Indicator['type'],
  1074. label: (MEASUREMENT_ACRONYM_MAPPING[measurement] ?? measurement).toUpperCase(),
  1075. });
  1076. }
  1077. }
  1078. // Returns boolean to indicate if node was updated
  1079. expand(node: TraceTreeNode<TraceTree.NodeValue>, expanded: boolean): boolean {
  1080. if (expanded === node.expanded) {
  1081. return false;
  1082. }
  1083. // Expanding is not allowed for zoomed in nodes
  1084. if (node.zoomedIn) {
  1085. return false;
  1086. }
  1087. if (node instanceof ParentAutogroupNode) {
  1088. // In parent autogrouping, we perform a node swap and either point the
  1089. // head or tails of the autogrouped sequence to the autogrouped node
  1090. if (node.expanded) {
  1091. const index = this._list.indexOf(node);
  1092. const autogroupedChildren = node.getVisibleChildren();
  1093. this._list.splice(index + 1, autogroupedChildren.length);
  1094. const newChildren = node.tail.getVisibleChildren();
  1095. for (const c of node.tail.children) {
  1096. c.parent = node;
  1097. }
  1098. this._list.splice(index + 1, 0, ...newChildren);
  1099. } else {
  1100. node.head.parent = node;
  1101. const index = this._list.indexOf(node);
  1102. const childrenCount = node.getVisibleChildrenCount();
  1103. this._list.splice(index + 1, childrenCount);
  1104. const newChildren = [node.head].concat(
  1105. node.head.getVisibleChildren() as TraceTreeNode<TraceTree.Span>[]
  1106. );
  1107. for (const c of node.children) {
  1108. c.parent = node.tail;
  1109. }
  1110. this._list.splice(index + 1, 0, ...newChildren);
  1111. }
  1112. node.invalidate(node);
  1113. node.expanded = expanded;
  1114. return true;
  1115. }
  1116. if (node.expanded) {
  1117. const index = this._list.indexOf(node);
  1118. this._list.splice(index + 1, node.getVisibleChildrenCount());
  1119. // Flip expanded after collecting visible children
  1120. node.expanded = expanded;
  1121. } else {
  1122. const index = this._list.indexOf(node);
  1123. // Flip expanded so that we can collect visible children
  1124. node.expanded = expanded;
  1125. this._list.splice(index + 1, 0, ...node.getVisibleChildren());
  1126. }
  1127. node.expanded = expanded;
  1128. return true;
  1129. }
  1130. static ExpandToEventID(
  1131. eventId: string,
  1132. tree: TraceTree,
  1133. rerender: () => void,
  1134. options: ViewManagerScrollToOptions
  1135. ): Promise<{index: number; node: TraceTreeNode<TraceTree.NodeValue>} | null | null> {
  1136. const node = findInTreeByEventId(tree.root, eventId);
  1137. if (!node) {
  1138. return Promise.resolve(null);
  1139. }
  1140. return TraceTree.ExpandToPath(tree, node.path, rerender, options).then(
  1141. async result => {
  1142. // When users are coming off an eventID link, we want to fetch the children
  1143. // of the node that the eventID points to. This is because the eventID link
  1144. // only points to the transaction, but we want to fetch the children of the
  1145. // transaction to show the user the list of spans in that transaction
  1146. if (result?.node?.canFetch) {
  1147. await tree.zoomIn(result.node, true, options).catch(_e => {
  1148. Sentry.captureMessage('Failed to fetch children of eventId on mount');
  1149. });
  1150. return result;
  1151. }
  1152. return null;
  1153. }
  1154. );
  1155. }
  1156. static ExpandToPath(
  1157. tree: TraceTree,
  1158. scrollQueue: TraceTree.NodePath[],
  1159. rerender: () => void,
  1160. options: ViewManagerScrollToOptions
  1161. ): Promise<{index: number; node: TraceTreeNode<TraceTree.NodeValue>} | null | null> {
  1162. const segments = [...scrollQueue];
  1163. const list = tree.list;
  1164. if (!list) {
  1165. return Promise.resolve(null);
  1166. }
  1167. if (segments.length === 1 && segments[0] === 'trace-root') {
  1168. rerender();
  1169. return Promise.resolve({index: 0, node: tree.root.children[0]});
  1170. }
  1171. // Keep parent reference as we traverse the tree so that we can only
  1172. // perform searching in the current level and not the entire tree
  1173. let parent: TraceTreeNode<TraceTree.NodeValue> = tree.root;
  1174. const recurseToRow = async (): Promise<{
  1175. index: number;
  1176. node: TraceTreeNode<TraceTree.NodeValue>;
  1177. } | null | null> => {
  1178. const path = segments.pop();
  1179. let current = findInTreeFromSegment(parent, path!);
  1180. if (!current) {
  1181. // Some parts of the codebase link to span:span_id, txn:event_id, where span_id is
  1182. // actally stored on the txn:event_id node. Since we cant tell from the link itself
  1183. // that this is happening, we will perform a final check to see if we've actually already
  1184. // arrived to the node in the previous search call.
  1185. if (path) {
  1186. const [type, id] = path.split('-');
  1187. if (
  1188. type === 'span' &&
  1189. isTransactionNode(parent) &&
  1190. parent.value.span_id === id
  1191. ) {
  1192. current = parent;
  1193. }
  1194. }
  1195. if (!current) {
  1196. Sentry.captureMessage('Failed to scroll to node in trace tree');
  1197. return null;
  1198. }
  1199. }
  1200. // Reassing the parent to the current node so that
  1201. // searching narrows down to the current level
  1202. // and we dont need to search the entire tree each time
  1203. parent = current;
  1204. if (isTransactionNode(current)) {
  1205. const nextSegment = segments[segments.length - 1];
  1206. if (
  1207. nextSegment?.startsWith('span-') ||
  1208. nextSegment?.startsWith('empty-') ||
  1209. nextSegment?.startsWith('ag-') ||
  1210. nextSegment?.startsWith('ms-')
  1211. ) {
  1212. await tree.zoomIn(current, true, options);
  1213. return recurseToRow();
  1214. }
  1215. }
  1216. if (isAutogroupedNode(current) && segments.length > 0) {
  1217. tree.expand(current, true);
  1218. return recurseToRow();
  1219. }
  1220. if (segments.length > 0) {
  1221. return recurseToRow();
  1222. }
  1223. // We are at the last path segment (the node that the user clicked on)
  1224. // and we should scroll the view to this node.
  1225. let index = current ? tree.list.findIndex(node => node === current) : -1;
  1226. // We have found the node, yet it is somehow not in the visible tree.
  1227. // This means that the path we were given did not match the current tree.
  1228. // This sometimes happens when we receive external links like span-x, txn-y
  1229. // however the resulting tree looks like span-x, autogroup, txn-y. In this case,
  1230. // we should expand the autogroup node and try to find the node again.
  1231. if (current && index === -1) {
  1232. let parent_node = current.parent;
  1233. while (parent_node) {
  1234. // Transactions break autogrouping chains, so we can stop here
  1235. if (isTransactionNode(parent_node)) {
  1236. break;
  1237. }
  1238. if (isAutogroupedNode(parent_node)) {
  1239. tree.expand(parent_node, true);
  1240. index = current ? tree.list.findIndex(node => node === current) : -1;
  1241. // This is very wasteful as it performs O(n^2) search each time we expand a node...
  1242. // In most cases though, we should be operating on a tree with sub 10k elements and hopefully
  1243. // a low autogrouped node count.
  1244. if (index !== -1) {
  1245. break;
  1246. }
  1247. }
  1248. parent_node = parent_node.parent;
  1249. }
  1250. }
  1251. if (index === -1) {
  1252. throw new Error(`Couldn't find node in list ${scrollQueue.join(',')}`);
  1253. }
  1254. rerender();
  1255. return {index, node: current};
  1256. };
  1257. return recurseToRow();
  1258. }
  1259. zoomIn(
  1260. node: TraceTreeNode<TraceTree.NodeValue>,
  1261. zoomedIn: boolean,
  1262. options: {
  1263. api: Client;
  1264. organization: Organization;
  1265. }
  1266. ): Promise<Event | null> {
  1267. if (zoomedIn === node.zoomedIn) {
  1268. return Promise.resolve(null);
  1269. }
  1270. if (!zoomedIn) {
  1271. const index = this._list.indexOf(node);
  1272. if (index === -1) {
  1273. return Promise.resolve(null);
  1274. }
  1275. const childrenCount = node.getVisibleChildrenCount();
  1276. this._list.splice(index + 1, childrenCount);
  1277. node.zoomedIn = zoomedIn;
  1278. node.invalidate(node);
  1279. if (node.expanded) {
  1280. this._list.splice(index + 1, 0, ...node.getVisibleChildren());
  1281. }
  1282. return Promise.resolve(null);
  1283. }
  1284. const key = cacheKey(
  1285. options.organization,
  1286. node.metadata.project_slug!,
  1287. node.metadata.event_id!
  1288. );
  1289. const promise =
  1290. this._spanPromises.get(key) ??
  1291. fetchTransactionSpans(
  1292. options.api,
  1293. options.organization,
  1294. node.metadata.project_slug!,
  1295. node.metadata.event_id!
  1296. );
  1297. node.fetchStatus = 'loading';
  1298. promise
  1299. .then(data => {
  1300. // The user may have collapsed the node before the promise resolved. When that
  1301. // happens, dont update the tree with the resolved data. Alternatively, we could implement
  1302. // a cancellable promise and avoid this cumbersome heuristic.
  1303. node.fetchStatus = 'resolved';
  1304. if (!node.expanded) {
  1305. return data;
  1306. }
  1307. const spans = data.entries.find(s => s.type === 'spans') ?? {data: []};
  1308. // Remove existing entries from the list
  1309. const index = this._list.indexOf(node);
  1310. if (index === -1) {
  1311. return data;
  1312. }
  1313. if (node.expanded) {
  1314. const childrenCount = node.getVisibleChildrenCount();
  1315. if (childrenCount > 0) {
  1316. this._list.splice(index + 1, childrenCount);
  1317. }
  1318. }
  1319. // Api response is not sorted
  1320. spans.data.sort((a, b) => a.start_timestamp - b.start_timestamp);
  1321. const [_, view] = TraceTree.FromSpans(node, data, spans.data, {
  1322. sdk: data.sdk?.name,
  1323. });
  1324. // Spans contain millisecond precision, which means that it is possible for the
  1325. // children spans of a transaction to extend beyond the start and end of the transaction
  1326. // through ns precision. To account for this, we need to adjust the space of the transaction node and the space
  1327. // of our trace so that all of the span children are visible and can be rendered inside the view.
  1328. if (
  1329. view &&
  1330. Number.isFinite(view[0]) &&
  1331. Number.isFinite(view[1]) &&
  1332. this.root.space
  1333. ) {
  1334. const prev_start = this.root.space[0];
  1335. const prev_end = this.root.space[1];
  1336. const new_start = view[0];
  1337. const new_end = view[1];
  1338. // Update the space of the tree and the trace root node
  1339. this.root.space = [
  1340. Math.min(new_start * node.multiplier, this.root.space[0]),
  1341. Math.max(new_end * node.multiplier - prev_start, this.root.space[1]),
  1342. ];
  1343. this.root.children[0].space = [...this.root.space];
  1344. if (prev_start !== this.root.space[0] || prev_end !== this.root.space[1]) {
  1345. this.dispatch('trace timeline change', this.root.space);
  1346. }
  1347. }
  1348. const spanChildren = node.getVisibleChildren();
  1349. this._list.splice(index + 1, 0, ...spanChildren);
  1350. return data;
  1351. })
  1352. .catch(_e => {
  1353. node.fetchStatus = 'error';
  1354. });
  1355. this._spanPromises.set(key, promise);
  1356. return promise;
  1357. }
  1358. toList(): TraceTreeNode<TraceTree.NodeValue>[] {
  1359. const list: TraceTreeNode<TraceTree.NodeValue>[] = [];
  1360. function visit(node: TraceTreeNode<TraceTree.NodeValue>) {
  1361. list.push(node);
  1362. if (!node.expanded) {
  1363. return;
  1364. }
  1365. for (const child of node.children) {
  1366. visit(child);
  1367. }
  1368. }
  1369. for (const child of this.root.children) {
  1370. visit(child);
  1371. }
  1372. return list;
  1373. }
  1374. get list(): ReadonlyArray<TraceTreeNode<TraceTree.NodeValue>> {
  1375. return this._list;
  1376. }
  1377. listeners: TraceTree.EventStore = {
  1378. 'trace timeline change': new Set(),
  1379. };
  1380. on<K extends keyof TraceTree.TraceTreeEvents>(
  1381. event: K,
  1382. cb: TraceTree.TraceTreeEvents[K]
  1383. ): void {
  1384. this.listeners[event].add(cb);
  1385. }
  1386. off<K extends keyof TraceTree.TraceTreeEvents>(
  1387. event: K,
  1388. cb: TraceTree.TraceTreeEvents[K]
  1389. ): void {
  1390. this.listeners[event].delete(cb);
  1391. }
  1392. dispatch<K extends keyof TraceTree.TraceTreeEvents>(
  1393. event: K,
  1394. ...args: ArgumentTypes<TraceTree.TraceTreeEvents[K]>
  1395. ): void {
  1396. if (!this.listeners[event]) {
  1397. return;
  1398. }
  1399. for (const handler of this.listeners[event]) {
  1400. // @ts-expect-error
  1401. handler(...args);
  1402. }
  1403. }
  1404. /**
  1405. * Prints the tree in a human readable format, useful for debugging and testing
  1406. */
  1407. print() {
  1408. // root nodes are -1 indexed, so we add 1 to the depth so .repeat doesnt throw
  1409. const print = this.list
  1410. .map(t => printNode(t, 0))
  1411. .filter(Boolean)
  1412. .join('\n');
  1413. // eslint-disable-next-line no-console
  1414. console.log(print);
  1415. }
  1416. build() {
  1417. this._list = this.toList();
  1418. return this;
  1419. }
  1420. }
  1421. export class TraceTreeNode<T extends TraceTree.NodeValue = TraceTree.NodeValue> {
  1422. canFetch: boolean = false;
  1423. fetchStatus: 'resolved' | 'error' | 'idle' | 'loading' = 'idle';
  1424. parent: TraceTreeNode | null = null;
  1425. value: T;
  1426. expanded: boolean = false;
  1427. zoomedIn: boolean = false;
  1428. metadata: TraceTree.Metadata = {
  1429. project_slug: undefined,
  1430. event_id: undefined,
  1431. };
  1432. errors: Set<TraceErrorType> = new Set<TraceErrorType>();
  1433. performance_issues: Set<TraceTree.TracePerformanceIssue> =
  1434. new Set<TraceTree.TracePerformanceIssue>();
  1435. profiles: TraceTree.Profile[] = [];
  1436. multiplier: number;
  1437. space: [number, number] = [0, 0];
  1438. private unit = 'milliseconds' as const;
  1439. private _depth: number | undefined;
  1440. private _children: TraceTreeNode[] = [];
  1441. private _spanChildren: TraceTreeNode[] = [];
  1442. private _connectors: number[] | undefined = undefined;
  1443. constructor(parent: TraceTreeNode | null, value: T, metadata: TraceTree.Metadata) {
  1444. this.parent = parent ?? null;
  1445. this.value = value;
  1446. this.metadata = metadata;
  1447. this.multiplier = this.unit === 'milliseconds' ? 1e3 : 1;
  1448. if (
  1449. value &&
  1450. 'timestamp' in value &&
  1451. 'start_timestamp' in value &&
  1452. typeof value.timestamp === 'number' &&
  1453. typeof value.start_timestamp === 'number'
  1454. ) {
  1455. this.space = [
  1456. value.start_timestamp * this.multiplier,
  1457. (value.timestamp - value.start_timestamp) * this.multiplier,
  1458. ];
  1459. } else if (value && 'timestamp' in value && typeof value.timestamp === 'number') {
  1460. this.space = [value.timestamp * this.multiplier, 0];
  1461. }
  1462. if (
  1463. isTraceErrorNode(this) &&
  1464. 'timestamp' in this.value &&
  1465. typeof this.value.timestamp === 'number'
  1466. ) {
  1467. this.space = [this.value.timestamp * this.multiplier, 0];
  1468. }
  1469. if (value && 'profile_id' in value && typeof value.profile_id === 'string') {
  1470. this.profiles.push({profile_id: value.profile_id, space: this.space ?? [0, 0]});
  1471. }
  1472. if (isTransactionNode(this)) {
  1473. this.canFetch = true;
  1474. }
  1475. if (isTransactionNode(this) || isTraceNode(this) || isSpanNode(this)) {
  1476. this.expanded = true;
  1477. }
  1478. if (shouldCollapseNodeByDefault(this)) {
  1479. this.expanded = false;
  1480. }
  1481. if (isTransactionNode(this)) {
  1482. this.errors = new Set(this.value.errors);
  1483. this.performance_issues = new Set(this.value.performance_issues);
  1484. }
  1485. // For error nodes, its value is the only associated issue.
  1486. if (isTraceErrorNode(this)) {
  1487. this.errors = new Set([this.value]);
  1488. }
  1489. }
  1490. cloneDeep():
  1491. | TraceTreeNode<T>
  1492. | ParentAutogroupNode
  1493. | SiblingAutogroupNode
  1494. | NoDataNode
  1495. | MissingInstrumentationNode {
  1496. let clone:
  1497. | TraceTreeNode<T>
  1498. | ParentAutogroupNode
  1499. | SiblingAutogroupNode
  1500. | NoDataNode
  1501. | MissingInstrumentationNode;
  1502. if (isParentAutogroupedNode(this)) {
  1503. clone = new ParentAutogroupNode(
  1504. this.parent,
  1505. this.value,
  1506. this.metadata,
  1507. this.head,
  1508. this.tail
  1509. );
  1510. clone.groupCount = this.groupCount;
  1511. } else if (isSiblingAutogroupedNode(this)) {
  1512. clone = new SiblingAutogroupNode(this.parent, this.value, this.metadata);
  1513. clone.groupCount = this.groupCount;
  1514. } else if (isNoDataNode(this)) {
  1515. clone = new NoDataNode(this.parent);
  1516. } else if (isMissingInstrumentationNode(this)) {
  1517. clone = new MissingInstrumentationNode(
  1518. this.parent!,
  1519. this.value,
  1520. this.metadata,
  1521. this.previous,
  1522. this.next
  1523. );
  1524. } else {
  1525. clone = new TraceTreeNode(this.parent, this.value, this.metadata);
  1526. }
  1527. if (!clone) {
  1528. throw new Error('CloneDeep is not implemented');
  1529. }
  1530. clone.expanded = this.expanded;
  1531. clone.zoomedIn = this.zoomedIn;
  1532. clone.canFetch = this.canFetch;
  1533. clone.fetchStatus = this.fetchStatus;
  1534. clone.space = this.space;
  1535. clone.metadata = this.metadata;
  1536. if (isParentAutogroupedNode(clone)) {
  1537. clone.head = clone.head.cloneDeep() as TraceTreeNode<TraceTree.Span>;
  1538. clone.tail = clone.tail.cloneDeep() as TraceTreeNode<TraceTree.Span>;
  1539. clone.head.parent = clone;
  1540. // If the node is not expanded, the parent of the tail points to the
  1541. // autogrouped clone. If the node is expanded, the parent of the children
  1542. // of the tail points to the autogrouped clone.
  1543. if (!clone.expanded) {
  1544. for (const c of clone.tail.children) {
  1545. c.parent = clone;
  1546. }
  1547. } else {
  1548. for (const c of clone.children) {
  1549. c.parent = clone.tail;
  1550. }
  1551. }
  1552. clone.head.parent = clone;
  1553. clone.tail.parent = clone;
  1554. } else if (isSiblingAutogroupedNode(clone)) {
  1555. for (const child of this.children) {
  1556. const childClone = child.cloneDeep() as TraceTreeNode<TraceTree.Span>;
  1557. clone.children.push(childClone);
  1558. childClone.parent = clone;
  1559. }
  1560. } else {
  1561. for (const child of this.children) {
  1562. const childClone = child.cloneDeep() as TraceTreeNode<TraceTree.Span>;
  1563. clone.children.push(childClone);
  1564. childClone.parent = clone;
  1565. }
  1566. }
  1567. return clone;
  1568. }
  1569. get isOrphaned() {
  1570. return this.parent?.value && 'orphan_errors' in this.parent.value;
  1571. }
  1572. get isLastChild() {
  1573. if (!this.parent || this.parent.children.length === 0) {
  1574. return true;
  1575. }
  1576. return this.parent.children[this.parent.children.length - 1] === this;
  1577. }
  1578. /**
  1579. * Return a lazily calculated depth of the node in the tree.
  1580. * Root node has a value of -1 as it is abstract.
  1581. */
  1582. get depth(): number {
  1583. if (typeof this._depth === 'number') {
  1584. return this._depth;
  1585. }
  1586. let depth = -2;
  1587. let node: TraceTreeNode<any> | null = this;
  1588. while (node) {
  1589. if (typeof node.parent?.depth === 'number') {
  1590. this._depth = node.parent.depth + 1;
  1591. return this._depth;
  1592. }
  1593. depth++;
  1594. node = node.parent;
  1595. }
  1596. this._depth = depth;
  1597. return this._depth;
  1598. }
  1599. get has_errors(): boolean {
  1600. return this.errors.size > 0 || this.performance_issues.size > 0;
  1601. }
  1602. get parent_transaction(): TraceTreeNode<TraceTree.Transaction> | null {
  1603. let node: TraceTreeNode<TraceTree.NodeValue> | null = this.parent;
  1604. while (node) {
  1605. if (isTransactionNode(node)) {
  1606. return node;
  1607. }
  1608. node = node.parent;
  1609. }
  1610. return null;
  1611. }
  1612. /**
  1613. * Returns the depth levels at which the row should draw vertical connectors
  1614. * negative values mean connector points to an orphaned node
  1615. */
  1616. get connectors(): number[] {
  1617. if (this._connectors !== undefined) {
  1618. return this._connectors!;
  1619. }
  1620. this._connectors = [];
  1621. if (!this.parent) {
  1622. return this._connectors;
  1623. }
  1624. if (this.parent?.connectors !== undefined) {
  1625. this._connectors = [...this.parent.connectors];
  1626. if (this.isLastChild || this.value === null) {
  1627. return this._connectors;
  1628. }
  1629. this.connectors.push(this.isOrphaned ? -this.depth : this.depth);
  1630. return this._connectors;
  1631. }
  1632. let node: TraceTreeNode<T> | TraceTreeNode<TraceTree.NodeValue> | null = this.parent;
  1633. while (node) {
  1634. if (node.value === null) {
  1635. break;
  1636. }
  1637. if (node.isLastChild) {
  1638. node = node.parent;
  1639. continue;
  1640. }
  1641. this._connectors.push(node.isOrphaned ? -node.depth : node.depth);
  1642. node = node.parent;
  1643. }
  1644. return this._connectors;
  1645. }
  1646. /**
  1647. * Returns the children that the node currently points to.
  1648. * The logic here is a consequence of the tree design, where we want to be able to store
  1649. * both transaction and span nodes in the same tree. This results in an annoying API where
  1650. * we either store span children separately or transaction children separately. A better design
  1651. * would have been to create an invisible meta node that always points to the correct children.
  1652. */
  1653. get children(): TraceTreeNode[] {
  1654. if (isAutogroupedNode(this)) {
  1655. return this._children;
  1656. }
  1657. if (isSpanNode(this)) {
  1658. return this.canFetch && !this.zoomedIn ? [] : this.spanChildren;
  1659. }
  1660. if (isTransactionNode(this)) {
  1661. return this.zoomedIn ? this._spanChildren : this._children;
  1662. }
  1663. return this._children;
  1664. }
  1665. set children(children: TraceTreeNode[]) {
  1666. this._children = children;
  1667. }
  1668. get spanChildren(): (TraceTreeNode | NoDataNode)[] {
  1669. return this._spanChildren;
  1670. }
  1671. private _max_severity: keyof Theme['level'] | undefined;
  1672. get max_severity(): keyof Theme['level'] {
  1673. if (this._max_severity) {
  1674. return this._max_severity;
  1675. }
  1676. for (const error of this.errors) {
  1677. if (error.level === 'error' || error.level === 'fatal') {
  1678. this._max_severity = error.level;
  1679. return this.max_severity;
  1680. }
  1681. }
  1682. return 'default';
  1683. }
  1684. /**
  1685. * Invalidate the visual data used to render the tree, forcing it
  1686. * to be recalculated on the next render. This is useful when for example
  1687. * the tree is expanded or collapsed, or when the tree is mutated and
  1688. * the visual data is no longer valid as the indentation changes
  1689. */
  1690. invalidate(root?: TraceTreeNode<TraceTree.NodeValue>) {
  1691. this._connectors = undefined;
  1692. this._depth = undefined;
  1693. if (root) {
  1694. const queue = [...this.children];
  1695. if (isParentAutogroupedNode(this)) {
  1696. queue.push(this.head);
  1697. }
  1698. while (queue.length > 0) {
  1699. const next = queue.pop()!;
  1700. next.invalidate();
  1701. if (isParentAutogroupedNode(next)) {
  1702. queue.push(next.head);
  1703. }
  1704. for (let i = 0; i < next.children.length; i++) {
  1705. queue.push(next.children[i]);
  1706. }
  1707. }
  1708. }
  1709. }
  1710. getVisibleChildrenCount(): number {
  1711. const stack: TraceTreeNode<TraceTree.NodeValue>[] = [];
  1712. let count = 0;
  1713. if (isParentAutogroupedNode(this)) {
  1714. if (this.expanded) {
  1715. return this.head.getVisibleChildrenCount();
  1716. }
  1717. return this.tail.getVisibleChildrenCount();
  1718. }
  1719. if (this.expanded || isMissingInstrumentationNode(this)) {
  1720. for (let i = this.children.length - 1; i >= 0; i--) {
  1721. stack.push(this.children[i]);
  1722. }
  1723. }
  1724. while (stack.length > 0) {
  1725. const node = stack.pop()!;
  1726. count++;
  1727. // Since we're using a stack and it's LIFO, reverse the children before pushing them
  1728. // to ensure they are processed in the original left-to-right order.
  1729. if (node.expanded || isParentAutogroupedNode(node)) {
  1730. for (let i = node.children.length - 1; i >= 0; i--) {
  1731. stack.push(node.children[i]);
  1732. }
  1733. }
  1734. }
  1735. return count;
  1736. }
  1737. getVisibleChildren(): TraceTreeNode<TraceTree.NodeValue>[] {
  1738. const stack: TraceTreeNode<TraceTree.NodeValue>[] = [];
  1739. const children: TraceTreeNode<TraceTree.NodeValue>[] = [];
  1740. if (
  1741. this.expanded ||
  1742. isParentAutogroupedNode(this) ||
  1743. isMissingInstrumentationNode(this)
  1744. ) {
  1745. for (let i = this.children.length - 1; i >= 0; i--) {
  1746. stack.push(this.children[i]);
  1747. }
  1748. }
  1749. while (stack.length > 0) {
  1750. const node = stack.pop()!;
  1751. children.push(node);
  1752. // Since we're using a stack and it's LIFO, reverse the children before pushing them
  1753. // to ensure they are processed in the original left-to-right order.
  1754. if (node.expanded || isParentAutogroupedNode(node)) {
  1755. for (let i = node.children.length - 1; i >= 0; i--) {
  1756. stack.push(node.children[i]);
  1757. }
  1758. }
  1759. }
  1760. return children;
  1761. }
  1762. // Returns the min path required to reach the node from the root.
  1763. // @TODO: skip nodes that do not require fetching
  1764. get path(): TraceTree.NodePath[] {
  1765. const nodes: TraceTreeNode<TraceTree.NodeValue>[] = [this];
  1766. let current: TraceTreeNode<TraceTree.NodeValue> | null = this.parent;
  1767. if (isSpanNode(this) || isAutogroupedNode(this)) {
  1768. while (
  1769. current &&
  1770. (isSpanNode(current) || (isAutogroupedNode(current) && !current.expanded))
  1771. ) {
  1772. current = current.parent;
  1773. }
  1774. }
  1775. while (current) {
  1776. if (isTransactionNode(current)) {
  1777. nodes.push(current);
  1778. }
  1779. if (isSpanNode(current)) {
  1780. nodes.push(current);
  1781. while (current.parent) {
  1782. if (isTransactionNode(current.parent)) {
  1783. break;
  1784. }
  1785. if (isAutogroupedNode(current.parent) && current.parent.expanded) {
  1786. break;
  1787. }
  1788. current = current.parent;
  1789. }
  1790. }
  1791. if (isAutogroupedNode(current)) {
  1792. nodes.push(current);
  1793. }
  1794. current = current.parent;
  1795. }
  1796. return nodes.map(nodeToId);
  1797. }
  1798. print() {
  1799. // root nodes are -1 indexed, so we add 1 to the depth so .repeat doesnt throw
  1800. const offset = this.depth === -1 ? 1 : 0;
  1801. const nodes = [this, ...this.getVisibleChildren()];
  1802. const print = nodes
  1803. .map(t => printNode(t, offset))
  1804. .filter(Boolean)
  1805. .join('\n');
  1806. // eslint-disable-next-line no-console
  1807. console.log(print);
  1808. }
  1809. static Find(
  1810. root: TraceTreeNode<TraceTree.NodeValue>,
  1811. predicate: (node: TraceTreeNode<TraceTree.NodeValue>) => boolean
  1812. ): TraceTreeNode<TraceTree.NodeValue> | null {
  1813. const queue = [root];
  1814. while (queue.length > 0) {
  1815. const next = queue.pop()!;
  1816. if (predicate(next)) {
  1817. return next;
  1818. }
  1819. if (isParentAutogroupedNode(next)) {
  1820. queue.push(next.head);
  1821. } else {
  1822. for (const child of next.children) {
  1823. queue.push(child);
  1824. }
  1825. }
  1826. }
  1827. return null;
  1828. }
  1829. static ForEachChild(
  1830. root: TraceTreeNode<TraceTree.NodeValue>,
  1831. cb: (node: TraceTreeNode<TraceTree.NodeValue>) => void
  1832. ): void {
  1833. const queue = [root];
  1834. while (queue.length > 0) {
  1835. const next = queue.pop()!;
  1836. cb(next);
  1837. if (isParentAutogroupedNode(next)) {
  1838. queue.push(next.head);
  1839. } else {
  1840. const children = next.spanChildren ? next.spanChildren : next.children;
  1841. for (const child of children) {
  1842. queue.push(child);
  1843. }
  1844. }
  1845. }
  1846. }
  1847. static Root() {
  1848. return new TraceTreeNode(null, null, {
  1849. event_id: undefined,
  1850. project_slug: undefined,
  1851. });
  1852. }
  1853. }
  1854. export class MissingInstrumentationNode extends TraceTreeNode<TraceTree.MissingInstrumentationSpan> {
  1855. next: TraceTreeNode<TraceTree.Span>;
  1856. previous: TraceTreeNode<TraceTree.Span>;
  1857. constructor(
  1858. parent: TraceTreeNode<TraceTree.NodeValue>,
  1859. node: TraceTree.MissingInstrumentationSpan,
  1860. metadata: TraceTree.Metadata,
  1861. previous: TraceTreeNode<TraceTree.Span>,
  1862. next: TraceTreeNode<TraceTree.Span>
  1863. ) {
  1864. super(parent, node, metadata);
  1865. this.next = next;
  1866. this.previous = previous;
  1867. }
  1868. }
  1869. export class ParentAutogroupNode extends TraceTreeNode<TraceTree.ChildrenAutogroup> {
  1870. head: TraceTreeNode<TraceTree.Span>;
  1871. tail: TraceTreeNode<TraceTree.Span>;
  1872. groupCount: number = 0;
  1873. profiles: TraceTree.Profile[] = [];
  1874. private _autogroupedSegments: [number, number][] | undefined;
  1875. constructor(
  1876. parent: TraceTreeNode<TraceTree.NodeValue> | null,
  1877. node: TraceTree.ChildrenAutogroup,
  1878. metadata: TraceTree.Metadata,
  1879. head: TraceTreeNode<TraceTree.Span>,
  1880. tail: TraceTreeNode<TraceTree.Span>
  1881. ) {
  1882. super(parent, node, metadata);
  1883. this.expanded = false;
  1884. this.head = head;
  1885. this.tail = tail;
  1886. }
  1887. get children() {
  1888. if (this.expanded) {
  1889. return [this.head];
  1890. }
  1891. return this.tail.children;
  1892. }
  1893. get has_errors(): boolean {
  1894. return this.errors.size > 0 || this.performance_issues.size > 0;
  1895. }
  1896. get autogroupedSegments(): [number, number][] {
  1897. if (this._autogroupedSegments) {
  1898. return this._autogroupedSegments;
  1899. }
  1900. const children: TraceTreeNode<TraceTree.NodeValue>[] = [];
  1901. let start: TraceTreeNode<TraceTree.NodeValue> | undefined = this.head;
  1902. while (start && start !== this.tail) {
  1903. children.push(start);
  1904. start = start.children[0];
  1905. }
  1906. children.push(this.tail);
  1907. this._autogroupedSegments = computeAutogroupedBarSegments(children);
  1908. return this._autogroupedSegments;
  1909. }
  1910. }
  1911. export class SiblingAutogroupNode extends TraceTreeNode<TraceTree.SiblingAutogroup> {
  1912. groupCount: number = 0;
  1913. profiles: TraceTree.Profile[] = [];
  1914. private _autogroupedSegments: [number, number][] | undefined;
  1915. constructor(
  1916. parent: TraceTreeNode<TraceTree.NodeValue> | null,
  1917. node: TraceTree.SiblingAutogroup,
  1918. metadata: TraceTree.Metadata
  1919. ) {
  1920. super(parent, node, metadata);
  1921. this.expanded = false;
  1922. }
  1923. get has_errors(): boolean {
  1924. return this.errors.size > 0 || this.performance_issues.size > 0;
  1925. }
  1926. get autogroupedSegments(): [number, number][] {
  1927. if (this._autogroupedSegments) {
  1928. return this._autogroupedSegments;
  1929. }
  1930. this._autogroupedSegments = computeAutogroupedBarSegments(this.children);
  1931. return this._autogroupedSegments;
  1932. }
  1933. }
  1934. export class NoDataNode extends TraceTreeNode<null> {
  1935. constructor(parent: TraceTreeNode<TraceTree.NodeValue> | null) {
  1936. super(parent, null, {
  1937. event_id: undefined,
  1938. project_slug: undefined,
  1939. });
  1940. }
  1941. }
  1942. // Generates a ID of the tree node based on its type
  1943. function nodeToId(n: TraceTreeNode<TraceTree.NodeValue>): TraceTree.NodePath {
  1944. if (isAutogroupedNode(n)) {
  1945. if (isParentAutogroupedNode(n)) {
  1946. return `ag-${n.head.value.span_id}`;
  1947. }
  1948. if (isSiblingAutogroupedNode(n)) {
  1949. const child = n.children[0];
  1950. if (isSpanNode(child)) {
  1951. return `ag-${child.value.span_id}`;
  1952. }
  1953. }
  1954. }
  1955. if (isTransactionNode(n)) {
  1956. return `txn-${n.value.event_id}`;
  1957. }
  1958. if (isSpanNode(n)) {
  1959. return `span-${n.value.span_id}`;
  1960. }
  1961. if (isTraceNode(n)) {
  1962. return `trace-root`;
  1963. }
  1964. if (isTraceErrorNode(n)) {
  1965. return `error-${n.value.event_id}`;
  1966. }
  1967. if (isNoDataNode(n)) {
  1968. return `empty-node`;
  1969. }
  1970. if (isRootNode(n)) {
  1971. throw new Error('A path to root node does not exist as the node is virtual');
  1972. }
  1973. if (isMissingInstrumentationNode(n)) {
  1974. if (n.previous) {
  1975. return `ms-${n.previous.value.span_id}`;
  1976. }
  1977. if (n.next) {
  1978. return `ms-${n.next.value.span_id}`;
  1979. }
  1980. throw new Error('Missing instrumentation node must have a previous or next node');
  1981. }
  1982. throw new Error('Not implemented');
  1983. }
  1984. // Returns a list of segments from a grouping sequence that can be used to render a span bar chart
  1985. // It looks for gaps between spans and creates a segment for each gap. If there are no gaps, it
  1986. // merges the n and n+1 segments.
  1987. export function computeAutogroupedBarSegments(
  1988. nodes: TraceTreeNode<TraceTree.NodeValue>[]
  1989. ): [number, number][] {
  1990. if (nodes.length === 0) {
  1991. return [];
  1992. }
  1993. if (nodes.length === 1) {
  1994. const space = nodes[0].space;
  1995. if (!space) {
  1996. throw new Error(
  1997. 'Autogrouped node child has no defined space. This should not happen.'
  1998. );
  1999. }
  2000. return [space];
  2001. }
  2002. const first = nodes[0];
  2003. const multiplier = first.multiplier;
  2004. if (!isSpanNode(first)) {
  2005. throw new Error('Autogrouped node must have span children');
  2006. }
  2007. const segments: [number, number][] = [];
  2008. let start = first.value.start_timestamp;
  2009. let end = first.value.timestamp;
  2010. let i = 1;
  2011. while (i < nodes.length) {
  2012. const next = nodes[i];
  2013. if (!isSpanNode(next)) {
  2014. throw new Error('Autogrouped node must have span children');
  2015. }
  2016. if (next.value.start_timestamp > end) {
  2017. segments.push([start * multiplier, (end - start) * multiplier]);
  2018. start = next.value.start_timestamp;
  2019. end = next.value.timestamp;
  2020. i++;
  2021. } else {
  2022. end = next.value.timestamp;
  2023. i++;
  2024. }
  2025. }
  2026. segments.push([start * multiplier, (end - start) * multiplier]);
  2027. return segments;
  2028. }
  2029. // Returns a list of errors related to the txn with ids matching the span id
  2030. function getRelatedSpanErrorsFromTransaction(
  2031. span: RawSpanType,
  2032. node?: TraceTreeNode<TraceTree.NodeValue>
  2033. ): TraceErrorType[] {
  2034. if (!node || !node.value || !isTransactionNode(node)) {
  2035. return [];
  2036. }
  2037. if (!node?.value?.errors?.length) {
  2038. return [];
  2039. }
  2040. const errors: TraceErrorType[] = [];
  2041. for (const error of node.value.errors) {
  2042. if (error.span === span.span_id) {
  2043. errors.push(error);
  2044. }
  2045. }
  2046. return errors;
  2047. }
  2048. // Returns a list of performance errors related to the txn with ids matching the span id
  2049. function getRelatedPerformanceIssuesFromTransaction(
  2050. span: RawSpanType,
  2051. node?: TraceTreeNode<TraceTree.NodeValue>
  2052. ): TraceTree.TracePerformanceIssue[] {
  2053. if (!node || !node.value || !isTransactionNode(node)) {
  2054. return [];
  2055. }
  2056. if (!node?.value?.performance_issues?.length) {
  2057. return [];
  2058. }
  2059. const performanceIssues: TraceTree.TracePerformanceIssue[] = [];
  2060. for (const perfIssue of node.value.performance_issues) {
  2061. for (const s of perfIssue.span) {
  2062. if (s === span.span_id) {
  2063. performanceIssues.push(perfIssue);
  2064. }
  2065. }
  2066. for (const suspect of perfIssue.suspect_spans) {
  2067. if (suspect === span.span_id) {
  2068. performanceIssues.push(perfIssue);
  2069. }
  2070. }
  2071. }
  2072. return performanceIssues;
  2073. }
  2074. function hasEventWithEventId(
  2075. node: TraceTreeNode<TraceTree.NodeValue>,
  2076. eventId: string
  2077. ): boolean {
  2078. // Skip trace nodes since they accumulate all errors and performance issues
  2079. // in the trace and is not an event.
  2080. if (isTraceNode(node)) {
  2081. return false;
  2082. }
  2083. // Search in errors
  2084. if (node.errors.size > 0) {
  2085. for (const e of node.errors) {
  2086. if (e.event_id === eventId) {
  2087. return true;
  2088. }
  2089. }
  2090. }
  2091. // Search in performance issues
  2092. if (node.performance_issues.size > 0) {
  2093. for (const p of node.performance_issues) {
  2094. if (p.event_id === eventId) {
  2095. return true;
  2096. }
  2097. }
  2098. }
  2099. // Check if we are maybe looking for the profile_id
  2100. if (node.value && 'profile_id' in node.value && node.value.profile_id === eventId) {
  2101. return true;
  2102. }
  2103. return false;
  2104. }
  2105. function findInTreeByEventId(start: TraceTreeNode<TraceTree.NodeValue>, eventId: string) {
  2106. return TraceTreeNode.Find(start, node => {
  2107. if (isTransactionNode(node)) {
  2108. if (node.value.event_id === eventId) {
  2109. return true;
  2110. }
  2111. } else if (isSpanNode(node)) {
  2112. return node.value.span_id === eventId;
  2113. } else if (isTraceErrorNode(node)) {
  2114. return node.value.event_id === eventId;
  2115. }
  2116. return hasEventWithEventId(node, eventId);
  2117. });
  2118. }
  2119. function findInTreeFromSegment(
  2120. start: TraceTreeNode<TraceTree.NodeValue>,
  2121. segment: TraceTree.NodePath
  2122. ): TraceTreeNode<TraceTree.NodeValue> | null {
  2123. const [type, id] = segment.split('-');
  2124. if (!type || !id) {
  2125. throw new TypeError('Node path must be in the format of `type-id`');
  2126. }
  2127. return TraceTreeNode.Find(start, node => {
  2128. if (type === 'txn' && isTransactionNode(node)) {
  2129. return node.value.event_id === id;
  2130. }
  2131. if (type === 'span' && isSpanNode(node)) {
  2132. return node.value.span_id === id;
  2133. }
  2134. if (type === 'ag' && isAutogroupedNode(node)) {
  2135. if (isParentAutogroupedNode(node)) {
  2136. return node.head.value.span_id === id || node.tail.value.span_id === id;
  2137. }
  2138. if (isSiblingAutogroupedNode(node)) {
  2139. const child = node.children[0];
  2140. if (isSpanNode(child)) {
  2141. return child.value.span_id === id;
  2142. }
  2143. }
  2144. }
  2145. if (type === 'ms' && isMissingInstrumentationNode(node)) {
  2146. return node.previous.value.span_id === id || node.next.value.span_id === id;
  2147. }
  2148. if (type === 'error' && isTraceErrorNode(node)) {
  2149. return node.value.event_id === id;
  2150. }
  2151. if (type === 'empty' && isNoDataNode(node)) {
  2152. return true;
  2153. }
  2154. return false;
  2155. });
  2156. }
  2157. function printNode(t: TraceTreeNode<TraceTree.NodeValue>, offset: number): string {
  2158. // +1 because we may be printing from the root which is -1 indexed
  2159. const padding = ' '.repeat(t.depth + offset);
  2160. if (isAutogroupedNode(t)) {
  2161. if (isParentAutogroupedNode(t)) {
  2162. return padding + `parent autogroup (${t.groupCount})`;
  2163. }
  2164. if (isSiblingAutogroupedNode(t)) {
  2165. return padding + `sibling autogroup (${t.groupCount})`;
  2166. }
  2167. return padding + 'autogroup';
  2168. }
  2169. if (isSpanNode(t)) {
  2170. return padding + (t.value.op || t.value.span_id || 'unknown span');
  2171. }
  2172. if (isTransactionNode(t)) {
  2173. return padding + (t.value.transaction || 'unknown transaction');
  2174. }
  2175. if (isMissingInstrumentationNode(t)) {
  2176. return padding + 'missing_instrumentation';
  2177. }
  2178. if (isRootNode(t)) {
  2179. return padding + 'Root';
  2180. }
  2181. if (isTraceNode(t)) {
  2182. return padding + 'Trace';
  2183. }
  2184. if (isNoDataNode(t)) {
  2185. return padding + 'No Data';
  2186. }
  2187. if (isTraceErrorNode(t)) {
  2188. return padding + (t.value.event_id || t.value.level) || 'unknown trace error';
  2189. }
  2190. return 'unknown node';
  2191. }
  2192. export function traceNodeAnalyticsName(node: TraceTreeNode<TraceTree.NodeValue>): string {
  2193. if (isAutogroupedNode(node)) {
  2194. return isParentAutogroupedNode(node) ? 'parent autogroup' : 'sibling autogroup';
  2195. }
  2196. if (isSpanNode(node)) return 'span';
  2197. if (isTransactionNode(node)) return 'transaction';
  2198. if (isMissingInstrumentationNode(node)) return 'missing instrumentation';
  2199. if (isRootNode(node)) return 'root';
  2200. if (isTraceNode(node)) return 'trace';
  2201. if (isNoDataNode(node)) return 'no data';
  2202. if (isTraceErrorNode(node)) return 'error';
  2203. return 'unknown';
  2204. }
  2205. export function traceNodeAdjacentAnalyticsProperties(
  2206. node: TraceTreeNode<TraceTree.NodeValue>
  2207. ): Pick<
  2208. TracingEventParameters['trace.trace_layout.span_row_click'],
  2209. 'next_op' | 'parent_op' | 'previous_op'
  2210. > {
  2211. if (isNoDataNode(node)) {
  2212. const parent_transaction = node.parent_transaction;
  2213. if (!parent_transaction) return {};
  2214. return {
  2215. parent_op: parent_transaction.value['transaction.op'],
  2216. };
  2217. }
  2218. if (isMissingInstrumentationNode(node)) {
  2219. return {
  2220. previous_op: node.previous.value.op,
  2221. next_op: node.next.value.op,
  2222. };
  2223. }
  2224. return {};
  2225. }
  2226. // Creates an example trace response that we use to render the loading placeholder
  2227. function partialTransaction(
  2228. partial: Partial<TraceTree.Transaction>
  2229. ): TraceTree.Transaction {
  2230. return {
  2231. start_timestamp: 0,
  2232. timestamp: 0,
  2233. errors: [],
  2234. performance_issues: [],
  2235. parent_span_id: '',
  2236. span_id: '',
  2237. parent_event_id: '',
  2238. project_id: 0,
  2239. sdk_name: '',
  2240. profiler_id: '',
  2241. 'transaction.duration': 0,
  2242. 'transaction.op': 'loading-transaction',
  2243. 'transaction.status': 'loading-status',
  2244. generation: 0,
  2245. project_slug: '',
  2246. event_id: `event_id`,
  2247. transaction: `transaction`,
  2248. children: [],
  2249. ...partial,
  2250. };
  2251. }
  2252. export function makeExampleTrace(metadata: TraceTree.Metadata): TraceTree {
  2253. const trace: TraceTree.Trace = {
  2254. transactions: [],
  2255. orphan_errors: [],
  2256. };
  2257. function randomBetween(min: number, max: number) {
  2258. return Math.floor(Math.random() * (max - min + 1) + min);
  2259. }
  2260. let start = new Date().getTime();
  2261. const root = partialTransaction({
  2262. ...metadata,
  2263. generation: 0,
  2264. start_timestamp: start,
  2265. transaction: 'root transaction',
  2266. timestamp: start + randomBetween(100, 200),
  2267. });
  2268. trace.transactions.push(root);
  2269. for (let i = 0; i < 50; i++) {
  2270. const end = start + randomBetween(100, 200);
  2271. const nest = i > 0 && Math.random() > 0.33;
  2272. if (nest) {
  2273. const parent = root.children[root.children.length - 1];
  2274. parent.children.push(
  2275. partialTransaction({
  2276. ...metadata,
  2277. generation: 0,
  2278. start_timestamp: start,
  2279. transaction: `parent transaction ${i}`,
  2280. timestamp: end,
  2281. })
  2282. );
  2283. parent.timestamp = end;
  2284. } else {
  2285. root.children.push(
  2286. partialTransaction({
  2287. ...metadata,
  2288. generation: 0,
  2289. start_timestamp: start,
  2290. transaction: 'loading...',
  2291. ['transaction.op']: 'loading',
  2292. timestamp: end,
  2293. })
  2294. );
  2295. }
  2296. start = end;
  2297. }
  2298. const tree = TraceTree.FromTrace(trace, null);
  2299. return tree;
  2300. }