traceTree.tsx 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713
  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<TraceTree.Trace>(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:
  448. value && 'project_slug' in value
  449. ? value.project_slug
  450. : parent.metadata.project_slug ??
  451. parent.parent_transaction?.metadata.project_slug,
  452. event_id:
  453. value && 'event_id' in value
  454. ? value.event_id
  455. : parent.metadata.event_id ??
  456. parent.parent_transaction?.metadata.project_slug,
  457. });
  458. node.canFetch = true;
  459. tree.eventsCount += 1;
  460. if (node.profiles.length > 0) {
  461. tree.profiled_events.add(node);
  462. }
  463. if (isTraceTransaction(value)) {
  464. for (const error of value.errors) {
  465. traceNode.errors.add(error);
  466. }
  467. for (const performanceIssue of value.performance_issues) {
  468. traceNode.performance_issues.add(performanceIssue);
  469. }
  470. } else {
  471. traceNode.errors.add(value);
  472. }
  473. if (parent) {
  474. parent.children.push(node as TraceTreeNode<TraceTree.NodeValue>);
  475. }
  476. if ('start_timestamp' in value && value.start_timestamp < traceStart) {
  477. traceStart = value.start_timestamp;
  478. }
  479. if ('timestamp' in value && typeof value.timestamp === 'number') {
  480. // Errors don't have 'start_timestamp', so we adjust traceStart
  481. // with an errors 'timestamp'
  482. if (isTraceError(value)) {
  483. traceStart = Math.min(value.timestamp, traceStart);
  484. }
  485. traceEnd = Math.max(value.timestamp, traceEnd);
  486. }
  487. if (value && 'measurements' in value) {
  488. tree.collectMeasurements(
  489. node,
  490. traceStart,
  491. value.measurements as Record<string, Measurement>,
  492. tree.vitals,
  493. tree.vital_types,
  494. tree.indicators
  495. );
  496. }
  497. if (value && 'children' in value) {
  498. for (const child of value.children) {
  499. visit(node, child);
  500. }
  501. }
  502. return node;
  503. }
  504. const transactionQueue = trace.transactions ?? [];
  505. const orphanErrorsQueue = trace.orphan_errors ?? [];
  506. let tIdx = 0;
  507. let oIdx = 0;
  508. const tLen = transactionQueue.length;
  509. const oLen = orphanErrorsQueue.length;
  510. // Items in each queue are sorted by timestamp, so we just take
  511. // from the queue with the earliest timestamp which means the final list will be ordered.
  512. while (tIdx < tLen || oIdx < oLen) {
  513. const transaction = transactionQueue[tIdx];
  514. const orphan = orphanErrorsQueue[oIdx];
  515. if (transaction && orphan) {
  516. if (
  517. typeof orphan.timestamp === 'number' &&
  518. transaction.start_timestamp <= orphan.timestamp
  519. ) {
  520. visit(traceNode, transaction);
  521. tIdx++;
  522. } else {
  523. visit(traceNode, orphan);
  524. oIdx++;
  525. }
  526. } else if (transaction) {
  527. visit(traceNode, transaction);
  528. tIdx++;
  529. } else if (orphan) {
  530. visit(traceNode, orphan);
  531. oIdx++;
  532. }
  533. }
  534. if (tree.indicators.length > 0) {
  535. tree.indicators.sort((a, b) => a.start - b.start);
  536. for (const indicator of tree.indicators) {
  537. if (indicator.start > traceEnd) {
  538. traceEnd = indicator.start;
  539. }
  540. indicator.start *= traceNode.multiplier;
  541. }
  542. }
  543. // The sum of all durations of traces that exist under a replay is not always
  544. // equal to the duration of the replay. We need to adjust the traceview bounds
  545. // to ensure that we can see the max of the replay duration and the sum(trace durations). This way, we
  546. // can ensure that the replay timestamp indicators are always visible in the traceview along with all spans from the traces.
  547. if (replayRecord) {
  548. const replayStart = replayRecord.started_at.getTime() / 1000;
  549. const replayEnd = replayRecord.finished_at.getTime() / 1000;
  550. traceStart = Math.min(traceStart, replayStart);
  551. traceEnd = Math.max(traceEnd, replayEnd);
  552. }
  553. traceNode.space = [
  554. traceStart * traceNode.multiplier,
  555. (traceEnd - traceStart) * traceNode.multiplier,
  556. ];
  557. tree.root.space = [
  558. traceStart * traceNode.multiplier,
  559. (traceEnd - traceStart) * traceNode.multiplier,
  560. ];
  561. return tree.build();
  562. }
  563. fetchAdditionalTraces(options: TraceFetchOptions): () => void {
  564. let cancelled = false;
  565. const {organization, api, urlParams, filters, rerender, replayTraces} = options;
  566. const clonedTraceIds = [...replayTraces];
  567. const root = this.root.children[0];
  568. root.fetchStatus = 'loading';
  569. rerender();
  570. (async () => {
  571. while (clonedTraceIds.length > 0) {
  572. const batch = clonedTraceIds.splice(0, 3);
  573. const results = await Promise.allSettled(
  574. batch.map(batchTraceData => {
  575. return fetchSingleTrace(api, {
  576. orgSlug: organization.slug,
  577. query: qs.stringify(
  578. getTraceQueryParams(urlParams, filters.selection, {
  579. timestamp: batchTraceData.timestamp,
  580. })
  581. ),
  582. traceId: batchTraceData.traceSlug,
  583. });
  584. })
  585. );
  586. if (cancelled) return;
  587. const updatedData = results.reduce(
  588. (acc, result) => {
  589. // Ignoring the error case for now
  590. if (result.status === 'fulfilled') {
  591. const {transactions, orphan_errors} = result.value;
  592. acc.transactions.push(...transactions);
  593. acc.orphan_errors.push(...orphan_errors);
  594. }
  595. return acc;
  596. },
  597. {
  598. transactions: [],
  599. orphan_errors: [],
  600. } as TraceSplitResults<TraceTree.Transaction>
  601. );
  602. this.appendTree(TraceTree.FromTrace(updatedData, null));
  603. rerender();
  604. }
  605. root.fetchStatus = 'idle';
  606. rerender();
  607. })();
  608. return () => {
  609. root.fetchStatus = 'idle';
  610. cancelled = true;
  611. };
  612. }
  613. appendTree(tree: TraceTree) {
  614. const baseTraceNode = this.root.children[0];
  615. const additionalTraceNode = tree.root.children[0];
  616. if (!baseTraceNode || !additionalTraceNode) {
  617. throw new Error('No trace node found in tree');
  618. }
  619. for (const child of additionalTraceNode.children) {
  620. child.parent = baseTraceNode;
  621. baseTraceNode.children.push(child);
  622. }
  623. for (const error of additionalTraceNode.errors) {
  624. baseTraceNode.errors.add(error);
  625. }
  626. for (const performanceIssue of additionalTraceNode.performance_issues) {
  627. baseTraceNode.performance_issues.add(performanceIssue);
  628. }
  629. for (const profile of additionalTraceNode.profiles) {
  630. baseTraceNode.profiles.push(profile);
  631. }
  632. for (const [node, vitals] of tree.vitals) {
  633. this.vitals.set(node, vitals);
  634. }
  635. for (const [node, _] of tree.vitals) {
  636. if (
  637. baseTraceNode.space?.[0] &&
  638. node.value &&
  639. 'start_timestamp' in node.value &&
  640. 'measurements' in node.value
  641. ) {
  642. this.collectMeasurements(
  643. node,
  644. baseTraceNode.space[0],
  645. node.value.measurements as Record<string, Measurement>,
  646. this.vitals,
  647. this.vital_types,
  648. this.indicators
  649. );
  650. }
  651. }
  652. // We need to invalidate the data in the last node of the tree
  653. // so that the connectors are updated and pointing to the sibling nodes
  654. const last = this.root.children[this.root.children.length - 1];
  655. last.invalidate(last);
  656. for (const child of tree.root.children) {
  657. this._list = this._list.concat(child.getVisibleChildren());
  658. }
  659. }
  660. get shape(): TraceType {
  661. const trace = this.root.children[0];
  662. if (!trace) {
  663. return TraceType.EMPTY_TRACE;
  664. }
  665. if (!isTraceNode(trace)) {
  666. throw new TypeError('Not trace node');
  667. }
  668. const {transactions, orphan_errors} = trace.value;
  669. const traceStats = transactions?.reduce<{
  670. javascriptRootTransactions: TraceTree.Transaction[];
  671. orphans: number;
  672. roots: number;
  673. }>(
  674. (stats, transaction) => {
  675. if (isRootTransaction(transaction)) {
  676. stats.roots++;
  677. if (isJavascriptSDKTransaction(transaction)) {
  678. stats.javascriptRootTransactions.push(transaction);
  679. }
  680. } else {
  681. stats.orphans++;
  682. }
  683. return stats;
  684. },
  685. {roots: 0, orphans: 0, javascriptRootTransactions: []}
  686. ) ?? {roots: 0, orphans: 0, javascriptRootTransactions: []};
  687. if (traceStats.roots === 0) {
  688. if (traceStats.orphans > 0) {
  689. return TraceType.NO_ROOT;
  690. }
  691. if (orphan_errors && orphan_errors.length > 0) {
  692. return TraceType.ONLY_ERRORS;
  693. }
  694. return TraceType.EMPTY_TRACE;
  695. }
  696. if (traceStats.roots === 1) {
  697. if (traceStats.orphans > 0) {
  698. return TraceType.BROKEN_SUBTRACES;
  699. }
  700. return TraceType.ONE_ROOT;
  701. }
  702. if (traceStats.roots > 1) {
  703. if (traceStats.javascriptRootTransactions.length > 0) {
  704. return TraceType.BROWSER_MULTIPLE_ROOTS;
  705. }
  706. return TraceType.MULTIPLE_ROOTS;
  707. }
  708. throw new Error('Unknown trace type');
  709. }
  710. static FromSpans(
  711. parent: TraceTreeNode<TraceTree.NodeValue>,
  712. data: Event,
  713. spans: RawSpanType[],
  714. options: {sdk: string | undefined} | undefined
  715. ): [TraceTreeNode<TraceTree.NodeValue>, [number, number] | null] {
  716. parent.invalidate(parent);
  717. const platformHasMissingSpans = shouldAddMissingInstrumentationSpan(options?.sdk);
  718. let min_span_start = Number.POSITIVE_INFINITY;
  719. let min_span_end = Number.NEGATIVE_INFINITY;
  720. const parentIsSpan = isSpanNode(parent);
  721. const lookuptable: Record<
  722. RawSpanType['span_id'],
  723. TraceTreeNode<TraceTree.Span | TraceTree.Transaction>
  724. > = {};
  725. // If we've already fetched children, the tree is already assembled
  726. if (parent.spanChildren.length > 0) {
  727. parent.zoomedIn = true;
  728. return [parent, null];
  729. }
  730. // If we have no spans, insert an empty node to indicate that there is no data
  731. if (!spans.length && !parent.children.length) {
  732. parent.zoomedIn = true;
  733. parent.spanChildren.push(new NoDataNode(parent));
  734. return [parent, null];
  735. }
  736. if (parentIsSpan) {
  737. if (parent.value && 'span_id' in parent.value) {
  738. lookuptable[parent.value.span_id] = parent as TraceTreeNode<TraceTree.Span>;
  739. }
  740. }
  741. const transactionsToSpanMap = new Map<
  742. string,
  743. TraceTreeNode<TraceTree.Transaction>[]
  744. >();
  745. for (const child of parent.children) {
  746. if (isTransactionNode(child)) {
  747. // keep track of the transaction nodes that should be reparented under the newly fetched spans.
  748. const key =
  749. 'parent_span_id' in child.value &&
  750. typeof child.value.parent_span_id === 'string'
  751. ? child.value.parent_span_id
  752. : // This should be unique, but unreachable at lookup time.
  753. `unreachable-${child.value.event_id}`;
  754. const list = transactionsToSpanMap.get(key) ?? [];
  755. list.push(child);
  756. transactionsToSpanMap.set(key, list);
  757. }
  758. }
  759. const remappedTransactionParents = new Set<TraceTreeNode<TraceTree.NodeValue>>();
  760. for (const span of spans) {
  761. const childTransactions = transactionsToSpanMap.get(span.span_id) ?? [];
  762. const spanNodeValue: TraceTree.Span = {
  763. ...span,
  764. event: data as EventTransaction,
  765. childTransactions,
  766. };
  767. const node: TraceTreeNode<TraceTree.Span> = new TraceTreeNode(null, spanNodeValue, {
  768. event_id: parent.metadata.event_id,
  769. project_slug: parent.metadata.project_slug,
  770. });
  771. if (
  772. typeof span.start_timestamp === 'number' &&
  773. span.start_timestamp < min_span_start
  774. ) {
  775. min_span_start = span.start_timestamp;
  776. }
  777. if (typeof span.timestamp === 'number' && span.timestamp > min_span_end) {
  778. min_span_end = span.timestamp;
  779. }
  780. for (const error of getRelatedSpanErrorsFromTransaction(span, parent)) {
  781. node.errors.add(error);
  782. }
  783. for (const performanceIssue of getRelatedPerformanceIssuesFromTransaction(
  784. span,
  785. parent
  786. )) {
  787. node.performance_issues.add(performanceIssue);
  788. }
  789. // This is the case where the current span is the parent of a transaction.
  790. // When zooming into the parent of the txn, we want to place a copy
  791. // of the txn as a child of the parenting span.
  792. if (childTransactions) {
  793. for (const childTransaction of childTransactions) {
  794. const clonedChildTxn = childTransaction.cloneDeep();
  795. node.spanChildren.push(clonedChildTxn);
  796. clonedChildTxn.parent = node;
  797. remappedTransactionParents.add(node);
  798. // Delete the transaction from the lookup table so that we don't
  799. // duplicate the transaction in the tree.
  800. }
  801. transactionsToSpanMap.delete(span.span_id);
  802. }
  803. lookuptable[span.span_id] = node;
  804. if (span.parent_span_id) {
  805. const spanParentNode = lookuptable[span.parent_span_id];
  806. if (spanParentNode) {
  807. node.parent = spanParentNode;
  808. if (platformHasMissingSpans) {
  809. maybeInsertMissingInstrumentationSpan(spanParentNode, node);
  810. }
  811. spanParentNode.spanChildren.push(node);
  812. continue;
  813. }
  814. }
  815. if (platformHasMissingSpans) {
  816. maybeInsertMissingInstrumentationSpan(parent, node);
  817. }
  818. parent.spanChildren.push(node);
  819. node.parent = parent;
  820. }
  821. // Whatever remains is transaction nodes that we failed to reparent under the spans.
  822. for (const [_, transactions] of transactionsToSpanMap) {
  823. for (const transaction of transactions) {
  824. if ('parent_span_id' in transaction.value && !!transaction.value.parent_span_id) {
  825. Sentry.withScope(scope => {
  826. scope.setFingerprint(['trace-view-reparenting']);
  827. scope.captureMessage(
  828. 'Failed to reparent transaction under span. None of the spans we fetched had a span_id matching the parent_span_id of the transaction.'
  829. );
  830. });
  831. }
  832. const cloned = transaction.cloneDeep();
  833. parent.spanChildren.push(cloned);
  834. cloned.parent = parent;
  835. }
  836. }
  837. for (const c of remappedTransactionParents) {
  838. c.spanChildren.sort(chronologicalSort);
  839. }
  840. parent.zoomedIn = true;
  841. TraceTree.AutogroupSiblingSpanNodes(parent);
  842. TraceTree.AutogroupDirectChildrenSpanNodes(parent);
  843. return [parent, [min_span_start, min_span_end]];
  844. }
  845. static AutogroupDirectChildrenSpanNodes(
  846. root: TraceTreeNode<TraceTree.NodeValue>
  847. ): void {
  848. const queue = [root];
  849. while (queue.length > 0) {
  850. const node = queue.pop()!;
  851. if (node.children.length > 1 || !isSpanNode(node)) {
  852. for (const child of node.children) {
  853. queue.push(child);
  854. }
  855. continue;
  856. }
  857. const head = node;
  858. let tail = node;
  859. let groupMatchCount = 0;
  860. const errors: TraceErrorType[] = [];
  861. const performance_issues: TraceTree.TracePerformanceIssue[] = [];
  862. let start = head.value.start_timestamp;
  863. let end = head.value.timestamp;
  864. while (
  865. tail &&
  866. tail.children.length === 1 &&
  867. isSpanNode(tail.children[0]) &&
  868. tail.children[0].value.op === head.value.op
  869. ) {
  870. if ((tail?.errors?.size ?? 0) > 0) {
  871. errors.push(...tail?.errors);
  872. }
  873. if ((tail?.performance_issues?.size ?? 0) > 0) {
  874. performance_issues.push(...tail.performance_issues);
  875. }
  876. // Collect start/end of all nodes in the list
  877. // so that we can properly render a autogrouped bar that
  878. // encapsulates all the nodes in the list
  879. if (tail.value.start_timestamp < start) {
  880. start = tail.value.start_timestamp;
  881. }
  882. if (tail.value.timestamp > end) {
  883. end = tail.value.timestamp;
  884. }
  885. groupMatchCount++;
  886. tail = tail.children[0];
  887. }
  888. // Checking the tail node for errors as it is not included in the grouping
  889. // while loop, but is hidden when the autogrouped node is collapsed
  890. if ((tail?.errors?.size ?? 0) > 0) {
  891. errors.push(...tail?.errors);
  892. }
  893. if ((tail?.performance_issues?.size ?? 0) > 0) {
  894. performance_issues.push(...tail.performance_issues);
  895. }
  896. if (groupMatchCount < 1) {
  897. for (const child of head.children) {
  898. queue.push(child);
  899. }
  900. continue;
  901. }
  902. const autoGroupedNode = new ParentAutogroupNode(
  903. node.parent,
  904. {
  905. ...head.value,
  906. start_timestamp: start,
  907. timestamp: end,
  908. autogrouped_by: {
  909. op: head.value && 'op' in head.value ? head.value.op ?? '' : '',
  910. },
  911. },
  912. {
  913. event_id: undefined,
  914. project_slug: undefined,
  915. },
  916. head,
  917. tail
  918. );
  919. if (!node.parent) {
  920. throw new Error('Parent node is missing, this should be unreachable code');
  921. }
  922. const index = node.parent.children.indexOf(node);
  923. node.parent.children[index] = autoGroupedNode;
  924. autoGroupedNode.head.parent = autoGroupedNode;
  925. autoGroupedNode.groupCount = groupMatchCount + 1;
  926. autoGroupedNode.space = [
  927. start * autoGroupedNode.multiplier,
  928. (end - start) * autoGroupedNode.multiplier,
  929. ];
  930. for (const error of errors) {
  931. autoGroupedNode.errors.add(error);
  932. }
  933. for (const performanceIssue of performance_issues) {
  934. autoGroupedNode.performance_issues.add(performanceIssue);
  935. }
  936. for (const c of tail.children) {
  937. c.parent = autoGroupedNode;
  938. queue.push(c);
  939. }
  940. }
  941. }
  942. static AutogroupSiblingSpanNodes(root: TraceTreeNode<TraceTree.NodeValue>): void {
  943. const queue = [root];
  944. while (queue.length > 0) {
  945. const node = queue.pop()!;
  946. for (const child of node.children) {
  947. queue.push(child);
  948. }
  949. if (isAutogroupedNode(node)) {
  950. continue;
  951. }
  952. if (node.children.length < 5) {
  953. continue;
  954. }
  955. let index = 0;
  956. let matchCount = 0;
  957. while (index < node.children.length) {
  958. if (!isSpanNode(node.children[index])) {
  959. index++;
  960. matchCount = 0;
  961. continue;
  962. }
  963. const current = node.children[index] as TraceTreeNode<TraceTree.Span>;
  964. const next = node.children[index + 1] as TraceTreeNode<TraceTree.Span>;
  965. if (
  966. next &&
  967. isSpanNode(next) &&
  968. next.children.length === 0 &&
  969. current.children.length === 0 &&
  970. next.value.op === current.value.op &&
  971. next.value.description === current.value.description
  972. ) {
  973. matchCount++;
  974. // If the next node is the last node in the list, we keep iterating
  975. if (index + 1 < node.children.length) {
  976. index++;
  977. continue;
  978. }
  979. }
  980. if (matchCount >= 4) {
  981. const autoGroupedNode = new SiblingAutogroupNode(
  982. node,
  983. {
  984. ...current.value,
  985. autogrouped_by: {
  986. op: current.value.op ?? '',
  987. description: current.value.description ?? '',
  988. },
  989. },
  990. {
  991. event_id: undefined,
  992. project_slug: undefined,
  993. }
  994. );
  995. autoGroupedNode.groupCount = matchCount + 1;
  996. const start = index - matchCount;
  997. let start_timestamp = Number.MAX_SAFE_INTEGER;
  998. let timestamp = Number.MIN_SAFE_INTEGER;
  999. for (let j = start; j < start + matchCount + 1; j++) {
  1000. const child = node.children[j];
  1001. if (
  1002. child.value &&
  1003. 'timestamp' in child.value &&
  1004. typeof child.value.timestamp === 'number' &&
  1005. child.value.timestamp > timestamp
  1006. ) {
  1007. timestamp = child.value.timestamp;
  1008. }
  1009. if (
  1010. child.value &&
  1011. 'start_timestamp' in child.value &&
  1012. typeof child.value.start_timestamp === 'number' &&
  1013. child.value.start_timestamp < start_timestamp
  1014. ) {
  1015. start_timestamp = child.value.start_timestamp;
  1016. }
  1017. if (child.has_errors) {
  1018. for (const error of child.errors) {
  1019. autoGroupedNode.errors.add(error);
  1020. }
  1021. for (const performanceIssue of child.performance_issues) {
  1022. autoGroupedNode.performance_issues.add(performanceIssue);
  1023. }
  1024. }
  1025. autoGroupedNode.children.push(node.children[j]);
  1026. autoGroupedNode.children[autoGroupedNode.children.length - 1].parent =
  1027. autoGroupedNode;
  1028. }
  1029. autoGroupedNode.space = [
  1030. start_timestamp * autoGroupedNode.multiplier,
  1031. (timestamp - start_timestamp) * autoGroupedNode.multiplier,
  1032. ];
  1033. node.children.splice(start, matchCount + 1, autoGroupedNode);
  1034. index = start + 1;
  1035. matchCount = 0;
  1036. } else {
  1037. index++;
  1038. matchCount = 0;
  1039. }
  1040. }
  1041. }
  1042. }
  1043. collectMeasurements(
  1044. node: TraceTreeNode<TraceTree.NodeValue>,
  1045. start_timestamp: number,
  1046. measurements: Record<string, Measurement>,
  1047. vitals: Map<TraceTreeNode<TraceTree.NodeValue>, TraceTree.CollectedVital[]>,
  1048. vital_types: Set<'web' | 'mobile'>,
  1049. indicators: TraceTree.Indicator[]
  1050. ): void {
  1051. for (const measurement of COLLECTABLE_MEASUREMENTS) {
  1052. const value = measurements[measurement];
  1053. if (!value || typeof value.value !== 'number') {
  1054. continue;
  1055. }
  1056. if (!vitals.has(node)) {
  1057. vitals.set(node, []);
  1058. }
  1059. WEB_VITALS_LOOKUP.has(measurement) && vital_types.add('web');
  1060. MOBILE_VITALS_LOOKUP.has(measurement) && vital_types.add('mobile');
  1061. const vital = vitals.get(node)!;
  1062. vital.push({
  1063. key: measurement,
  1064. measurement: value,
  1065. });
  1066. if (!RENDERABLE_MEASUREMENTS[measurement]) {
  1067. continue;
  1068. }
  1069. const timestamp = measurementToTimestamp(
  1070. start_timestamp,
  1071. value.value,
  1072. value.unit ?? 'millisecond'
  1073. );
  1074. indicators.push({
  1075. start: timestamp,
  1076. duration: 0,
  1077. measurement: value,
  1078. poor: MEASUREMENT_THRESHOLDS[measurement]
  1079. ? value.value > MEASUREMENT_THRESHOLDS[measurement]
  1080. : false,
  1081. type: measurement as TraceTree.Indicator['type'],
  1082. label: (MEASUREMENT_ACRONYM_MAPPING[measurement] ?? measurement).toUpperCase(),
  1083. });
  1084. }
  1085. }
  1086. // Returns boolean to indicate if node was updated
  1087. expand(node: TraceTreeNode<TraceTree.NodeValue>, expanded: boolean): boolean {
  1088. if (expanded === node.expanded) {
  1089. return false;
  1090. }
  1091. // Expanding is not allowed for zoomed in nodes
  1092. if (node.zoomedIn) {
  1093. return false;
  1094. }
  1095. if (node instanceof ParentAutogroupNode) {
  1096. // In parent autogrouping, we perform a node swap and either point the
  1097. // head or tails of the autogrouped sequence to the autogrouped node
  1098. if (node.expanded) {
  1099. const index = this._list.indexOf(node);
  1100. const autogroupedChildren = node.getVisibleChildren();
  1101. this._list.splice(index + 1, autogroupedChildren.length);
  1102. const newChildren = node.tail.getVisibleChildren();
  1103. for (const c of node.tail.children) {
  1104. c.parent = node;
  1105. }
  1106. this._list.splice(index + 1, 0, ...newChildren);
  1107. } else {
  1108. node.head.parent = node;
  1109. const index = this._list.indexOf(node);
  1110. const childrenCount = node.getVisibleChildrenCount();
  1111. this._list.splice(index + 1, childrenCount);
  1112. const newChildren = [node.head].concat(
  1113. node.head.getVisibleChildren() as TraceTreeNode<TraceTree.Span>[]
  1114. );
  1115. for (const c of node.children) {
  1116. c.parent = node.tail;
  1117. }
  1118. this._list.splice(index + 1, 0, ...newChildren);
  1119. }
  1120. node.invalidate(node);
  1121. node.expanded = expanded;
  1122. return true;
  1123. }
  1124. if (node.expanded) {
  1125. const index = this._list.indexOf(node);
  1126. this._list.splice(index + 1, node.getVisibleChildrenCount());
  1127. // Flip expanded after collecting visible children
  1128. node.expanded = expanded;
  1129. } else {
  1130. const index = this._list.indexOf(node);
  1131. // Flip expanded so that we can collect visible children
  1132. node.expanded = expanded;
  1133. this._list.splice(index + 1, 0, ...node.getVisibleChildren());
  1134. }
  1135. node.expanded = expanded;
  1136. return true;
  1137. }
  1138. static ExpandToEventID(
  1139. eventId: string,
  1140. tree: TraceTree,
  1141. rerender: () => void,
  1142. options: ViewManagerScrollToOptions
  1143. ): Promise<{index: number; node: TraceTreeNode<TraceTree.NodeValue>} | null | null> {
  1144. const node = findInTreeByEventId(tree.root, eventId);
  1145. if (!node) {
  1146. return Promise.resolve(null);
  1147. }
  1148. return TraceTree.ExpandToPath(tree, node.path, rerender, options).then(
  1149. async result => {
  1150. // When users are coming off an eventID link, we want to fetch the children
  1151. // of the node that the eventID points to. This is because the eventID link
  1152. // only points to the transaction, but we want to fetch the children of the
  1153. // transaction to show the user the list of spans in that transaction
  1154. if (result?.node?.canFetch) {
  1155. await tree.zoomIn(result.node, true, options).catch(_e => {
  1156. Sentry.captureMessage('Failed to fetch children of eventId on mount');
  1157. });
  1158. return result;
  1159. }
  1160. return null;
  1161. }
  1162. );
  1163. }
  1164. static ExpandToPath(
  1165. tree: TraceTree,
  1166. scrollQueue: TraceTree.NodePath[],
  1167. rerender: () => void,
  1168. options: ViewManagerScrollToOptions
  1169. ): Promise<{index: number; node: TraceTreeNode<TraceTree.NodeValue>} | null | null> {
  1170. const segments = [...scrollQueue];
  1171. const list = tree.list;
  1172. if (!list) {
  1173. return Promise.resolve(null);
  1174. }
  1175. if (segments.length === 1 && segments[0] === 'trace-root') {
  1176. rerender();
  1177. return Promise.resolve({index: 0, node: tree.root.children[0]});
  1178. }
  1179. // Keep parent reference as we traverse the tree so that we can only
  1180. // perform searching in the current level and not the entire tree
  1181. let parent: TraceTreeNode<TraceTree.NodeValue> = tree.root;
  1182. const recurseToRow = async (): Promise<{
  1183. index: number;
  1184. node: TraceTreeNode<TraceTree.NodeValue>;
  1185. } | null | null> => {
  1186. const path = segments.pop();
  1187. let current = findInTreeFromSegment(parent, path!);
  1188. if (!current) {
  1189. // Some parts of the codebase link to span:span_id, txn:event_id, where span_id is
  1190. // actally stored on the txn:event_id node. Since we cant tell from the link itself
  1191. // that this is happening, we will perform a final check to see if we've actually already
  1192. // arrived to the node in the previous search call.
  1193. if (path) {
  1194. const [type, id] = path.split('-');
  1195. if (
  1196. type === 'span' &&
  1197. isTransactionNode(parent) &&
  1198. parent.value.span_id === id
  1199. ) {
  1200. current = parent;
  1201. }
  1202. }
  1203. if (!current) {
  1204. Sentry.captureMessage('Failed to scroll to node in trace tree');
  1205. return null;
  1206. }
  1207. }
  1208. // Reassing the parent to the current node so that
  1209. // searching narrows down to the current level
  1210. // and we dont need to search the entire tree each time
  1211. parent = current;
  1212. if (isTransactionNode(current)) {
  1213. const nextSegment = segments[segments.length - 1];
  1214. if (
  1215. nextSegment?.startsWith('span-') ||
  1216. nextSegment?.startsWith('empty-') ||
  1217. nextSegment?.startsWith('ag-') ||
  1218. nextSegment?.startsWith('ms-')
  1219. ) {
  1220. await tree.zoomIn(current, true, options);
  1221. return recurseToRow();
  1222. }
  1223. }
  1224. if (isAutogroupedNode(current) && segments.length > 0) {
  1225. tree.expand(current, true);
  1226. return recurseToRow();
  1227. }
  1228. if (segments.length > 0) {
  1229. return recurseToRow();
  1230. }
  1231. // We are at the last path segment (the node that the user clicked on)
  1232. // and we should scroll the view to this node.
  1233. let index = current ? tree.list.findIndex(node => node === current) : -1;
  1234. // We have found the node, yet it is somehow not in the visible tree.
  1235. // This means that the path we were given did not match the current tree.
  1236. // This sometimes happens when we receive external links like span-x, txn-y
  1237. // however the resulting tree looks like span-x, autogroup, txn-y. In this case,
  1238. // we should expand the autogroup node and try to find the node again.
  1239. if (current && index === -1) {
  1240. let parent_node = current.parent;
  1241. while (parent_node) {
  1242. // Transactions break autogrouping chains, so we can stop here
  1243. if (isTransactionNode(parent_node)) {
  1244. break;
  1245. }
  1246. if (isAutogroupedNode(parent_node)) {
  1247. tree.expand(parent_node, true);
  1248. index = current ? tree.list.findIndex(node => node === current) : -1;
  1249. // This is very wasteful as it performs O(n^2) search each time we expand a node...
  1250. // In most cases though, we should be operating on a tree with sub 10k elements and hopefully
  1251. // a low autogrouped node count.
  1252. if (index !== -1) {
  1253. break;
  1254. }
  1255. }
  1256. parent_node = parent_node.parent;
  1257. }
  1258. }
  1259. if (index === -1) {
  1260. throw new Error(`Couldn't find node in list ${scrollQueue.join(',')}`);
  1261. }
  1262. rerender();
  1263. return {index, node: current};
  1264. };
  1265. return recurseToRow();
  1266. }
  1267. zoomIn(
  1268. node: TraceTreeNode<TraceTree.NodeValue>,
  1269. zoomedIn: boolean,
  1270. options: {
  1271. api: Client;
  1272. organization: Organization;
  1273. }
  1274. ): Promise<Event | null> {
  1275. if (zoomedIn === node.zoomedIn) {
  1276. return Promise.resolve(null);
  1277. }
  1278. if (!zoomedIn) {
  1279. const index = this._list.indexOf(node);
  1280. if (index === -1) {
  1281. return Promise.resolve(null);
  1282. }
  1283. const childrenCount = node.getVisibleChildrenCount();
  1284. this._list.splice(index + 1, childrenCount);
  1285. node.zoomedIn = zoomedIn;
  1286. node.invalidate(node);
  1287. if (node.expanded) {
  1288. this._list.splice(index + 1, 0, ...node.getVisibleChildren());
  1289. }
  1290. return Promise.resolve(null);
  1291. }
  1292. const key = cacheKey(
  1293. options.organization,
  1294. node.metadata.project_slug!,
  1295. node.metadata.event_id!
  1296. );
  1297. const promise =
  1298. this._spanPromises.get(key) ??
  1299. fetchTransactionSpans(
  1300. options.api,
  1301. options.organization,
  1302. node.metadata.project_slug!,
  1303. node.metadata.event_id!
  1304. );
  1305. node.fetchStatus = 'loading';
  1306. promise
  1307. .then(data => {
  1308. // The user may have collapsed the node before the promise resolved. When that
  1309. // happens, dont update the tree with the resolved data. Alternatively, we could implement
  1310. // a cancellable promise and avoid this cumbersome heuristic.
  1311. node.fetchStatus = 'resolved';
  1312. if (!node.expanded) {
  1313. return data;
  1314. }
  1315. const spans = data.entries.find(s => s.type === 'spans') ?? {data: []};
  1316. // Remove existing entries from the list
  1317. const index = this._list.indexOf(node);
  1318. if (index === -1) {
  1319. return data;
  1320. }
  1321. if (node.expanded) {
  1322. const childrenCount = node.getVisibleChildrenCount();
  1323. if (childrenCount > 0) {
  1324. this._list.splice(index + 1, childrenCount);
  1325. }
  1326. }
  1327. // Api response is not sorted
  1328. spans.data.sort((a, b) => a.start_timestamp - b.start_timestamp);
  1329. const [_, view] = TraceTree.FromSpans(node, data, spans.data, {
  1330. sdk: data.sdk?.name,
  1331. });
  1332. // Spans contain millisecond precision, which means that it is possible for the
  1333. // children spans of a transaction to extend beyond the start and end of the transaction
  1334. // through ns precision. To account for this, we need to adjust the space of the transaction node and the space
  1335. // of our trace so that all of the span children are visible and can be rendered inside the view.
  1336. if (
  1337. view &&
  1338. Number.isFinite(view[0]) &&
  1339. Number.isFinite(view[1]) &&
  1340. this.root.space
  1341. ) {
  1342. const prev_start = this.root.space[0];
  1343. const prev_end = this.root.space[1];
  1344. const new_start = view[0];
  1345. const new_end = view[1];
  1346. // Update the space of the tree and the trace root node
  1347. this.root.space = [
  1348. Math.min(new_start * node.multiplier, this.root.space[0]),
  1349. Math.max(new_end * node.multiplier - prev_start, this.root.space[1]),
  1350. ];
  1351. this.root.children[0].space = [...this.root.space];
  1352. if (prev_start !== this.root.space[0] || prev_end !== this.root.space[1]) {
  1353. this.dispatch('trace timeline change', this.root.space);
  1354. }
  1355. }
  1356. const spanChildren = node.getVisibleChildren();
  1357. this._list.splice(index + 1, 0, ...spanChildren);
  1358. return data;
  1359. })
  1360. .catch(_e => {
  1361. node.fetchStatus = 'error';
  1362. });
  1363. this._spanPromises.set(key, promise);
  1364. return promise;
  1365. }
  1366. toList(): TraceTreeNode<TraceTree.NodeValue>[] {
  1367. const list: TraceTreeNode<TraceTree.NodeValue>[] = [];
  1368. function visit(node: TraceTreeNode<TraceTree.NodeValue>) {
  1369. list.push(node);
  1370. if (!node.expanded) {
  1371. return;
  1372. }
  1373. for (const child of node.children) {
  1374. visit(child);
  1375. }
  1376. }
  1377. for (const child of this.root.children) {
  1378. visit(child);
  1379. }
  1380. return list;
  1381. }
  1382. get list(): ReadonlyArray<TraceTreeNode<TraceTree.NodeValue>> {
  1383. return this._list;
  1384. }
  1385. listeners: TraceTree.EventStore = {
  1386. 'trace timeline change': new Set(),
  1387. };
  1388. on<K extends keyof TraceTree.TraceTreeEvents>(
  1389. event: K,
  1390. cb: TraceTree.TraceTreeEvents[K]
  1391. ): void {
  1392. this.listeners[event].add(cb);
  1393. }
  1394. off<K extends keyof TraceTree.TraceTreeEvents>(
  1395. event: K,
  1396. cb: TraceTree.TraceTreeEvents[K]
  1397. ): void {
  1398. this.listeners[event].delete(cb);
  1399. }
  1400. dispatch<K extends keyof TraceTree.TraceTreeEvents>(
  1401. event: K,
  1402. ...args: ArgumentTypes<TraceTree.TraceTreeEvents[K]>
  1403. ): void {
  1404. if (!this.listeners[event]) {
  1405. return;
  1406. }
  1407. for (const handler of this.listeners[event]) {
  1408. // @ts-expect-error
  1409. handler(...args);
  1410. }
  1411. }
  1412. /**
  1413. * Prints the tree in a human readable format, useful for debugging and testing
  1414. */
  1415. print() {
  1416. // root nodes are -1 indexed, so we add 1 to the depth so .repeat doesnt throw
  1417. const print = this.list
  1418. .map(t => printNode(t, 0))
  1419. .filter(Boolean)
  1420. .join('\n');
  1421. // eslint-disable-next-line no-console
  1422. console.log(print);
  1423. }
  1424. build() {
  1425. this._list = this.toList();
  1426. return this;
  1427. }
  1428. }
  1429. export class TraceTreeNode<T extends TraceTree.NodeValue = TraceTree.NodeValue> {
  1430. canFetch: boolean = false;
  1431. fetchStatus: 'resolved' | 'error' | 'idle' | 'loading' = 'idle';
  1432. parent: TraceTreeNode | null = null;
  1433. value: T;
  1434. expanded: boolean = false;
  1435. zoomedIn: boolean = false;
  1436. metadata: TraceTree.Metadata = {
  1437. project_slug: undefined,
  1438. event_id: undefined,
  1439. };
  1440. errors: Set<TraceErrorType> = new Set<TraceErrorType>();
  1441. performance_issues: Set<TraceTree.TracePerformanceIssue> =
  1442. new Set<TraceTree.TracePerformanceIssue>();
  1443. profiles: TraceTree.Profile[] = [];
  1444. multiplier: number;
  1445. space: [number, number] = [0, 0];
  1446. private unit = 'milliseconds' as const;
  1447. private _depth: number | undefined;
  1448. private _children: TraceTreeNode[] = [];
  1449. private _spanChildren: TraceTreeNode[] = [];
  1450. private _connectors: number[] | undefined = undefined;
  1451. constructor(parent: TraceTreeNode | null, value: T, metadata: TraceTree.Metadata) {
  1452. this.parent = parent ?? null;
  1453. this.value = value;
  1454. this.metadata = metadata;
  1455. this.multiplier = this.unit === 'milliseconds' ? 1e3 : 1;
  1456. if (
  1457. value &&
  1458. 'timestamp' in value &&
  1459. 'start_timestamp' in value &&
  1460. typeof value.timestamp === 'number' &&
  1461. typeof value.start_timestamp === 'number'
  1462. ) {
  1463. this.space = [
  1464. value.start_timestamp * this.multiplier,
  1465. (value.timestamp - value.start_timestamp) * this.multiplier,
  1466. ];
  1467. } else if (value && 'timestamp' in value && typeof value.timestamp === 'number') {
  1468. this.space = [value.timestamp * this.multiplier, 0];
  1469. }
  1470. if (
  1471. isTraceErrorNode(this) &&
  1472. 'timestamp' in this.value &&
  1473. typeof this.value.timestamp === 'number'
  1474. ) {
  1475. this.space = [this.value.timestamp * this.multiplier, 0];
  1476. }
  1477. if (value && 'profile_id' in value && typeof value.profile_id === 'string') {
  1478. this.profiles.push({profile_id: value.profile_id, space: this.space ?? [0, 0]});
  1479. }
  1480. if (isTransactionNode(this)) {
  1481. this.canFetch = true;
  1482. }
  1483. if (isTransactionNode(this) || isTraceNode(this) || isSpanNode(this)) {
  1484. this.expanded = true;
  1485. }
  1486. if (shouldCollapseNodeByDefault(this)) {
  1487. this.expanded = false;
  1488. }
  1489. if (isTransactionNode(this)) {
  1490. this.errors = new Set(this.value.errors);
  1491. this.performance_issues = new Set(this.value.performance_issues);
  1492. }
  1493. // For error nodes, its value is the only associated issue.
  1494. if (isTraceErrorNode(this)) {
  1495. this.errors = new Set([this.value]);
  1496. }
  1497. }
  1498. cloneDeep():
  1499. | TraceTreeNode<T>
  1500. | ParentAutogroupNode
  1501. | SiblingAutogroupNode
  1502. | NoDataNode
  1503. | MissingInstrumentationNode {
  1504. let clone:
  1505. | TraceTreeNode<T>
  1506. | ParentAutogroupNode
  1507. | SiblingAutogroupNode
  1508. | NoDataNode
  1509. | MissingInstrumentationNode;
  1510. if (isParentAutogroupedNode(this)) {
  1511. clone = new ParentAutogroupNode(
  1512. this.parent,
  1513. this.value,
  1514. this.metadata,
  1515. this.head,
  1516. this.tail
  1517. );
  1518. clone.groupCount = this.groupCount;
  1519. } else if (isSiblingAutogroupedNode(this)) {
  1520. clone = new SiblingAutogroupNode(this.parent, this.value, this.metadata);
  1521. clone.groupCount = this.groupCount;
  1522. } else if (isNoDataNode(this)) {
  1523. clone = new NoDataNode(this.parent);
  1524. } else if (isMissingInstrumentationNode(this)) {
  1525. clone = new MissingInstrumentationNode(
  1526. this.parent!,
  1527. this.value,
  1528. this.metadata,
  1529. this.previous,
  1530. this.next
  1531. );
  1532. } else {
  1533. clone = new TraceTreeNode(this.parent, this.value, this.metadata);
  1534. }
  1535. if (!clone) {
  1536. throw new Error('CloneDeep is not implemented');
  1537. }
  1538. clone.expanded = this.expanded;
  1539. clone.zoomedIn = this.zoomedIn;
  1540. clone.canFetch = this.canFetch;
  1541. clone.fetchStatus = this.fetchStatus;
  1542. clone.space = this.space;
  1543. clone.metadata = this.metadata;
  1544. if (isParentAutogroupedNode(clone)) {
  1545. clone.head = clone.head.cloneDeep() as TraceTreeNode<TraceTree.Span>;
  1546. clone.tail = clone.tail.cloneDeep() as TraceTreeNode<TraceTree.Span>;
  1547. clone.head.parent = clone;
  1548. // If the node is not expanded, the parent of the tail points to the
  1549. // autogrouped clone. If the node is expanded, the parent of the children
  1550. // of the tail points to the autogrouped clone.
  1551. if (!clone.expanded) {
  1552. for (const c of clone.tail.children) {
  1553. c.parent = clone;
  1554. }
  1555. } else {
  1556. for (const c of clone.children) {
  1557. c.parent = clone.tail;
  1558. }
  1559. }
  1560. clone.head.parent = clone;
  1561. clone.tail.parent = clone;
  1562. } else if (isSiblingAutogroupedNode(clone)) {
  1563. for (const child of this.children) {
  1564. const childClone = child.cloneDeep() as TraceTreeNode<TraceTree.Span>;
  1565. clone.children.push(childClone);
  1566. childClone.parent = clone;
  1567. }
  1568. } else {
  1569. for (const child of this.children) {
  1570. const childClone = child.cloneDeep() as TraceTreeNode<TraceTree.Span>;
  1571. clone.children.push(childClone);
  1572. childClone.parent = clone;
  1573. }
  1574. }
  1575. return clone;
  1576. }
  1577. get isOrphaned() {
  1578. return this.parent?.value && 'orphan_errors' in this.parent.value;
  1579. }
  1580. get isLastChild() {
  1581. if (!this.parent || this.parent.children.length === 0) {
  1582. return true;
  1583. }
  1584. return this.parent.children[this.parent.children.length - 1] === this;
  1585. }
  1586. /**
  1587. * Return a lazily calculated depth of the node in the tree.
  1588. * Root node has a value of -1 as it is abstract.
  1589. */
  1590. get depth(): number {
  1591. if (typeof this._depth === 'number') {
  1592. return this._depth;
  1593. }
  1594. let depth = -2;
  1595. let node: TraceTreeNode<any> | null = this;
  1596. while (node) {
  1597. if (typeof node.parent?.depth === 'number') {
  1598. this._depth = node.parent.depth + 1;
  1599. return this._depth;
  1600. }
  1601. depth++;
  1602. node = node.parent;
  1603. }
  1604. this._depth = depth;
  1605. return this._depth;
  1606. }
  1607. get has_errors(): boolean {
  1608. return this.errors.size > 0 || this.performance_issues.size > 0;
  1609. }
  1610. get parent_transaction(): TraceTreeNode<TraceTree.Transaction> | null {
  1611. let node: TraceTreeNode<TraceTree.NodeValue> | null = this.parent;
  1612. while (node) {
  1613. if (isTransactionNode(node)) {
  1614. return node;
  1615. }
  1616. node = node.parent;
  1617. }
  1618. return null;
  1619. }
  1620. /**
  1621. * Returns the depth levels at which the row should draw vertical connectors
  1622. * negative values mean connector points to an orphaned node
  1623. */
  1624. get connectors(): number[] {
  1625. if (this._connectors !== undefined) {
  1626. return this._connectors!;
  1627. }
  1628. this._connectors = [];
  1629. if (!this.parent) {
  1630. return this._connectors;
  1631. }
  1632. if (this.parent?.connectors !== undefined) {
  1633. this._connectors = [...this.parent.connectors];
  1634. if (this.isLastChild || this.value === null) {
  1635. return this._connectors;
  1636. }
  1637. this.connectors.push(this.isOrphaned ? -this.depth : this.depth);
  1638. return this._connectors;
  1639. }
  1640. let node: TraceTreeNode<T> | TraceTreeNode<TraceTree.NodeValue> | null = this.parent;
  1641. while (node) {
  1642. if (node.value === null) {
  1643. break;
  1644. }
  1645. if (node.isLastChild) {
  1646. node = node.parent;
  1647. continue;
  1648. }
  1649. this._connectors.push(node.isOrphaned ? -node.depth : node.depth);
  1650. node = node.parent;
  1651. }
  1652. return this._connectors;
  1653. }
  1654. /**
  1655. * Returns the children that the node currently points to.
  1656. * The logic here is a consequence of the tree design, where we want to be able to store
  1657. * both transaction and span nodes in the same tree. This results in an annoying API where
  1658. * we either store span children separately or transaction children separately. A better design
  1659. * would have been to create an invisible meta node that always points to the correct children.
  1660. */
  1661. get children(): TraceTreeNode[] {
  1662. if (isAutogroupedNode(this)) {
  1663. return this._children;
  1664. }
  1665. if (isSpanNode(this)) {
  1666. return this.canFetch && !this.zoomedIn ? [] : this.spanChildren;
  1667. }
  1668. if (isTransactionNode(this)) {
  1669. return this.zoomedIn ? this._spanChildren : this._children;
  1670. }
  1671. return this._children;
  1672. }
  1673. set children(children: TraceTreeNode[]) {
  1674. this._children = children;
  1675. }
  1676. get spanChildren(): (TraceTreeNode | NoDataNode)[] {
  1677. return this._spanChildren;
  1678. }
  1679. private _max_severity: keyof Theme['level'] | undefined;
  1680. get max_severity(): keyof Theme['level'] {
  1681. if (this._max_severity) {
  1682. return this._max_severity;
  1683. }
  1684. for (const error of this.errors) {
  1685. if (error.level === 'error' || error.level === 'fatal') {
  1686. this._max_severity = error.level;
  1687. return this.max_severity;
  1688. }
  1689. }
  1690. return 'default';
  1691. }
  1692. /**
  1693. * Invalidate the visual data used to render the tree, forcing it
  1694. * to be recalculated on the next render. This is useful when for example
  1695. * the tree is expanded or collapsed, or when the tree is mutated and
  1696. * the visual data is no longer valid as the indentation changes
  1697. */
  1698. invalidate(root?: TraceTreeNode<TraceTree.NodeValue>) {
  1699. this._connectors = undefined;
  1700. this._depth = undefined;
  1701. if (root) {
  1702. const queue = [...this.children];
  1703. if (isParentAutogroupedNode(this)) {
  1704. queue.push(this.head);
  1705. }
  1706. while (queue.length > 0) {
  1707. const next = queue.pop()!;
  1708. next.invalidate();
  1709. if (isParentAutogroupedNode(next)) {
  1710. queue.push(next.head);
  1711. }
  1712. for (let i = 0; i < next.children.length; i++) {
  1713. queue.push(next.children[i]);
  1714. }
  1715. }
  1716. }
  1717. }
  1718. getVisibleChildrenCount(): number {
  1719. const stack: TraceTreeNode<TraceTree.NodeValue>[] = [];
  1720. let count = 0;
  1721. if (isParentAutogroupedNode(this)) {
  1722. if (this.expanded) {
  1723. return this.head.getVisibleChildrenCount();
  1724. }
  1725. return this.tail.getVisibleChildrenCount();
  1726. }
  1727. if (this.expanded || isMissingInstrumentationNode(this)) {
  1728. for (let i = this.children.length - 1; i >= 0; i--) {
  1729. stack.push(this.children[i]);
  1730. }
  1731. }
  1732. while (stack.length > 0) {
  1733. const node = stack.pop()!;
  1734. count++;
  1735. // Since we're using a stack and it's LIFO, reverse the children before pushing them
  1736. // to ensure they are processed in the original left-to-right order.
  1737. if (node.expanded || isParentAutogroupedNode(node)) {
  1738. for (let i = node.children.length - 1; i >= 0; i--) {
  1739. stack.push(node.children[i]);
  1740. }
  1741. }
  1742. }
  1743. return count;
  1744. }
  1745. getVisibleChildren(): TraceTreeNode<TraceTree.NodeValue>[] {
  1746. const stack: TraceTreeNode<TraceTree.NodeValue>[] = [];
  1747. const children: TraceTreeNode<TraceTree.NodeValue>[] = [];
  1748. if (
  1749. this.expanded ||
  1750. isParentAutogroupedNode(this) ||
  1751. isMissingInstrumentationNode(this)
  1752. ) {
  1753. for (let i = this.children.length - 1; i >= 0; i--) {
  1754. stack.push(this.children[i]);
  1755. }
  1756. }
  1757. while (stack.length > 0) {
  1758. const node = stack.pop()!;
  1759. children.push(node);
  1760. // Since we're using a stack and it's LIFO, reverse the children before pushing them
  1761. // to ensure they are processed in the original left-to-right order.
  1762. if (node.expanded || isParentAutogroupedNode(node)) {
  1763. for (let i = node.children.length - 1; i >= 0; i--) {
  1764. stack.push(node.children[i]);
  1765. }
  1766. }
  1767. }
  1768. return children;
  1769. }
  1770. // Returns the min path required to reach the node from the root.
  1771. // @TODO: skip nodes that do not require fetching
  1772. get path(): TraceTree.NodePath[] {
  1773. const nodes: TraceTreeNode<TraceTree.NodeValue>[] = [this];
  1774. let current: TraceTreeNode<TraceTree.NodeValue> | null = this.parent;
  1775. if (isSpanNode(this) || isAutogroupedNode(this)) {
  1776. while (
  1777. current &&
  1778. (isSpanNode(current) || (isAutogroupedNode(current) && !current.expanded))
  1779. ) {
  1780. current = current.parent;
  1781. }
  1782. }
  1783. while (current) {
  1784. if (isTransactionNode(current)) {
  1785. nodes.push(current);
  1786. }
  1787. if (isSpanNode(current)) {
  1788. nodes.push(current);
  1789. while (current.parent) {
  1790. if (isTransactionNode(current.parent)) {
  1791. break;
  1792. }
  1793. if (isAutogroupedNode(current.parent) && current.parent.expanded) {
  1794. break;
  1795. }
  1796. current = current.parent;
  1797. }
  1798. }
  1799. if (isAutogroupedNode(current)) {
  1800. nodes.push(current);
  1801. }
  1802. current = current.parent;
  1803. }
  1804. return nodes.map(nodeToId);
  1805. }
  1806. print() {
  1807. // root nodes are -1 indexed, so we add 1 to the depth so .repeat doesnt throw
  1808. const offset = this.depth === -1 ? 1 : 0;
  1809. const nodes = [this, ...this.getVisibleChildren()];
  1810. const print = nodes
  1811. .map(t => printNode(t, offset))
  1812. .filter(Boolean)
  1813. .join('\n');
  1814. // eslint-disable-next-line no-console
  1815. console.log(print);
  1816. }
  1817. static Find(
  1818. root: TraceTreeNode<TraceTree.NodeValue>,
  1819. predicate: (node: TraceTreeNode<TraceTree.NodeValue>) => boolean
  1820. ): TraceTreeNode<TraceTree.NodeValue> | null {
  1821. const queue = [root];
  1822. while (queue.length > 0) {
  1823. const next = queue.pop()!;
  1824. if (predicate(next)) {
  1825. return next;
  1826. }
  1827. if (isParentAutogroupedNode(next)) {
  1828. queue.push(next.head);
  1829. } else {
  1830. for (const child of next.children) {
  1831. queue.push(child);
  1832. }
  1833. }
  1834. }
  1835. return null;
  1836. }
  1837. static ForEachChild(
  1838. root: TraceTreeNode<TraceTree.NodeValue>,
  1839. cb: (node: TraceTreeNode<TraceTree.NodeValue>) => void
  1840. ): void {
  1841. const queue = [root];
  1842. while (queue.length > 0) {
  1843. const next = queue.pop()!;
  1844. cb(next);
  1845. if (isParentAutogroupedNode(next)) {
  1846. queue.push(next.head);
  1847. } else {
  1848. const children = next.spanChildren ? next.spanChildren : next.children;
  1849. for (const child of children) {
  1850. queue.push(child);
  1851. }
  1852. }
  1853. }
  1854. }
  1855. static Root() {
  1856. return new TraceTreeNode(null, null, {
  1857. event_id: undefined,
  1858. project_slug: undefined,
  1859. });
  1860. }
  1861. }
  1862. export class MissingInstrumentationNode extends TraceTreeNode<TraceTree.MissingInstrumentationSpan> {
  1863. next: TraceTreeNode<TraceTree.Span>;
  1864. previous: TraceTreeNode<TraceTree.Span>;
  1865. constructor(
  1866. parent: TraceTreeNode<TraceTree.NodeValue>,
  1867. node: TraceTree.MissingInstrumentationSpan,
  1868. metadata: TraceTree.Metadata,
  1869. previous: TraceTreeNode<TraceTree.Span>,
  1870. next: TraceTreeNode<TraceTree.Span>
  1871. ) {
  1872. super(parent, node, metadata);
  1873. this.next = next;
  1874. this.previous = previous;
  1875. }
  1876. }
  1877. export class ParentAutogroupNode extends TraceTreeNode<TraceTree.ChildrenAutogroup> {
  1878. head: TraceTreeNode<TraceTree.Span>;
  1879. tail: TraceTreeNode<TraceTree.Span>;
  1880. groupCount: number = 0;
  1881. profiles: TraceTree.Profile[] = [];
  1882. private _autogroupedSegments: [number, number][] | undefined;
  1883. constructor(
  1884. parent: TraceTreeNode<TraceTree.NodeValue> | null,
  1885. node: TraceTree.ChildrenAutogroup,
  1886. metadata: TraceTree.Metadata,
  1887. head: TraceTreeNode<TraceTree.Span>,
  1888. tail: TraceTreeNode<TraceTree.Span>
  1889. ) {
  1890. super(parent, node, metadata);
  1891. this.expanded = false;
  1892. this.head = head;
  1893. this.tail = tail;
  1894. }
  1895. get children() {
  1896. if (this.expanded) {
  1897. return [this.head];
  1898. }
  1899. return this.tail.children;
  1900. }
  1901. get has_errors(): boolean {
  1902. return this.errors.size > 0 || this.performance_issues.size > 0;
  1903. }
  1904. get autogroupedSegments(): [number, number][] {
  1905. if (this._autogroupedSegments) {
  1906. return this._autogroupedSegments;
  1907. }
  1908. const children: TraceTreeNode<TraceTree.NodeValue>[] = [];
  1909. let start: TraceTreeNode<TraceTree.NodeValue> | undefined = this.head;
  1910. while (start && start !== this.tail) {
  1911. children.push(start);
  1912. start = start.children[0];
  1913. }
  1914. children.push(this.tail);
  1915. this._autogroupedSegments = computeAutogroupedBarSegments(children);
  1916. return this._autogroupedSegments;
  1917. }
  1918. }
  1919. export class SiblingAutogroupNode extends TraceTreeNode<TraceTree.SiblingAutogroup> {
  1920. groupCount: number = 0;
  1921. profiles: TraceTree.Profile[] = [];
  1922. private _autogroupedSegments: [number, number][] | undefined;
  1923. constructor(
  1924. parent: TraceTreeNode<TraceTree.NodeValue> | null,
  1925. node: TraceTree.SiblingAutogroup,
  1926. metadata: TraceTree.Metadata
  1927. ) {
  1928. super(parent, node, metadata);
  1929. this.expanded = false;
  1930. }
  1931. get has_errors(): boolean {
  1932. return this.errors.size > 0 || this.performance_issues.size > 0;
  1933. }
  1934. get autogroupedSegments(): [number, number][] {
  1935. if (this._autogroupedSegments) {
  1936. return this._autogroupedSegments;
  1937. }
  1938. this._autogroupedSegments = computeAutogroupedBarSegments(this.children);
  1939. return this._autogroupedSegments;
  1940. }
  1941. }
  1942. export class NoDataNode extends TraceTreeNode<null> {
  1943. constructor(parent: TraceTreeNode<TraceTree.NodeValue> | null) {
  1944. super(parent, null, {
  1945. event_id: undefined,
  1946. project_slug: undefined,
  1947. });
  1948. }
  1949. }
  1950. // Generates a ID of the tree node based on its type
  1951. function nodeToId(n: TraceTreeNode<TraceTree.NodeValue>): TraceTree.NodePath {
  1952. if (isAutogroupedNode(n)) {
  1953. if (isParentAutogroupedNode(n)) {
  1954. return `ag-${n.head.value.span_id}`;
  1955. }
  1956. if (isSiblingAutogroupedNode(n)) {
  1957. const child = n.children[0];
  1958. if (isSpanNode(child)) {
  1959. return `ag-${child.value.span_id}`;
  1960. }
  1961. }
  1962. }
  1963. if (isTransactionNode(n)) {
  1964. return `txn-${n.value.event_id}`;
  1965. }
  1966. if (isSpanNode(n)) {
  1967. return `span-${n.value.span_id}`;
  1968. }
  1969. if (isTraceNode(n)) {
  1970. return `trace-root`;
  1971. }
  1972. if (isTraceErrorNode(n)) {
  1973. return `error-${n.value.event_id}`;
  1974. }
  1975. if (isNoDataNode(n)) {
  1976. return `empty-node`;
  1977. }
  1978. if (isRootNode(n)) {
  1979. throw new Error('A path to root node does not exist as the node is virtual');
  1980. }
  1981. if (isMissingInstrumentationNode(n)) {
  1982. if (n.previous) {
  1983. return `ms-${n.previous.value.span_id}`;
  1984. }
  1985. if (n.next) {
  1986. return `ms-${n.next.value.span_id}`;
  1987. }
  1988. throw new Error('Missing instrumentation node must have a previous or next node');
  1989. }
  1990. throw new Error('Not implemented');
  1991. }
  1992. // Returns a list of segments from a grouping sequence that can be used to render a span bar chart
  1993. // It looks for gaps between spans and creates a segment for each gap. If there are no gaps, it
  1994. // merges the n and n+1 segments.
  1995. export function computeAutogroupedBarSegments(
  1996. nodes: TraceTreeNode<TraceTree.NodeValue>[]
  1997. ): [number, number][] {
  1998. if (nodes.length === 0) {
  1999. return [];
  2000. }
  2001. if (nodes.length === 1) {
  2002. const space = nodes[0].space;
  2003. if (!space) {
  2004. throw new Error(
  2005. 'Autogrouped node child has no defined space. This should not happen.'
  2006. );
  2007. }
  2008. return [space];
  2009. }
  2010. const first = nodes[0];
  2011. const multiplier = first.multiplier;
  2012. if (!isSpanNode(first)) {
  2013. throw new Error('Autogrouped node must have span children');
  2014. }
  2015. const segments: [number, number][] = [];
  2016. let start = first.value.start_timestamp;
  2017. let end = first.value.timestamp;
  2018. let i = 1;
  2019. while (i < nodes.length) {
  2020. const next = nodes[i];
  2021. if (!isSpanNode(next)) {
  2022. throw new Error('Autogrouped node must have span children');
  2023. }
  2024. if (next.value.start_timestamp > end) {
  2025. segments.push([start * multiplier, (end - start) * multiplier]);
  2026. start = next.value.start_timestamp;
  2027. end = next.value.timestamp;
  2028. i++;
  2029. } else {
  2030. end = next.value.timestamp;
  2031. i++;
  2032. }
  2033. }
  2034. segments.push([start * multiplier, (end - start) * multiplier]);
  2035. return segments;
  2036. }
  2037. // Returns a list of errors related to the txn with ids matching the span id
  2038. function getRelatedSpanErrorsFromTransaction(
  2039. span: RawSpanType,
  2040. node?: TraceTreeNode<TraceTree.NodeValue>
  2041. ): TraceErrorType[] {
  2042. if (!node || !node.value || !isTransactionNode(node)) {
  2043. return [];
  2044. }
  2045. if (!node?.value?.errors?.length) {
  2046. return [];
  2047. }
  2048. const errors: TraceErrorType[] = [];
  2049. for (const error of node.value.errors) {
  2050. if (error.span === span.span_id) {
  2051. errors.push(error);
  2052. }
  2053. }
  2054. return errors;
  2055. }
  2056. // Returns a list of performance errors related to the txn with ids matching the span id
  2057. function getRelatedPerformanceIssuesFromTransaction(
  2058. span: RawSpanType,
  2059. node?: TraceTreeNode<TraceTree.NodeValue>
  2060. ): TraceTree.TracePerformanceIssue[] {
  2061. if (!node || !node.value || !isTransactionNode(node)) {
  2062. return [];
  2063. }
  2064. if (!node?.value?.performance_issues?.length) {
  2065. return [];
  2066. }
  2067. const performanceIssues: TraceTree.TracePerformanceIssue[] = [];
  2068. for (const perfIssue of node.value.performance_issues) {
  2069. for (const s of perfIssue.span) {
  2070. if (s === span.span_id) {
  2071. performanceIssues.push(perfIssue);
  2072. }
  2073. }
  2074. for (const suspect of perfIssue.suspect_spans) {
  2075. if (suspect === span.span_id) {
  2076. performanceIssues.push(perfIssue);
  2077. }
  2078. }
  2079. }
  2080. return performanceIssues;
  2081. }
  2082. function hasEventWithEventId(
  2083. node: TraceTreeNode<TraceTree.NodeValue>,
  2084. eventId: string
  2085. ): boolean {
  2086. // Skip trace nodes since they accumulate all errors and performance issues
  2087. // in the trace and is not an event.
  2088. if (isTraceNode(node)) {
  2089. return false;
  2090. }
  2091. // Search in errors
  2092. if (node.errors.size > 0) {
  2093. for (const e of node.errors) {
  2094. if (e.event_id === eventId) {
  2095. return true;
  2096. }
  2097. }
  2098. }
  2099. // Search in performance issues
  2100. if (node.performance_issues.size > 0) {
  2101. for (const p of node.performance_issues) {
  2102. if (p.event_id === eventId) {
  2103. return true;
  2104. }
  2105. }
  2106. }
  2107. // Check if we are maybe looking for the profile_id
  2108. if (node.value && 'profile_id' in node.value && node.value.profile_id === eventId) {
  2109. return true;
  2110. }
  2111. return false;
  2112. }
  2113. function findInTreeByEventId(start: TraceTreeNode<TraceTree.NodeValue>, eventId: string) {
  2114. return TraceTreeNode.Find(start, node => {
  2115. if (isTransactionNode(node)) {
  2116. if (node.value.event_id === eventId) {
  2117. return true;
  2118. }
  2119. } else if (isSpanNode(node)) {
  2120. return node.value.span_id === eventId;
  2121. } else if (isTraceErrorNode(node)) {
  2122. return node.value.event_id === eventId;
  2123. }
  2124. return hasEventWithEventId(node, eventId);
  2125. });
  2126. }
  2127. function findInTreeFromSegment(
  2128. start: TraceTreeNode<TraceTree.NodeValue>,
  2129. segment: TraceTree.NodePath
  2130. ): TraceTreeNode<TraceTree.NodeValue> | null {
  2131. const [type, id] = segment.split('-');
  2132. if (!type || !id) {
  2133. throw new TypeError('Node path must be in the format of `type-id`');
  2134. }
  2135. return TraceTreeNode.Find(start, node => {
  2136. if (type === 'txn' && isTransactionNode(node)) {
  2137. return node.value.event_id === id;
  2138. }
  2139. if (type === 'span' && isSpanNode(node)) {
  2140. return node.value.span_id === id;
  2141. }
  2142. if (type === 'ag' && isAutogroupedNode(node)) {
  2143. if (isParentAutogroupedNode(node)) {
  2144. return node.head.value.span_id === id || node.tail.value.span_id === id;
  2145. }
  2146. if (isSiblingAutogroupedNode(node)) {
  2147. const child = node.children[0];
  2148. if (isSpanNode(child)) {
  2149. return child.value.span_id === id;
  2150. }
  2151. }
  2152. }
  2153. if (type === 'ms' && isMissingInstrumentationNode(node)) {
  2154. return node.previous.value.span_id === id || node.next.value.span_id === id;
  2155. }
  2156. if (type === 'error' && isTraceErrorNode(node)) {
  2157. return node.value.event_id === id;
  2158. }
  2159. if (type === 'empty' && isNoDataNode(node)) {
  2160. return true;
  2161. }
  2162. return false;
  2163. });
  2164. }
  2165. function printNode(t: TraceTreeNode<TraceTree.NodeValue>, offset: number): string {
  2166. // +1 because we may be printing from the root which is -1 indexed
  2167. const padding = ' '.repeat(t.depth + offset);
  2168. if (isAutogroupedNode(t)) {
  2169. if (isParentAutogroupedNode(t)) {
  2170. return padding + `parent autogroup (${t.groupCount})`;
  2171. }
  2172. if (isSiblingAutogroupedNode(t)) {
  2173. return padding + `sibling autogroup (${t.groupCount})`;
  2174. }
  2175. return padding + 'autogroup';
  2176. }
  2177. if (isSpanNode(t)) {
  2178. return padding + (t.value.op || t.value.span_id || 'unknown span');
  2179. }
  2180. if (isTransactionNode(t)) {
  2181. return padding + (t.value.transaction || 'unknown transaction');
  2182. }
  2183. if (isMissingInstrumentationNode(t)) {
  2184. return padding + 'missing_instrumentation';
  2185. }
  2186. if (isRootNode(t)) {
  2187. return padding + 'Root';
  2188. }
  2189. if (isTraceNode(t)) {
  2190. return padding + 'Trace';
  2191. }
  2192. if (isNoDataNode(t)) {
  2193. return padding + 'No Data';
  2194. }
  2195. if (isTraceErrorNode(t)) {
  2196. return padding + (t.value.event_id || t.value.level) || 'unknown trace error';
  2197. }
  2198. return 'unknown node';
  2199. }
  2200. export function traceNodeAnalyticsName(node: TraceTreeNode<TraceTree.NodeValue>): string {
  2201. if (isAutogroupedNode(node)) {
  2202. return isParentAutogroupedNode(node) ? 'parent autogroup' : 'sibling autogroup';
  2203. }
  2204. if (isSpanNode(node)) return 'span';
  2205. if (isTransactionNode(node)) return 'transaction';
  2206. if (isMissingInstrumentationNode(node)) return 'missing instrumentation';
  2207. if (isRootNode(node)) return 'root';
  2208. if (isTraceNode(node)) return 'trace';
  2209. if (isNoDataNode(node)) return 'no data';
  2210. if (isTraceErrorNode(node)) return 'error';
  2211. return 'unknown';
  2212. }
  2213. export function traceNodeAdjacentAnalyticsProperties(
  2214. node: TraceTreeNode<TraceTree.NodeValue>
  2215. ): Pick<
  2216. TracingEventParameters['trace.trace_layout.span_row_click'],
  2217. 'next_op' | 'parent_op' | 'previous_op'
  2218. > {
  2219. if (isNoDataNode(node)) {
  2220. const parent_transaction = node.parent_transaction;
  2221. if (!parent_transaction) return {};
  2222. return {
  2223. parent_op: parent_transaction.value['transaction.op'],
  2224. };
  2225. }
  2226. if (isMissingInstrumentationNode(node)) {
  2227. return {
  2228. previous_op: node.previous.value.op,
  2229. next_op: node.next.value.op,
  2230. };
  2231. }
  2232. return {};
  2233. }
  2234. // Creates an example trace response that we use to render the loading placeholder
  2235. function partialTransaction(
  2236. partial: Partial<TraceTree.Transaction>
  2237. ): TraceTree.Transaction {
  2238. return {
  2239. start_timestamp: 0,
  2240. timestamp: 0,
  2241. errors: [],
  2242. performance_issues: [],
  2243. parent_span_id: '',
  2244. span_id: '',
  2245. parent_event_id: '',
  2246. project_id: 0,
  2247. sdk_name: '',
  2248. profiler_id: '',
  2249. 'transaction.duration': 0,
  2250. 'transaction.op': 'loading-transaction',
  2251. 'transaction.status': 'loading-status',
  2252. generation: 0,
  2253. project_slug: '',
  2254. event_id: `event_id`,
  2255. transaction: `transaction`,
  2256. children: [],
  2257. ...partial,
  2258. };
  2259. }
  2260. export function makeExampleTrace(metadata: TraceTree.Metadata): TraceTree {
  2261. const trace: TraceTree.Trace = {
  2262. transactions: [],
  2263. orphan_errors: [],
  2264. };
  2265. function randomBetween(min: number, max: number) {
  2266. return Math.floor(Math.random() * (max - min + 1) + min);
  2267. }
  2268. let start = new Date().getTime();
  2269. const root = partialTransaction({
  2270. ...metadata,
  2271. generation: 0,
  2272. start_timestamp: start,
  2273. transaction: 'root transaction',
  2274. timestamp: start + randomBetween(100, 200),
  2275. });
  2276. trace.transactions.push(root);
  2277. for (let i = 0; i < 50; i++) {
  2278. const end = start + randomBetween(100, 200);
  2279. const nest = i > 0 && Math.random() > 0.33;
  2280. if (nest) {
  2281. const parent = root.children[root.children.length - 1];
  2282. parent.children.push(
  2283. partialTransaction({
  2284. ...metadata,
  2285. generation: 0,
  2286. start_timestamp: start,
  2287. transaction: `parent transaction ${i}`,
  2288. timestamp: end,
  2289. })
  2290. );
  2291. parent.timestamp = end;
  2292. } else {
  2293. root.children.push(
  2294. partialTransaction({
  2295. ...metadata,
  2296. generation: 0,
  2297. start_timestamp: start,
  2298. transaction: 'loading...',
  2299. ['transaction.op']: 'loading',
  2300. timestamp: end,
  2301. })
  2302. );
  2303. }
  2304. start = end;
  2305. }
  2306. const tree = TraceTree.FromTrace(trace, null);
  2307. return tree;
  2308. }