traceTree.tsx 62 KB

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