traceTree.tsx 79 KB

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