traceTree.tsx 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094
  1. import * as Sentry from '@sentry/react';
  2. import type {Location} from 'history';
  3. import * as qs from 'query-string';
  4. import type {Client} from 'sentry/api';
  5. import type {RawSpanType} from 'sentry/components/events/interfaces/spans/types';
  6. import type {Event, EventTransaction, Measurement} from 'sentry/types/event';
  7. import type {Organization} from 'sentry/types/organization';
  8. import type {
  9. TraceError as TraceErrorType,
  10. TraceFullDetailed,
  11. TracePerformanceIssue as TracePerformanceIssueType,
  12. TraceSplitResults,
  13. } from 'sentry/utils/performance/quickTrace/types';
  14. import {collectTraceMeasurements} from 'sentry/views/performance/newTraceDetails/traceModels/traceTree.measurements';
  15. import type {TracePreferencesState} from 'sentry/views/performance/newTraceDetails/traceState/tracePreferences';
  16. import type {ReplayTrace} from 'sentry/views/replays/detail/trace/useReplayTraces';
  17. import type {ReplayRecord} from 'sentry/views/replays/types';
  18. import {isRootTransaction} from '../../traceDetails/utils';
  19. import {getTraceQueryParams} from '../traceApi/useTrace';
  20. import type {TraceMetaQueryResults} from '../traceApi/useTraceMeta';
  21. import {
  22. getPageloadTransactionChildCount,
  23. isAutogroupedNode,
  24. isBrowserRequestSpan,
  25. isCollapsedNode,
  26. isJavascriptSDKTransaction,
  27. isMissingInstrumentationNode,
  28. isPageloadTransactionNode,
  29. isParentAutogroupedNode,
  30. isRootNode,
  31. isServerRequestHandlerTransactionNode,
  32. isSiblingAutogroupedNode,
  33. isSpanNode,
  34. isTraceErrorNode,
  35. isTraceNode,
  36. isTransactionNode,
  37. shouldAddMissingInstrumentationSpan,
  38. } from '../traceGuards';
  39. import {makeExampleTrace} from './makeExampleTrace';
  40. import {MissingInstrumentationNode} from './missingInstrumentationNode';
  41. import {ParentAutogroupNode} from './parentAutogroupNode';
  42. import {SiblingAutogroupNode} from './siblingAutogroupNode';
  43. import {TraceTreeEventDispatcher} from './traceTreeEventDispatcher';
  44. import {TraceTreeNode} from './traceTreeNode';
  45. /**
  46. *
  47. * This file implements the tree data structure that is used to represent a trace. We do
  48. * this both for performance reasons as well as flexibility. The requirement for a tree
  49. * is to support incremental patching and updates. This is important because we want to
  50. * be able to fetch more data as the user interacts with the tree, and we want to be able
  51. * efficiently update the tree as we receive more data.
  52. *
  53. * The trace is represented as a tree with different node value types (transaction or span)
  54. * Each tree node contains a reference to its parent and a list of references to its children,
  55. * as well as a reference to the value that the node holds. Each node also contains
  56. * some meta data and state about the node, such as if it is expanded or zoomed in. The benefit
  57. * of abstracting parts of the UI state is that the tree will persist user actions such as expanding
  58. * or collapsing nodes which would have otherwise been lost when individual nodes are remounted in the tree.
  59. *
  60. * Each tree holds a list reference, which is a live reference to a flattened representation
  61. * 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
  62. * reasons as we want to support mutations on traces with ~100k+ nodes), callers need to manage reactivity themselves.
  63. *
  64. * An alternative, but not recommended approach is to call build() on the tree after each mutation,
  65. * which will iterate over all of the children and build a fresh list reference.
  66. *
  67. * In most cases, the initial tree is a list of transactions containing other transactions. Each transaction can
  68. * then be expanded into a list of spans which can also in some cases be expanded.
  69. *
  70. * - trace - trace
  71. * |- parent transaction --> when expanding |- parent transaction
  72. * |- child transaction |- span
  73. * |- span this used to be a transaction,
  74. * |- child transaction span <- but is now be a list of spans
  75. * |- span belonging to the transaction
  76. * this results in child txns to be lost,
  77. * which is a confusing user experience
  78. *
  79. * The tree supports autogrouping of spans vertically or as siblings. When that happens, a autogrouped node of either a vertical or
  80. * sibling type is inserted as an intermediary node. In the vertical case, the autogrouped node
  81. * holds the reference to the head and tail of the autogrouped sequence. In the sibling case, the autogrouped node
  82. * holds a reference to the children that are part of the autogrouped sequence. When expanding and collapsing these nodes,
  83. * the tree perform a reference swap to either point to the head (when expanded) or tail (when collapsed) of the autogrouped sequence.
  84. *
  85. * In vertical grouping case, the following happens:
  86. *
  87. * - root - root
  88. * - trace - trace
  89. * |- transaction |- transaction
  90. * |- span 1 <-| these become autogrouped |- autogrouped (head=span1, tail=span3, children points to children of tail)
  91. * |- span 2 |- as they are inserted into |- other span (parent points to autogrouped node)
  92. * |- span 3 <-| the tree.
  93. * |- other span
  94. *
  95. * When the autogrouped node is expanded the UI needs to show the entire collapsed chain, so we swap the tail children to point
  96. * back to the tail, and have autogrouped node point to its head as the children.
  97. *
  98. * - root - root
  99. * - trace - trace
  100. * |- transaction |- transaction
  101. * |- autogrouped (head=span1, tail=span3) <- when expanding |- autogrouped (head=span1, tail=span3, children points to head)
  102. * | other span (paren points to autogrouped) |- span 1 (head)
  103. * |- span 2
  104. * |- span 3 (tail)
  105. * |- other span (children of tail, parent points to tail)
  106. *
  107. * Notes and improvements:
  108. * - the notion of expanded and zoomed is confusing, they stand for the same idea from a UI pov
  109. * - ???
  110. */
  111. export declare namespace TraceTree {
  112. interface TraceTreeEvents {
  113. ['trace timeline change']: (view: [number, number]) => void;
  114. }
  115. // Raw node values
  116. interface Span extends RawSpanType {
  117. measurements?: Record<string, Measurement>;
  118. }
  119. interface Transaction extends TraceFullDetailed {
  120. profiler_id: string;
  121. sdk_name: string;
  122. }
  123. type Trace = TraceSplitResults<Transaction>;
  124. type TraceError = TraceErrorType;
  125. type TracePerformanceIssue = TracePerformanceIssueType;
  126. type Profile = {profile_id: string} | {profiler_id: string};
  127. type Project = {
  128. id: number;
  129. slug: string;
  130. };
  131. type Root = null;
  132. // All possible node value types
  133. type NodeValue =
  134. | Trace
  135. | Transaction
  136. | TraceError
  137. | Span
  138. | MissingInstrumentationSpan
  139. | SiblingAutogroup
  140. | ChildrenAutogroup
  141. | CollapsedNode
  142. | Root;
  143. interface CollapsedNode {
  144. type: 'collapsed';
  145. }
  146. // Node types
  147. interface MissingInstrumentationSpan {
  148. start_timestamp: number;
  149. timestamp: number;
  150. type: 'missing_instrumentation';
  151. }
  152. interface SiblingAutogroup extends Span {
  153. autogrouped_by: {
  154. description: string;
  155. op: string;
  156. };
  157. }
  158. interface ChildrenAutogroup extends Span {
  159. autogrouped_by: {
  160. op: string;
  161. };
  162. }
  163. // All possible node types
  164. type Node =
  165. | TraceTreeNode<NodeValue>
  166. | ParentAutogroupNode
  167. | SiblingAutogroupNode
  168. | MissingInstrumentationNode;
  169. type NodePath =
  170. `${'txn' | 'span' | 'ag' | 'trace' | 'ms' | 'error' | 'empty'}-${string}`;
  171. type Metadata = {
  172. event_id: string | undefined;
  173. project_slug: string | undefined;
  174. spans?: number;
  175. };
  176. type Indicator = {
  177. duration: number;
  178. label: string;
  179. measurement: Measurement;
  180. poor: boolean;
  181. start: number;
  182. type: 'cls' | 'fcp' | 'fp' | 'lcp' | 'ttfb';
  183. };
  184. type CollectedVital = {key: string; measurement: Measurement};
  185. }
  186. export enum TraceShape {
  187. ONE_ROOT = 'one_root',
  188. NO_ROOT = 'no_root',
  189. BROWSER_MULTIPLE_ROOTS = 'browser_multiple_roots',
  190. MULTIPLE_ROOTS = 'multiple_roots',
  191. BROKEN_SUBTRACES = 'broken_subtraces',
  192. ONLY_ERRORS = 'only_errors',
  193. EMPTY_TRACE = 'empty_trace',
  194. }
  195. function fetchTransactionSpans(
  196. api: Client,
  197. organization: Organization,
  198. project_slug: string,
  199. event_id: string
  200. ): Promise<EventTransaction> {
  201. return api.requestPromise(
  202. `/organizations/${organization.slug}/events/${project_slug}:${event_id}/?averageColumn=span.self_time&averageColumn=span.duration`
  203. );
  204. }
  205. function fetchTrace(
  206. api: Client,
  207. params: {
  208. orgSlug: string;
  209. query: string;
  210. traceId: string;
  211. }
  212. ): Promise<TraceSplitResults<TraceTree.Transaction>> {
  213. return api.requestPromise(
  214. `/organizations/${params.orgSlug}/events-trace/${params.traceId}/?${params.query}`
  215. );
  216. }
  217. export class TraceTree extends TraceTreeEventDispatcher {
  218. eventsCount = 0;
  219. projects = new Set<TraceTree.Project>();
  220. type: 'loading' | 'empty' | 'error' | 'trace' = 'trace';
  221. root: TraceTreeNode<null> = TraceTreeNode.Root();
  222. vital_types: Set<'web' | 'mobile'> = new Set();
  223. vitals = new Map<TraceTreeNode<TraceTree.NodeValue>, TraceTree.CollectedVital[]>();
  224. profiled_events = new Set<TraceTreeNode<TraceTree.NodeValue>>();
  225. indicators: TraceTree.Indicator[] = [];
  226. list: TraceTreeNode<TraceTree.NodeValue>[] = [];
  227. events: Map<string, EventTransaction> = new Map();
  228. private _spanPromises: Map<string, Promise<EventTransaction>> = new Map();
  229. static MISSING_INSTRUMENTATION_THRESHOLD_MS = 100;
  230. static Empty() {
  231. const tree = new TraceTree().build();
  232. tree.type = 'empty';
  233. return tree;
  234. }
  235. static Loading(metadata: TraceTree.Metadata): TraceTree {
  236. const t = makeExampleTrace(metadata);
  237. t.type = 'loading';
  238. t.build();
  239. return t;
  240. }
  241. static Error(metadata: TraceTree.Metadata): TraceTree {
  242. const t = makeExampleTrace(metadata);
  243. t.type = 'error';
  244. t.build();
  245. return t;
  246. }
  247. static FromTrace(
  248. trace: TraceTree.Trace,
  249. options: {
  250. meta: TraceMetaQueryResults['data'] | null;
  251. replay: ReplayRecord | null;
  252. }
  253. ): TraceTree {
  254. const tree = new TraceTree();
  255. const traceNode = new TraceTreeNode<TraceTree.Trace>(tree.root, trace, {
  256. event_id: undefined,
  257. project_slug: undefined,
  258. });
  259. tree.root.children.push(traceNode);
  260. function visit(
  261. parent: TraceTreeNode<TraceTree.NodeValue | null>,
  262. value: TraceTree.Transaction | TraceTree.TraceError
  263. ) {
  264. tree.eventsCount++;
  265. tree.projects.add({
  266. id: value.project_id,
  267. slug: value.project_slug,
  268. });
  269. const node = new TraceTreeNode(parent, value, {
  270. spans: options.meta?.transactiontoSpanChildrenCount[value.event_id] ?? 0,
  271. project_slug: value && 'project_slug' in value ? value.project_slug : undefined,
  272. event_id: value && 'event_id' in value ? value.event_id : undefined,
  273. });
  274. if (isTransactionNode(node)) {
  275. const spanChildrenCount =
  276. options.meta?.transactiontoSpanChildrenCount[node.value.event_id];
  277. // We check for >1 events, as the first one is the transaction node itself
  278. node.canFetch = spanChildrenCount === undefined ? true : spanChildrenCount > 1;
  279. }
  280. if (!node.metadata.project_slug && !node.metadata.event_id) {
  281. const parentNodeMetadata = TraceTree.ParentTransaction(node)?.metadata;
  282. if (parentNodeMetadata) {
  283. node.metadata = {...parentNodeMetadata};
  284. }
  285. }
  286. parent.children.push(node);
  287. if (node.value && 'children' in node.value) {
  288. for (const child of node.value.children) {
  289. visit(node, child);
  290. }
  291. }
  292. }
  293. traceQueueIterator(trace, traceNode, visit);
  294. // At this point, the tree is built, we need iterate over it again to collect all of the
  295. // measurements, web vitals, errors and perf issues as well as calculate the min and max space
  296. // the trace should take up.
  297. const traceSpaceBounds = [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY];
  298. TraceTree.ForEachChild(traceNode, c => {
  299. traceSpaceBounds[0] = Math.min(traceSpaceBounds[0], c.space[0]);
  300. traceSpaceBounds[1] = Math.max(traceSpaceBounds[1], c.space[0] + c.space[1]);
  301. if (isTransactionNode(c)) {
  302. for (const error of c.value.errors) {
  303. traceNode.errors.add(error);
  304. }
  305. for (const performanceIssue of c.value.performance_issues) {
  306. traceNode.performance_issues.add(performanceIssue);
  307. }
  308. }
  309. if (isTraceErrorNode(c)) {
  310. traceNode.errors.add(c.value);
  311. }
  312. if (c.profiles.length > 0) {
  313. tree.profiled_events.add(c);
  314. }
  315. if (c.value && 'measurements' in c.value) {
  316. tree.indicators = tree.indicators.concat(
  317. collectTraceMeasurements(
  318. c,
  319. c.space[0],
  320. c.value.measurements,
  321. tree.vitals,
  322. tree.vital_types
  323. )
  324. );
  325. }
  326. if (
  327. c.parent &&
  328. isPageloadTransactionNode(c) &&
  329. isServerRequestHandlerTransactionNode(c.parent) &&
  330. getPageloadTransactionChildCount(c.parent) === 1
  331. ) {
  332. // // The swap can occur at a later point when new transactions are fetched,
  333. // // which means we need to invalidate the tree and re-render the UI.
  334. const parent = c.parent.parent;
  335. TraceTree.Swap({parent: c.parent, child: c, reason: 'pageload server handler'});
  336. TraceTree.invalidate(parent!, true);
  337. }
  338. });
  339. // The sum of all durations of traces that exist under a replay is not always
  340. // equal to the duration of the replay. We need to adjust the traceview bounds
  341. // to ensure that we can see the max of the replay duration and the sum(trace durations). This way, we
  342. // can ensure that the replay timestamp indicators are always visible in the traceview along with all spans from the traces.
  343. if (options.replay) {
  344. const replayStart = options.replay.started_at.getTime();
  345. const replayEnd = options.replay.finished_at.getTime();
  346. traceSpaceBounds[0] = Math.min(traceSpaceBounds[0], replayStart);
  347. traceSpaceBounds[1] = Math.max(traceSpaceBounds[1], replayEnd);
  348. }
  349. for (const indicator of tree.indicators) {
  350. // If any indicator starts after the trace ends, set end to the indicator start
  351. if (indicator.start > traceSpaceBounds[1]) {
  352. traceSpaceBounds[1] = indicator.start;
  353. }
  354. // If an indicator starts before the trace start, set start to the indicator start
  355. if (indicator.start < traceSpaceBounds[0]) {
  356. traceSpaceBounds[0] = indicator.start;
  357. }
  358. }
  359. // Space needs a start and end, if we don't have one we can't construct a timeline.
  360. if (!Number.isFinite(traceSpaceBounds[0])) {
  361. traceSpaceBounds[0] = 0;
  362. }
  363. if (!Number.isFinite(traceSpaceBounds[1])) {
  364. traceSpaceBounds[1] = 0;
  365. }
  366. const space = [traceSpaceBounds[0], traceSpaceBounds[1] - traceSpaceBounds[0]];
  367. tree.root.space = [space[0], space[1]];
  368. traceNode.space = [space[0], space[1]];
  369. tree.indicators.sort((a, b) => a.start - b.start);
  370. return tree;
  371. }
  372. static FromSpans(
  373. node: TraceTreeNode<TraceTree.NodeValue>,
  374. spans: TraceTree.Span[],
  375. event: EventTransaction | null
  376. ): [TraceTreeNode<TraceTree.NodeValue>, [number, number]] {
  377. // collect transactions
  378. const transactions = TraceTree.FindAll(node, n =>
  379. isTransactionNode(n)
  380. ) as TraceTreeNode<TraceTree.Transaction>[];
  381. // Create span nodes
  382. const spanNodes: TraceTreeNode<TraceTree.Span>[] = [];
  383. const spanIdToNode = new Map<string, TraceTreeNode<TraceTree.NodeValue>>();
  384. // Transactions have a span_id that needs to be used as the edge to child child span
  385. if (node.value && 'span_id' in node.value) {
  386. spanIdToNode.set(node.value.span_id, node);
  387. }
  388. for (const span of spans) {
  389. const spanNode: TraceTreeNode<TraceTree.Span> = new TraceTreeNode(null, span, {
  390. event_id: node.metadata.event_id,
  391. project_slug: node.metadata.project_slug,
  392. });
  393. spanNode.event = event;
  394. if (spanIdToNode.has(span.span_id)) {
  395. Sentry.withScope(scope => {
  396. scope.setFingerprint(['trace-span-id-hash-collision']);
  397. scope.captureMessage('Span ID hash collision detected');
  398. });
  399. }
  400. spanIdToNode.set(span.span_id, spanNode);
  401. spanNodes.push(spanNode);
  402. }
  403. // Clear children of root node as we are recreating the sub tree
  404. node.children = [];
  405. // Construct the span tree
  406. for (const span of spanNodes) {
  407. // If the span has no parent span id, nest it under the root
  408. const parent = span.value.parent_span_id
  409. ? spanIdToNode.get(span.value.parent_span_id) ?? node
  410. : node;
  411. span.parent = parent;
  412. parent.children.push(span);
  413. }
  414. // Reparent transactions under children spans
  415. for (const transaction of transactions) {
  416. const parent = spanIdToNode.get(transaction.value.parent_span_id!);
  417. // If the parent span does not exist in the span tree, the transaction will remain under the current node
  418. if (!parent) {
  419. if (transaction.parent?.children.indexOf(transaction) === -1) {
  420. transaction.parent.children.push(transaction);
  421. }
  422. continue;
  423. }
  424. if (transaction === node) {
  425. Sentry.withScope(scope => {
  426. scope.setFingerprint(['trace-tree-span-parent-cycle']);
  427. scope.captureMessage(
  428. 'Span is a parent of its own transaction, this should not be possible'
  429. );
  430. });
  431. continue;
  432. }
  433. parent.children.push(transaction);
  434. transaction.parent = parent;
  435. }
  436. const subTreeSpaceBounds: [number, number] = [node.space[0], node.space[1]];
  437. TraceTree.ForEachChild(node, c => {
  438. c.invalidate();
  439. // When reparenting transactions under spans, the children are not guaranteed to be in order
  440. // so we need to sort them chronologically after the reparenting is complete
  441. // Track the min and max space of the sub tree as spans have ms precision
  442. subTreeSpaceBounds[0] = Math.min(subTreeSpaceBounds[0], c.space[0]);
  443. subTreeSpaceBounds[1] = Math.max(subTreeSpaceBounds[1], c.space[1]);
  444. if (isSpanNode(c)) {
  445. for (const performanceIssue of getRelatedPerformanceIssuesFromTransaction(
  446. c.value,
  447. node
  448. )) {
  449. c.performance_issues.add(performanceIssue);
  450. }
  451. for (const error of getRelatedSpanErrorsFromTransaction(c.value, node)) {
  452. c.errors.add(error);
  453. }
  454. if (isBrowserRequestSpan(c.value)) {
  455. const serverRequestHandler = c.parent?.children.find(n =>
  456. isServerRequestHandlerTransactionNode(n)
  457. );
  458. if (serverRequestHandler) {
  459. serverRequestHandler.parent!.children =
  460. serverRequestHandler.parent!.children.filter(
  461. n => n !== serverRequestHandler
  462. );
  463. c.children.push(serverRequestHandler);
  464. serverRequestHandler.parent = c;
  465. }
  466. }
  467. }
  468. c.children.sort(traceChronologicalSort);
  469. });
  470. if (!Number.isFinite(subTreeSpaceBounds[0])) {
  471. subTreeSpaceBounds[0] = 0;
  472. }
  473. if (!Number.isFinite(subTreeSpaceBounds[1])) {
  474. subTreeSpaceBounds[1] = 0;
  475. }
  476. return [node, subTreeSpaceBounds];
  477. }
  478. appendTree(tree: TraceTree) {
  479. const baseTraceNode = this.root.children[0];
  480. const additionalTraceNode = tree.root.children[0];
  481. if (!baseTraceNode || !additionalTraceNode) {
  482. throw new Error('No trace node found in tree');
  483. }
  484. for (const child of additionalTraceNode.children) {
  485. child.parent = baseTraceNode;
  486. baseTraceNode.children.push(child);
  487. }
  488. for (const error of additionalTraceNode.errors) {
  489. baseTraceNode.errors.add(error);
  490. }
  491. for (const performanceIssue of additionalTraceNode.performance_issues) {
  492. baseTraceNode.performance_issues.add(performanceIssue);
  493. }
  494. for (const profile of additionalTraceNode.profiles) {
  495. baseTraceNode.profiles.push(profile);
  496. }
  497. for (const [node, vitals] of tree.vitals) {
  498. this.vitals.set(node, vitals);
  499. }
  500. for (const [node, _] of tree.vitals) {
  501. if (
  502. baseTraceNode.space?.[0] &&
  503. node.value &&
  504. 'start_timestamp' in node.value &&
  505. 'measurements' in node.value
  506. ) {
  507. tree.indicators = tree.indicators.concat(
  508. collectTraceMeasurements(
  509. node,
  510. baseTraceNode.space[0],
  511. node.value.measurements,
  512. this.vitals,
  513. this.vital_types
  514. )
  515. );
  516. }
  517. }
  518. // We need to invalidate the data in the last node of the tree
  519. // so that the connectors are updated and pointing to the sibling nodes
  520. const last = this.root.children[this.root.children.length - 1];
  521. TraceTree.invalidate(last, true);
  522. const previousEnd = this.root.space[0] + this.root.space[1];
  523. const newEnd = tree.root.space[0] + tree.root.space[1];
  524. this.root.space[0] = Math.min(tree.root.space[0], this.root.space[0]);
  525. this.root.space[1] = Math.max(
  526. previousEnd - this.root.space[0],
  527. newEnd - this.root.space[0]
  528. );
  529. for (const child of tree.root.children) {
  530. this.list = this.list.concat(TraceTree.VisibleChildren(child));
  531. }
  532. }
  533. /**
  534. * Invalidate the visual data used to render the tree, forcing it
  535. * to be recalculated on the next render. This is useful when for example
  536. * the tree is expanded or collapsed, or when the tree is mutated and
  537. * the visual data is no longer valid as the indentation changes
  538. */
  539. static invalidate(node: TraceTreeNode<TraceTree.NodeValue>, recurse: boolean) {
  540. node.invalidate();
  541. if (recurse) {
  542. const queue = [...node.children];
  543. if (isParentAutogroupedNode(node)) {
  544. queue.push(node.head);
  545. }
  546. while (queue.length > 0) {
  547. const next = queue.pop()!;
  548. next.invalidate();
  549. if (isParentAutogroupedNode(next)) {
  550. queue.push(next.head);
  551. }
  552. for (let i = 0; i < next.children.length; i++) {
  553. queue.push(next.children[i]);
  554. }
  555. }
  556. }
  557. }
  558. static DetectMissingInstrumentation(root: TraceTreeNode<TraceTree.NodeValue>): number {
  559. let previous: TraceTreeNode<TraceTree.NodeValue> | null = null;
  560. let missingInstrumentationCount = 0;
  561. TraceTree.ForEachChild(root, child => {
  562. if (
  563. previous &&
  564. child &&
  565. isSpanNode(previous) &&
  566. isSpanNode(child) &&
  567. shouldAddMissingInstrumentationSpan(child.event?.sdk?.name ?? '') &&
  568. shouldAddMissingInstrumentationSpan(previous.event?.sdk?.name ?? '') &&
  569. child.space[0] - previous.space[0] - previous.space[1] >=
  570. TraceTree.MISSING_INSTRUMENTATION_THRESHOLD_MS
  571. ) {
  572. const node = new MissingInstrumentationNode(
  573. child.parent!,
  574. {
  575. type: 'missing_instrumentation',
  576. start_timestamp: previous.value.timestamp,
  577. timestamp: child.value.start_timestamp,
  578. },
  579. {
  580. event_id: undefined,
  581. project_slug: undefined,
  582. },
  583. previous,
  584. child
  585. );
  586. missingInstrumentationCount++;
  587. if (child.parent === previous) {
  588. // The tree is dfs iterated, so it can only ever be the first child
  589. previous.children.splice(0, 0, node);
  590. node.parent = previous;
  591. } else {
  592. const childIndex = child.parent?.children.indexOf(child) ?? -1;
  593. if (childIndex === -1) {
  594. Sentry.captureException('Detecting missing instrumentation failed');
  595. return;
  596. }
  597. child.parent?.children.splice(childIndex, 0, node);
  598. }
  599. previous = node;
  600. return;
  601. }
  602. previous = child;
  603. });
  604. return missingInstrumentationCount;
  605. }
  606. // We can just filter out the missing instrumentation
  607. // nodes as they never have any children that require remapping
  608. static RemoveMissingInstrumentationNodes(
  609. root: TraceTreeNode<TraceTree.NodeValue>
  610. ): number {
  611. let removeCount = 0;
  612. TraceTree.Filter(root, node => {
  613. if (isMissingInstrumentationNode(node)) {
  614. removeCount++;
  615. return false;
  616. }
  617. return true;
  618. });
  619. return removeCount;
  620. }
  621. static AutogroupDirectChildrenSpanNodes(
  622. root: TraceTreeNode<TraceTree.NodeValue>
  623. ): number {
  624. const queue = [root];
  625. let autogroupCount = 0;
  626. while (queue.length > 0) {
  627. const node = queue.pop()!;
  628. if (!isSpanNode(node) || node.children.length > 1) {
  629. for (const child of node.children) {
  630. queue.push(child);
  631. }
  632. continue;
  633. }
  634. const head = node;
  635. let tail = node;
  636. let groupMatchCount = 0;
  637. let errors: TraceErrorType[] = [];
  638. let performance_issues: TraceTree.TracePerformanceIssue[] = [];
  639. let start = head.space[0];
  640. let end = head.space[0] + head.space[1];
  641. while (
  642. tail &&
  643. tail.children.length === 1 &&
  644. isSpanNode(tail.children[0]) &&
  645. tail.children[0].value.op === head.value.op
  646. ) {
  647. start = Math.min(start, tail.space[0]);
  648. end = Math.max(end, tail.space[0] + tail.space[1]);
  649. errors = errors.concat(Array.from(tail.errors));
  650. performance_issues = performance_issues.concat(
  651. Array.from(tail.performance_issues)
  652. );
  653. groupMatchCount++;
  654. tail = tail.children[0];
  655. }
  656. if (groupMatchCount < 1) {
  657. for (const child of head.children) {
  658. queue.push(child);
  659. }
  660. continue;
  661. }
  662. const autoGroupedNode = new ParentAutogroupNode(
  663. node.parent,
  664. {
  665. ...head.value,
  666. autogrouped_by: {
  667. op: head.value && 'op' in head.value ? head.value.op ?? '' : '',
  668. },
  669. },
  670. {
  671. event_id: undefined,
  672. project_slug: undefined,
  673. },
  674. head,
  675. tail
  676. );
  677. autogroupCount++;
  678. if (!node.parent) {
  679. throw new Error('Parent node is missing, this should be unreachable code');
  680. }
  681. const children = isParentAutogroupedNode(node.parent)
  682. ? node.parent.tail.children
  683. : node.parent.children;
  684. const index = children.indexOf(node);
  685. if (index === -1) {
  686. throw new Error('Node is not a child of its parent');
  687. }
  688. children[index] = autoGroupedNode;
  689. autoGroupedNode.head.parent = autoGroupedNode;
  690. autoGroupedNode.groupCount = groupMatchCount + 1;
  691. // Checking the tail node for errors as it is not included in the grouping
  692. // while loop, but is hidden when the autogrouped node is collapsed
  693. errors = errors.concat(Array.from(tail.errors));
  694. performance_issues = performance_issues.concat(Array.from(tail.performance_issues));
  695. start = Math.min(start, tail.space[0]);
  696. end = Math.max(end, tail.space[0] + tail.space[1]);
  697. autoGroupedNode.space = [start, end - start];
  698. autoGroupedNode.errors = new Set(errors);
  699. autoGroupedNode.performance_issues = new Set(performance_issues);
  700. for (const c of tail.children) {
  701. c.parent = autoGroupedNode;
  702. queue.push(c);
  703. }
  704. }
  705. return autogroupCount;
  706. }
  707. static RemoveDirectChildrenAutogroupNodes(
  708. root: TraceTreeNode<TraceTree.NodeValue>
  709. ): number {
  710. let removeCount = 0;
  711. TraceTree.ForEachChild(root, node => {
  712. if (isParentAutogroupedNode(node)) {
  713. const index = node.parent?.children.indexOf(node) ?? -1;
  714. if (!node.parent || index === -1) {
  715. Sentry.captureException('Removing direct children autogroup nodes failed');
  716. return;
  717. }
  718. removeCount++;
  719. node.parent.children[index] = node.head;
  720. // Head of parent now points to the parent of autogrouped node
  721. node.head.parent = node.parent;
  722. // All children now point to the tail of the autogrouped node
  723. for (const child of node.tail.children) {
  724. child.parent = node.tail;
  725. }
  726. }
  727. });
  728. return removeCount;
  729. }
  730. static AutogroupSiblingSpanNodes(root: TraceTreeNode<TraceTree.NodeValue>): number {
  731. const queue = [root];
  732. let autogroupCount = 0;
  733. while (queue.length > 0) {
  734. const node = queue.pop()!;
  735. if (isParentAutogroupedNode(node)) {
  736. queue.push(node.head);
  737. } else {
  738. for (const child of node.children) {
  739. queue.push(child);
  740. }
  741. }
  742. if (isAutogroupedNode(node) || isMissingInstrumentationNode(node)) {
  743. continue;
  744. }
  745. if (node.children.length < 5) {
  746. continue;
  747. }
  748. let index = 0;
  749. let matchCount = 0;
  750. while (index < node.children.length) {
  751. // Skip until we find a span candidate
  752. if (!isSpanNode(node.children[index])) {
  753. index++;
  754. matchCount = 0;
  755. continue;
  756. }
  757. const current = node.children[index] as TraceTreeNode<TraceTree.Span>;
  758. const next = node.children[index + 1] as TraceTreeNode<TraceTree.Span>;
  759. if (
  760. next &&
  761. isSpanNode(next) &&
  762. next.children.length === 0 &&
  763. current.children.length === 0 &&
  764. next.value.op === current.value.op &&
  765. next.value.description === current.value.description
  766. ) {
  767. matchCount++;
  768. // If the next node is the last node in the list, we keep iterating
  769. if (index + 1 < node.children.length) {
  770. index++;
  771. continue;
  772. }
  773. }
  774. if (matchCount >= 4) {
  775. const autoGroupedNode = new SiblingAutogroupNode(
  776. node,
  777. {
  778. ...current.value,
  779. autogrouped_by: {
  780. op: current.value.op ?? '',
  781. description: current.value.description ?? '',
  782. },
  783. },
  784. {
  785. event_id: undefined,
  786. project_slug: undefined,
  787. }
  788. );
  789. autogroupCount++;
  790. autoGroupedNode.groupCount = matchCount + 1;
  791. const start = index - matchCount;
  792. let start_timestamp = Number.POSITIVE_INFINITY;
  793. let timestamp = Number.NEGATIVE_INFINITY;
  794. for (let j = start; j < start + matchCount + 1; j++) {
  795. const child = node.children[j];
  796. start_timestamp = Math.min(start_timestamp, node.children[j].space[0]);
  797. timestamp = Math.max(
  798. timestamp,
  799. node.children[j].space[0] + node.children[j].space[1]
  800. );
  801. if (node.children[j].hasErrors) {
  802. for (const error of child.errors) {
  803. autoGroupedNode.errors.add(error);
  804. }
  805. for (const performanceIssue of child.performance_issues) {
  806. autoGroupedNode.performance_issues.add(performanceIssue);
  807. }
  808. }
  809. autoGroupedNode.children.push(node.children[j]);
  810. node.children[j].parent = autoGroupedNode;
  811. }
  812. autoGroupedNode.space = [start_timestamp, timestamp - start_timestamp];
  813. node.children.splice(start, matchCount + 1, autoGroupedNode);
  814. index = start + 1;
  815. matchCount = 0;
  816. } else {
  817. index++;
  818. matchCount = 0;
  819. }
  820. }
  821. }
  822. return autogroupCount;
  823. }
  824. static RemoveSiblingAutogroupNodes(root: TraceTreeNode<TraceTree.NodeValue>): number {
  825. let removeCount = 0;
  826. TraceTree.ForEachChild(root, node => {
  827. if (isSiblingAutogroupedNode(node)) {
  828. removeCount++;
  829. const index = node.parent?.children.indexOf(node) ?? -1;
  830. if (!node.parent || index === -1) {
  831. Sentry.captureException('Removing sibling autogroup nodes failed');
  832. return;
  833. }
  834. node.parent.children.splice(index, 1, ...node.children);
  835. for (const child of node.children) {
  836. child.parent = node.parent;
  837. }
  838. }
  839. });
  840. return removeCount;
  841. }
  842. static DirectVisibleChildren(
  843. node: TraceTreeNode<TraceTree.NodeValue>
  844. ): TraceTreeNode<TraceTree.NodeValue>[] {
  845. if (isParentAutogroupedNode(node)) {
  846. if (node.expanded) {
  847. return [node.head];
  848. }
  849. return node.tail.children;
  850. }
  851. return node.children;
  852. }
  853. static VisibleChildren(
  854. root: TraceTreeNode<TraceTree.NodeValue>
  855. ): TraceTreeNode<TraceTree.NodeValue>[] {
  856. const queue: TraceTreeNode<TraceTree.NodeValue>[] = [];
  857. const visibleChildren: TraceTreeNode<TraceTree.NodeValue>[] = [];
  858. if (root.expanded || isParentAutogroupedNode(root)) {
  859. const children = TraceTree.DirectVisibleChildren(root);
  860. for (let i = children.length - 1; i >= 0; i--) {
  861. queue.push(children[i]);
  862. }
  863. }
  864. while (queue.length > 0) {
  865. const node = queue.pop()!;
  866. visibleChildren.push(node);
  867. // iterate in reverse to ensure nodes are processed in order
  868. if (node.expanded || isParentAutogroupedNode(node)) {
  869. const children = TraceTree.DirectVisibleChildren(node);
  870. for (let i = children.length - 1; i >= 0; i--) {
  871. queue.push(children[i]);
  872. }
  873. }
  874. }
  875. return visibleChildren;
  876. }
  877. static PathToNode(node: TraceTreeNode<TraceTree.NodeValue>): TraceTree.NodePath[] {
  878. // If the node is a transaction node, then it will not require any
  879. // fetching and we can link to it directly
  880. if (isTransactionNode(node)) {
  881. return [nodeToId(node)];
  882. }
  883. // Otherwise, we need to traverse up the tree until we find a transaction node.
  884. const nodes: TraceTreeNode<TraceTree.NodeValue>[] = [node];
  885. let current: TraceTreeNode<TraceTree.NodeValue> | null = node.parent;
  886. while (current && !isTransactionNode(current)) {
  887. current = current.parent;
  888. }
  889. if (current && isTransactionNode(current)) {
  890. nodes.push(current);
  891. }
  892. return nodes.map(nodeToId);
  893. }
  894. static ForEachChild(
  895. root: TraceTreeNode<TraceTree.NodeValue>,
  896. cb: (node: TraceTreeNode<TraceTree.NodeValue>) => void
  897. ): void {
  898. const queue: TraceTreeNode<TraceTree.NodeValue>[] = [];
  899. if (isParentAutogroupedNode(root)) {
  900. queue.push(root.head);
  901. } else {
  902. for (let i = root.children.length - 1; i >= 0; i--) {
  903. queue.push(root.children[i]);
  904. }
  905. }
  906. while (queue.length > 0) {
  907. const next = queue.pop()!;
  908. cb(next);
  909. // Parent autogroup nodes have a head and tail pointer instead of children
  910. if (isParentAutogroupedNode(next)) {
  911. queue.push(next.head);
  912. } else {
  913. for (let i = next.children.length - 1; i >= 0; i--) {
  914. queue.push(next.children[i]);
  915. }
  916. }
  917. }
  918. }
  919. // Removes node and all its children from the tree
  920. static Filter(
  921. node: TraceTreeNode<TraceTree.NodeValue>,
  922. predicate: (node: TraceTreeNode) => boolean
  923. ): TraceTreeNode<TraceTree.NodeValue> {
  924. const queue = [node];
  925. while (queue.length) {
  926. const next = queue.pop()!;
  927. next.children = next.children.filter(c => {
  928. if (predicate(c)) {
  929. queue.push(c);
  930. return true;
  931. }
  932. return false;
  933. });
  934. }
  935. return node;
  936. }
  937. static Find(
  938. root: TraceTreeNode<TraceTree.NodeValue>,
  939. predicate: (node: TraceTreeNode<TraceTree.NodeValue>) => boolean
  940. ): TraceTreeNode<TraceTree.NodeValue> | null {
  941. const queue = [root];
  942. while (queue.length > 0) {
  943. const next = queue.pop()!;
  944. if (predicate(next)) {
  945. return next;
  946. }
  947. if (isParentAutogroupedNode(next)) {
  948. queue.push(next.head);
  949. } else {
  950. for (const child of next.children) {
  951. queue.push(child);
  952. }
  953. }
  954. }
  955. return null;
  956. }
  957. static FindAll(
  958. root: TraceTreeNode<TraceTree.NodeValue>,
  959. predicate: (node: TraceTreeNode<TraceTree.NodeValue>) => boolean
  960. ): TraceTreeNode<TraceTree.NodeValue>[] {
  961. const queue = [root];
  962. const results: TraceTreeNode<TraceTree.NodeValue>[] = [];
  963. while (queue.length > 0) {
  964. const next = queue.pop()!;
  965. if (predicate(next)) {
  966. results.push(next);
  967. }
  968. if (isParentAutogroupedNode(next)) {
  969. queue.push(next.head);
  970. } else {
  971. for (let i = next.children.length - 1; i >= 0; i--) {
  972. queue.push(next.children[i]);
  973. }
  974. }
  975. }
  976. return results;
  977. }
  978. static FindByPath(
  979. tree: TraceTree,
  980. path: TraceTree.NodePath
  981. ): TraceTreeNode<TraceTree.NodeValue> | null {
  982. const [type, id, rest] = path.split('-');
  983. if (!type || !id || rest) {
  984. Sentry.withScope(scope => {
  985. scope.setFingerprint(['trace-view-path-error']);
  986. scope.captureMessage('Invalid path to trace tree node ');
  987. });
  988. return null;
  989. }
  990. if (type === 'trace' && id === 'root') {
  991. return tree.root.children[0];
  992. }
  993. return TraceTree.Find(tree.root, node => {
  994. if (type === 'txn' && isTransactionNode(node)) {
  995. // A transaction itself is a span and we are starting to treat it as such.
  996. // Hence we check for both event_id and span_id.
  997. return node.value.event_id === id || node.value.span_id === id;
  998. }
  999. if (type === 'span' && isSpanNode(node)) {
  1000. return node.value.span_id === id;
  1001. }
  1002. if (type === 'ag' && isAutogroupedNode(node)) {
  1003. if (isParentAutogroupedNode(node)) {
  1004. return (
  1005. node.value.span_id === id ||
  1006. node.head.value.span_id === id ||
  1007. node.tail.value.span_id === id
  1008. );
  1009. }
  1010. if (isSiblingAutogroupedNode(node)) {
  1011. const child = node.children[0];
  1012. if (isSpanNode(child)) {
  1013. return child.value.span_id === id;
  1014. }
  1015. }
  1016. }
  1017. if (type === 'ms' && isMissingInstrumentationNode(node)) {
  1018. return node.previous.value.span_id === id || node.next.value.span_id === id;
  1019. }
  1020. if (type === 'error' && isTraceErrorNode(node)) {
  1021. return node.value.event_id === id;
  1022. }
  1023. return false;
  1024. });
  1025. }
  1026. static FindByID(
  1027. root: TraceTreeNode<TraceTree.NodeValue>,
  1028. eventId: string
  1029. ): TraceTreeNode<TraceTree.NodeValue> | null {
  1030. return TraceTree.Find(root, n => {
  1031. if (isTransactionNode(n)) {
  1032. // A transaction itself is a span and we are starting to treat it as such.
  1033. // Hence we check for both event_id and span_id.
  1034. if (n.value.event_id === eventId || n.value.span_id === eventId) {
  1035. return true;
  1036. }
  1037. // If we dont have an exact match, then look for an event_id in the errors or performance issues
  1038. for (const e of n.errors) {
  1039. if (e.event_id === eventId) {
  1040. return true;
  1041. }
  1042. }
  1043. for (const p of n.performance_issues) {
  1044. if (p.event_id === eventId) {
  1045. return true;
  1046. }
  1047. }
  1048. }
  1049. if (isSpanNode(n)) {
  1050. if (n.value.span_id === eventId) {
  1051. return true;
  1052. }
  1053. // If we dont have an exact match, then look for an event_id in the errors or performance issues
  1054. for (const e of n.errors) {
  1055. if (e.event_id === eventId) {
  1056. return true;
  1057. }
  1058. }
  1059. for (const p of n.performance_issues) {
  1060. if (p.event_id === eventId) {
  1061. return true;
  1062. }
  1063. }
  1064. }
  1065. if (isTraceErrorNode(n)) {
  1066. return n.value.event_id === eventId;
  1067. }
  1068. if (isTraceNode(n)) {
  1069. return false;
  1070. }
  1071. if (isMissingInstrumentationNode(n)) {
  1072. return n.previous.value.span_id === eventId || n.next.value.span_id === eventId;
  1073. }
  1074. if (isParentAutogroupedNode(n)) {
  1075. return (
  1076. n.value.span_id === eventId ||
  1077. n.head.value.span_id === eventId ||
  1078. n.tail.value.span_id === eventId
  1079. );
  1080. }
  1081. if (isSiblingAutogroupedNode(n)) {
  1082. const child = n.children[0];
  1083. if (isSpanNode(child)) {
  1084. return child.value.span_id === eventId;
  1085. }
  1086. }
  1087. if (eventId === 'root' && isTraceNode(n)) {
  1088. return true;
  1089. }
  1090. return false;
  1091. });
  1092. }
  1093. static ParentTransaction(
  1094. node: TraceTreeNode<TraceTree.NodeValue>
  1095. ): TraceTreeNode<TraceTree.Transaction> | null {
  1096. let next: TraceTreeNode<TraceTree.NodeValue> | null = node.parent;
  1097. while (next) {
  1098. if (isTransactionNode(next)) {
  1099. return next;
  1100. }
  1101. next = next.parent;
  1102. }
  1103. return null;
  1104. }
  1105. expand(node: TraceTreeNode<TraceTree.NodeValue>, expanded: boolean): boolean {
  1106. // Trace root nodes are not expandable or collapsable
  1107. if (isTraceNode(node)) {
  1108. return false;
  1109. }
  1110. // Expanding is not allowed for zoomed in nodes
  1111. if (expanded === node.expanded || node.zoomedIn) {
  1112. return false;
  1113. }
  1114. if (isParentAutogroupedNode(node)) {
  1115. if (!expanded) {
  1116. const index = this.list.indexOf(node);
  1117. this.list.splice(index + 1, TraceTree.VisibleChildren(node).length);
  1118. // When we collapse the autogroup, we need to point the tail children
  1119. // back to the tail autogroup node.
  1120. for (const c of node.tail.children) {
  1121. c.parent = node;
  1122. }
  1123. this.list.splice(index + 1, 0, ...TraceTree.VisibleChildren(node.tail));
  1124. } else {
  1125. const index = this.list.indexOf(node);
  1126. this.list.splice(index + 1, TraceTree.VisibleChildren(node).length);
  1127. // When the node is collapsed, children point to the autogrouped node.
  1128. // We need to point them back to the tail node which is now visible
  1129. for (const c of node.tail.children) {
  1130. c.parent = node.tail;
  1131. }
  1132. this.list.splice(
  1133. index + 1,
  1134. 0,
  1135. node.head,
  1136. ...TraceTree.VisibleChildren(node.head)
  1137. );
  1138. }
  1139. TraceTree.invalidate(node, true);
  1140. node.expanded = expanded;
  1141. return true;
  1142. }
  1143. if (!expanded) {
  1144. const index = this.list.indexOf(node);
  1145. this.list.splice(index + 1, TraceTree.VisibleChildren(node).length);
  1146. node.expanded = expanded;
  1147. // When transaction nodes are collapsed, they still render child transactions
  1148. if (isTransactionNode(node)) {
  1149. this.list.splice(index + 1, 0, ...TraceTree.VisibleChildren(node));
  1150. }
  1151. } else {
  1152. node.expanded = expanded;
  1153. // Flip expanded so that we can collect visible children
  1154. const index = this.list.indexOf(node);
  1155. this.list.splice(index + 1, 0, ...TraceTree.VisibleChildren(node));
  1156. }
  1157. TraceTree.invalidate(node, true);
  1158. return true;
  1159. }
  1160. zoom(
  1161. node: TraceTreeNode<TraceTree.NodeValue>,
  1162. zoomedIn: boolean,
  1163. options: {
  1164. api: Client;
  1165. organization: Organization;
  1166. preferences: Pick<TracePreferencesState, 'autogroup' | 'missing_instrumentation'>;
  1167. }
  1168. ): Promise<Event | null> {
  1169. if (isTraceNode(node)) {
  1170. return Promise.resolve(null);
  1171. }
  1172. if (zoomedIn === node.zoomedIn || !node.canFetch) {
  1173. return Promise.resolve(null);
  1174. }
  1175. if (!zoomedIn) {
  1176. const index = this.list.indexOf(node);
  1177. // Remove currently visible children
  1178. this.list.splice(index + 1, TraceTree.VisibleChildren(node).length);
  1179. // Flip visibility
  1180. node.zoomedIn = zoomedIn;
  1181. // When transactions are zoomed out, they still render child transactions
  1182. if (isTransactionNode(node)) {
  1183. // Find all transactions that are children of the current transaction
  1184. // remove all non transaction events from current node and its children
  1185. // point transactions back to their parents
  1186. const transactions = TraceTree.FindAll(
  1187. node,
  1188. c => isTransactionNode(c) && c !== node
  1189. );
  1190. for (const t of transactions) {
  1191. // point transactions back to their parents
  1192. const parent = TraceTree.ParentTransaction(t);
  1193. // If they already have the correct parent, then we can skip this
  1194. if (t.parent === parent) {
  1195. continue;
  1196. }
  1197. if (!parent) {
  1198. Sentry.withScope(scope => {
  1199. scope.setFingerprint(['trace-view-transaction-parent']);
  1200. scope.captureMessage('Failed to find parent transaction when zooming out');
  1201. });
  1202. continue;
  1203. }
  1204. t.parent = parent;
  1205. parent.children.push(t);
  1206. }
  1207. node.children = node.children.filter(c => isTransactionNode(c));
  1208. node.children.sort(traceChronologicalSort);
  1209. this.list.splice(index + 1, 0, ...TraceTree.VisibleChildren(node));
  1210. }
  1211. TraceTree.invalidate(node, true);
  1212. return Promise.resolve(null);
  1213. }
  1214. const key =
  1215. options.organization.slug +
  1216. ':' +
  1217. node.metadata.project_slug! +
  1218. ':' +
  1219. node.metadata.event_id!;
  1220. const promise =
  1221. this._spanPromises.get(key) ??
  1222. fetchTransactionSpans(
  1223. options.api,
  1224. options.organization,
  1225. node.metadata.project_slug!,
  1226. node.metadata.event_id!
  1227. );
  1228. node.fetchStatus = 'loading';
  1229. promise
  1230. .then((data: EventTransaction) => {
  1231. // The user may have collapsed the node before the promise resolved. When that
  1232. // happens, dont update the tree with the resolved data. Alternatively, we could implement
  1233. // a cancellable promise and avoid this cumbersome heuristic.
  1234. // Remove existing entries from the list
  1235. const index = this.list.indexOf(node);
  1236. node.fetchStatus = 'resolved';
  1237. if (node.expanded && index !== -1) {
  1238. const childrenCount = TraceTree.VisibleChildren(node).length;
  1239. if (childrenCount > 0) {
  1240. this.list.splice(index + 1, childrenCount);
  1241. }
  1242. }
  1243. // API response is not sorted
  1244. const spans = data.entries.find(s => s.type === 'spans') ?? {data: []};
  1245. spans.data.sort((a, b) => a.start_timestamp - b.start_timestamp);
  1246. const [root, spanTreeSpaceBounds] = TraceTree.FromSpans(node, spans.data, data);
  1247. root.zoomedIn = true;
  1248. // Spans contain millisecond precision, which means that it is possible for the
  1249. // children spans of a transaction to extend beyond the start and end of the transaction
  1250. // through ns precision. To account for this, we need to adjust the space of the transaction node and the space
  1251. // of our trace so that all of the span children are visible and can be rendered inside the view
  1252. const previousStart = this.root.space[0];
  1253. const previousDuration = this.root.space[1];
  1254. const newStart = spanTreeSpaceBounds[0];
  1255. const newEnd = spanTreeSpaceBounds[0] + spanTreeSpaceBounds[1];
  1256. // Extend the start of the trace to include the new min start
  1257. if (newStart <= this.root.space[0]) {
  1258. this.root.space[0] = newStart;
  1259. }
  1260. // Extend the end of the trace to include the new max end
  1261. if (newEnd > this.root.space[0] + this.root.space[1]) {
  1262. this.root.space[1] = newEnd - this.root.space[0];
  1263. }
  1264. if (
  1265. previousStart !== this.root.space[0] ||
  1266. previousDuration !== this.root.space[1]
  1267. ) {
  1268. this.dispatch('trace timeline change', this.root.space);
  1269. }
  1270. if (options.preferences.missing_instrumentation) {
  1271. TraceTree.DetectMissingInstrumentation(root);
  1272. }
  1273. if (options.preferences.autogroup.sibling) {
  1274. TraceTree.AutogroupSiblingSpanNodes(root);
  1275. }
  1276. if (options.preferences.autogroup.parent) {
  1277. TraceTree.AutogroupDirectChildrenSpanNodes(root);
  1278. }
  1279. if (index !== -1) {
  1280. this.list.splice(index + 1, 0, ...TraceTree.VisibleChildren(node));
  1281. }
  1282. return data;
  1283. })
  1284. .catch(_e => {
  1285. node.fetchStatus = 'error';
  1286. });
  1287. this._spanPromises.set(key, promise);
  1288. return promise;
  1289. }
  1290. static EnforceVisibility(
  1291. tree: TraceTree,
  1292. node: TraceTreeNode<TraceTree.NodeValue>
  1293. ): number {
  1294. let index = tree.list.indexOf(node);
  1295. if (node && index === -1) {
  1296. let parent_node = node.parent;
  1297. while (parent_node) {
  1298. // Transactions break autogrouping chains, so we can stop here
  1299. tree.expand(parent_node, true);
  1300. // This is very wasteful as it performs O(n^2) search each time we expand a node...
  1301. // In most cases though, we should be operating on a tree with sub 10k elements and hopefully
  1302. // a low autogrouped node count.
  1303. index = node ? tree.list.indexOf(node) : -1;
  1304. if (index !== -1) {
  1305. break;
  1306. }
  1307. parent_node = parent_node.parent;
  1308. }
  1309. }
  1310. return index;
  1311. }
  1312. static ExpandToEventID(
  1313. tree: TraceTree,
  1314. eventId: string,
  1315. options: {
  1316. api: Client;
  1317. organization: Organization;
  1318. preferences: Pick<TracePreferencesState, 'autogroup' | 'missing_instrumentation'>;
  1319. }
  1320. ): Promise<void> {
  1321. const node = TraceTree.FindByID(tree.root, eventId);
  1322. if (!node) {
  1323. return Promise.resolve();
  1324. }
  1325. return TraceTree.ExpandToPath(tree, TraceTree.PathToNode(node), options);
  1326. }
  1327. static ExpandToPath(
  1328. tree: TraceTree,
  1329. scrollQueue: TraceTree.NodePath[],
  1330. options: {
  1331. api: Client;
  1332. organization: Organization;
  1333. preferences: Pick<TracePreferencesState, 'autogroup' | 'missing_instrumentation'>;
  1334. }
  1335. ): Promise<void> {
  1336. const transactionIds = new Set(
  1337. scrollQueue.filter(s => s.startsWith('txn-')).map(s => s.replace('txn-', ''))
  1338. );
  1339. // If we are just linking to a transaction, then we dont need to fetch its spans
  1340. if (transactionIds.size === 1 && scrollQueue.length === 1) {
  1341. return Promise.resolve();
  1342. }
  1343. const transactionNodes = TraceTree.FindAll(
  1344. tree.root,
  1345. node =>
  1346. isTransactionNode(node) &&
  1347. (transactionIds.has(node.value.span_id) ||
  1348. transactionIds.has(node.value.event_id))
  1349. );
  1350. const promises = transactionNodes.map(node => tree.zoom(node, true, options));
  1351. return Promise.all(promises)
  1352. .then(_resp => {
  1353. // Ignore response
  1354. })
  1355. .catch(e => {
  1356. Sentry.withScope(scope => {
  1357. scope.setFingerprint(['trace-view-expand-to-path-error']);
  1358. scope.captureMessage('Failed to expand to path');
  1359. scope.captureException(e);
  1360. });
  1361. });
  1362. }
  1363. // Only supports parent/child swaps (the only ones we need)
  1364. static Swap({
  1365. parent,
  1366. child,
  1367. reason,
  1368. }: {
  1369. child: TraceTreeNode<TraceTree.NodeValue>;
  1370. parent: TraceTreeNode<TraceTree.NodeValue>;
  1371. reason: TraceTreeNode['reparent_reason'];
  1372. }) {
  1373. const commonRoot = parent.parent!;
  1374. const parentIndex = commonRoot.children.indexOf(parent);
  1375. if (!commonRoot || parentIndex === -1) {
  1376. throw new Error('Cannot find common parent');
  1377. }
  1378. TraceTree.Filter(commonRoot, c => c !== child);
  1379. parent.parent = null;
  1380. child.parent = null;
  1381. // Insert child into parent
  1382. commonRoot.children[parentIndex] = child;
  1383. child.children.push(parent);
  1384. child.parent = commonRoot;
  1385. parent.parent = child;
  1386. child.reparent_reason = reason;
  1387. parent.reparent_reason = reason;
  1388. }
  1389. static IsLastChild(n: TraceTreeNode<TraceTree.NodeValue>): boolean {
  1390. if (!n.parent) {
  1391. return false;
  1392. }
  1393. if (isParentAutogroupedNode(n.parent)) {
  1394. if (n.parent.expanded) {
  1395. // The autogrouped
  1396. return true;
  1397. }
  1398. return n.parent.tail.children[n.parent.tail.children.length - 1] === n;
  1399. }
  1400. return n.parent.children[n.parent.children.length - 1] === n;
  1401. }
  1402. static HasVisibleChildren(node: TraceTreeNode<TraceTree.NodeValue>): boolean {
  1403. if (isParentAutogroupedNode(node)) {
  1404. if (node.expanded) {
  1405. return node.head.children.length > 0;
  1406. }
  1407. return node.tail.children.length > 0;
  1408. }
  1409. if (node.expanded) {
  1410. return node.children.length > 0;
  1411. }
  1412. return false;
  1413. }
  1414. /**
  1415. * Return a lazily calculated depth of the node in the tree.
  1416. * Root node has a value of -1 as it is abstract.
  1417. */
  1418. static Depth(node: TraceTreeNode<any>): number {
  1419. if (node.depth !== undefined) {
  1420. return node.depth;
  1421. }
  1422. let depth = -2;
  1423. let start: TraceTreeNode<any> | null = node;
  1424. while (start) {
  1425. depth++;
  1426. start = start.parent;
  1427. }
  1428. node.depth = depth;
  1429. return depth;
  1430. }
  1431. static ConnectorsTo(node: TraceTreeNode<TraceTree.NodeValue>): number[] {
  1432. if (node.connectors !== undefined) {
  1433. return node.connectors;
  1434. }
  1435. const connectors: number[] = [];
  1436. let start: TraceTreeNode<TraceTree.NodeValue> | null = node.parent;
  1437. if (start && isTraceNode(start) && !TraceTree.IsLastChild(node)) {
  1438. node.connectors = [-TraceTree.Depth(node)];
  1439. return node.connectors;
  1440. }
  1441. if (!TraceTree.IsLastChild(node)) {
  1442. connectors.push(TraceTree.Depth(node));
  1443. }
  1444. while (start) {
  1445. if (!start.value || !start.parent) {
  1446. break;
  1447. }
  1448. if (TraceTree.IsLastChild(start)) {
  1449. start = start.parent;
  1450. continue;
  1451. }
  1452. connectors.push(
  1453. isTraceNode(start.parent) ? -TraceTree.Depth(start) : TraceTree.Depth(start)
  1454. );
  1455. start = start.parent;
  1456. }
  1457. node.connectors = connectors;
  1458. return connectors;
  1459. }
  1460. toList(): TraceTreeNode<TraceTree.NodeValue>[] {
  1461. this.list = TraceTree.VisibleChildren(this.root);
  1462. return this.list;
  1463. }
  1464. rebuild() {
  1465. TraceTree.invalidate(this.root, true);
  1466. this.list = this.toList();
  1467. return this;
  1468. }
  1469. build() {
  1470. this.list = this.toList();
  1471. return this;
  1472. }
  1473. get shape(): TraceShape {
  1474. const trace = this.root.children[0];
  1475. if (!trace) {
  1476. return TraceShape.EMPTY_TRACE;
  1477. }
  1478. if (!isTraceNode(trace)) {
  1479. throw new TypeError('Not trace node');
  1480. }
  1481. const traceStats = trace.value.transactions?.reduce<{
  1482. javascriptRootTransactions: TraceTree.Transaction[];
  1483. orphans: number;
  1484. roots: number;
  1485. }>(
  1486. (stats, transaction) => {
  1487. if (isRootTransaction(transaction)) {
  1488. stats.roots++;
  1489. if (isJavascriptSDKTransaction(transaction)) {
  1490. stats.javascriptRootTransactions.push(transaction);
  1491. }
  1492. } else {
  1493. stats.orphans++;
  1494. }
  1495. return stats;
  1496. },
  1497. {roots: 0, orphans: 0, javascriptRootTransactions: []}
  1498. ) ?? {roots: 0, orphans: 0, javascriptRootTransactions: []};
  1499. if (traceStats.roots === 0) {
  1500. if (traceStats.orphans > 0) {
  1501. return TraceShape.NO_ROOT;
  1502. }
  1503. if ((trace.value.orphan_errors?.length ?? 0) > 0) {
  1504. return TraceShape.ONLY_ERRORS;
  1505. }
  1506. return TraceShape.EMPTY_TRACE;
  1507. }
  1508. if (traceStats.roots === 1) {
  1509. if (traceStats.orphans > 0) {
  1510. return TraceShape.BROKEN_SUBTRACES;
  1511. }
  1512. return TraceShape.ONE_ROOT;
  1513. }
  1514. if (traceStats.roots > 1) {
  1515. if (traceStats.javascriptRootTransactions.length > 0) {
  1516. return TraceShape.BROWSER_MULTIPLE_ROOTS;
  1517. }
  1518. return TraceShape.MULTIPLE_ROOTS;
  1519. }
  1520. throw new Error('Unknown trace type');
  1521. }
  1522. fetchAdditionalTraces(options: {
  1523. api: Client;
  1524. filters: any;
  1525. meta: TraceMetaQueryResults | null;
  1526. organization: Organization;
  1527. replayTraces: ReplayTrace[];
  1528. rerender: () => void;
  1529. urlParams: Location['query'];
  1530. }): () => void {
  1531. let cancelled = false;
  1532. const {organization, api, urlParams, filters, rerender, replayTraces} = options;
  1533. const clonedTraceIds = [...replayTraces];
  1534. const root = this.root.children[0];
  1535. root.fetchStatus = 'loading';
  1536. rerender();
  1537. (async () => {
  1538. while (clonedTraceIds.length > 0) {
  1539. const batch = clonedTraceIds.splice(0, 3);
  1540. const results = await Promise.allSettled(
  1541. batch.map(batchTraceData => {
  1542. return fetchTrace(api, {
  1543. orgSlug: organization.slug,
  1544. query: qs.stringify(
  1545. getTraceQueryParams(urlParams, filters.selection, {
  1546. timestamp: batchTraceData.timestamp,
  1547. })
  1548. ),
  1549. traceId: batchTraceData.traceSlug,
  1550. });
  1551. })
  1552. );
  1553. if (cancelled) {
  1554. return;
  1555. }
  1556. const updatedData = results.reduce(
  1557. (acc, result) => {
  1558. // Ignoring the error case for now
  1559. if (result.status === 'fulfilled') {
  1560. const {transactions, orphan_errors} = result.value;
  1561. acc.transactions.push(...transactions);
  1562. acc.orphan_errors.push(...orphan_errors);
  1563. }
  1564. return acc;
  1565. },
  1566. {
  1567. transactions: [],
  1568. orphan_errors: [],
  1569. } as TraceSplitResults<TraceTree.Transaction>
  1570. );
  1571. this.appendTree(
  1572. TraceTree.FromTrace(updatedData, {
  1573. meta: options.meta?.data,
  1574. replay: null,
  1575. })
  1576. );
  1577. rerender();
  1578. }
  1579. root.fetchStatus = 'idle';
  1580. rerender();
  1581. })();
  1582. return () => {
  1583. root.fetchStatus = 'idle';
  1584. cancelled = true;
  1585. };
  1586. }
  1587. /**
  1588. * Prints the tree in a human readable format, useful for debugging and testing
  1589. */
  1590. print() {
  1591. // eslint-disable-next-line no-console
  1592. console.log(this.serialize());
  1593. }
  1594. serialize() {
  1595. return (
  1596. '\n' +
  1597. this.list
  1598. .map(t => printTraceTreeNode(t, 0))
  1599. .filter(Boolean)
  1600. .join('\n') +
  1601. '\n'
  1602. );
  1603. }
  1604. }
  1605. // Generates a ID of the tree node based on its type
  1606. function nodeToId(n: TraceTreeNode<TraceTree.NodeValue>): TraceTree.NodePath {
  1607. if (isAutogroupedNode(n)) {
  1608. if (isParentAutogroupedNode(n)) {
  1609. return `ag-${n.head.value.span_id}`;
  1610. }
  1611. if (isSiblingAutogroupedNode(n)) {
  1612. const child = n.children[0];
  1613. if (isSpanNode(child)) {
  1614. return `ag-${child.value.span_id}`;
  1615. }
  1616. }
  1617. }
  1618. if (isTransactionNode(n)) {
  1619. return `txn-${n.value.event_id}`;
  1620. }
  1621. if (isSpanNode(n)) {
  1622. return `span-${n.value.span_id}`;
  1623. }
  1624. if (isTraceNode(n)) {
  1625. return `trace-root`;
  1626. }
  1627. if (isTraceErrorNode(n)) {
  1628. return `error-${n.value.event_id}`;
  1629. }
  1630. if (isRootNode(n)) {
  1631. throw new Error('A path to root node does not exist as the node is virtual');
  1632. }
  1633. if (isMissingInstrumentationNode(n)) {
  1634. return `ms-${n.previous.value.span_id}`;
  1635. }
  1636. throw new Error('Not implemented');
  1637. }
  1638. function printTraceTreeNode(
  1639. t: TraceTreeNode<TraceTree.NodeValue>,
  1640. offset: number
  1641. ): string {
  1642. // +1 because we may be printing from the root which is -1 indexed
  1643. const padding = ' '.repeat(TraceTree.Depth(t) + offset);
  1644. if (isAutogroupedNode(t)) {
  1645. if (isParentAutogroupedNode(t)) {
  1646. return padding + `parent autogroup (${t.head.value.op}: ${t.groupCount})`;
  1647. }
  1648. if (isSiblingAutogroupedNode(t)) {
  1649. return (
  1650. padding +
  1651. `sibling autogroup (${(t.children[0] as TraceTreeNode<TraceTree.Span>)?.value?.op}: ${t.groupCount})`
  1652. );
  1653. }
  1654. return padding + 'autogroup';
  1655. }
  1656. if (isSpanNode(t)) {
  1657. return (
  1658. padding +
  1659. (t.value.op || 'unknown span') +
  1660. ' - ' +
  1661. (t.value.description || 'unknown description')
  1662. );
  1663. }
  1664. if (isTransactionNode(t)) {
  1665. return (
  1666. padding +
  1667. (t.value.transaction || 'unknown transaction') +
  1668. ' - ' +
  1669. (t.value['transaction.op'] ?? 'unknown op')
  1670. );
  1671. }
  1672. if (isMissingInstrumentationNode(t)) {
  1673. return padding + 'missing_instrumentation';
  1674. }
  1675. if (isRootNode(t)) {
  1676. return padding + 'virtual root';
  1677. }
  1678. if (isTraceNode(t)) {
  1679. return padding + 'trace root';
  1680. }
  1681. if (isTraceErrorNode(t)) {
  1682. return padding + (t.value.event_id || t.value.level) || 'unknown trace error';
  1683. }
  1684. if (isCollapsedNode(t)) {
  1685. return padding + 'collapsed';
  1686. }
  1687. return 'unknown node';
  1688. }
  1689. // Double queue iterator to merge transactions and errors into a single list ordered by timestamp
  1690. // without having to reallocate the potentially large list of transactions and errors.
  1691. function traceQueueIterator(
  1692. trace: TraceTree.Trace,
  1693. root: TraceTreeNode<TraceTree.NodeValue>,
  1694. visitor: (
  1695. parent: TraceTreeNode<TraceTree.NodeValue>,
  1696. value: TraceTree.Transaction | TraceTree.TraceError
  1697. ) => void
  1698. ) {
  1699. let tIdx = 0;
  1700. let oIdx = 0;
  1701. const tLen = trace.transactions.length;
  1702. const oLen = trace.orphan_errors.length;
  1703. const transactions = [...trace.transactions].sort(
  1704. (a, b) => a.start_timestamp - b.start_timestamp
  1705. );
  1706. const orphan_errors = [...trace.orphan_errors].sort(
  1707. (a, b) => (a?.timestamp ?? 0) - (b?.timestamp ?? 0)
  1708. );
  1709. // Items in each queue are sorted by timestamp, so we just take
  1710. // from the queue with the earliest timestamp which means the final list will be ordered.
  1711. while (tIdx < tLen || oIdx < oLen) {
  1712. const transaction = transactions[tIdx];
  1713. const orphan = orphan_errors[oIdx];
  1714. if (transaction && orphan) {
  1715. if (
  1716. typeof orphan.timestamp === 'number' &&
  1717. transaction.start_timestamp <= orphan.timestamp
  1718. ) {
  1719. visitor(root, transaction);
  1720. tIdx++;
  1721. } else {
  1722. visitor(root, orphan);
  1723. oIdx++;
  1724. }
  1725. } else if (transaction) {
  1726. visitor(root, transaction);
  1727. tIdx++;
  1728. } else if (orphan) {
  1729. visitor(root, orphan);
  1730. oIdx++;
  1731. }
  1732. }
  1733. }
  1734. function traceChronologicalSort(
  1735. a: TraceTreeNode<TraceTree.NodeValue>,
  1736. b: TraceTreeNode<TraceTree.NodeValue>
  1737. ) {
  1738. return a.space[0] - b.space[0];
  1739. }
  1740. function getRelatedSpanErrorsFromTransaction(
  1741. span: TraceTree.Span,
  1742. node: TraceTreeNode<TraceTree.NodeValue>
  1743. ): TraceTree.TraceError[] {
  1744. if (!isTransactionNode(node) || !node.value?.errors?.length) {
  1745. return [];
  1746. }
  1747. const errors: TraceTree.TraceError[] = [];
  1748. for (const error of node.value.errors) {
  1749. if (error.span === span.span_id) {
  1750. errors.push(error);
  1751. }
  1752. }
  1753. return errors;
  1754. }
  1755. // Returns a list of performance errors related to the txn with ids matching the span id
  1756. function getRelatedPerformanceIssuesFromTransaction(
  1757. span: TraceTree.Span,
  1758. node: TraceTreeNode<TraceTree.NodeValue>
  1759. ): TraceTree.TracePerformanceIssue[] {
  1760. if (!isTransactionNode(node) || !node.value?.performance_issues?.length) {
  1761. return [];
  1762. }
  1763. const performanceIssues: TraceTree.TracePerformanceIssue[] = [];
  1764. for (const perfIssue of node.value.performance_issues) {
  1765. for (const s of perfIssue.span) {
  1766. if (s === span.span_id) {
  1767. performanceIssues.push(perfIssue);
  1768. }
  1769. }
  1770. for (const suspect of perfIssue.suspect_spans) {
  1771. if (suspect === span.span_id) {
  1772. performanceIssues.push(perfIssue);
  1773. }
  1774. }
  1775. }
  1776. return performanceIssues;
  1777. }