traceTree.tsx 62 KB

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