traceTree.tsx 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852
  1. import type {Theme} from '@emotion/react';
  2. import type {Client} from 'sentry/api';
  3. import type {RawSpanType} from 'sentry/components/events/interfaces/spans/types';
  4. import {pickBarColor} from 'sentry/components/performance/waterfall/utils';
  5. import type {Organization} from 'sentry/types';
  6. import type {Event, EventTransaction, Measurement} from 'sentry/types/event';
  7. import {MobileVital, WebVital} from 'sentry/utils/fields';
  8. import type {
  9. TraceError as TraceErrorType,
  10. TraceFullDetailed,
  11. TracePerformanceIssue,
  12. TraceSplitResults,
  13. } from 'sentry/utils/performance/quickTrace/types';
  14. import {
  15. isTraceError,
  16. isTraceTransaction,
  17. } from 'sentry/utils/performance/quickTrace/utils';
  18. import {TraceType} from '../traceDetails/newTraceDetailsContent';
  19. import {isRootTransaction} from '../traceDetails/utils';
  20. import {
  21. isAutogroupedNode,
  22. isMissingInstrumentationNode,
  23. isParentAutogroupedNode,
  24. isRootNode,
  25. isSiblingAutogroupedNode,
  26. isSpanNode,
  27. isTraceErrorNode,
  28. isTraceNode,
  29. isTransactionNode,
  30. shouldAddMissingInstrumentationSpan,
  31. } from './guards';
  32. /**
  33. *
  34. * This file implements the tree data structure that is used to represent a trace. We do
  35. * this both for performance reasons as well as flexibility. The requirement for a tree
  36. * is to support incremental patching and updates. This is important because we want to
  37. * be able to fetch more data as the user interacts with the tree, and we want to be able
  38. * efficiently update the tree as we receive more data.
  39. *
  40. * The trace is represented as a tree with different node value types (transaction or span)
  41. * Each tree node contains a reference to its parent and a list of references to its children,
  42. * as well as a reference to the value that the node holds. Each node also contains
  43. * some meta data and state about the node, such as if it is expanded or zoomed in. The benefit
  44. * of abstracting parts of the UI state is that the tree will persist user actions such as expanding
  45. * or collapsing nodes which would have otherwise been lost when individual nodes are remounted in the tree.
  46. *
  47. * Each tree holds a list reference, which is a live reference to a flattened representation
  48. * 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
  49. * reasons as we want to support mutations on traces with ~100k+ nodes), callers need to manage reactivity themselves.
  50. *
  51. * An alternative, but not recommended approach is to call build() on the tree after each mutation,
  52. * which will iterate over all of the children and build a fresh list reference.
  53. *
  54. * In most cases, the initial tree is a list of transactions containing other transactions. Each transaction can
  55. * then be expanded into a list of spans which can also in some cases be expanded.
  56. *
  57. * - trace - trace
  58. * |- parent transaction --> when expanding |- parent transaction
  59. * |- child transaction |- span
  60. * |- span this used to be a transaction,
  61. * |- child transaction span <- but is now be a list of spans
  62. * |- span belonging to the transaction
  63. * this results in child txns to be lost,
  64. * which is a confusing user experience
  65. *
  66. * The tree supports autogrouping of spans vertically or as siblings. When that happens, a autogrouped node of either a vertical or
  67. * sibling type is inserted as an intermediary node. In the vertical case, the autogrouped node
  68. * holds the reference to the head and tail of the autogrouped sequence. In the sibling case, the autogrouped node
  69. * holds a reference to the children that are part of the autogrouped sequence. When expanding and collapsing these nodes,
  70. * the tree perform a reference swap to either point to the head (when expanded) or tail (when collapsed) of the autogrouped sequence.
  71. *
  72. * In vertical grouping case, the following happens:
  73. *
  74. * - root - root
  75. * - trace - trace
  76. * |- transaction |- transaction
  77. * |- span 1 <-| these become autogrouped |- autogrouped (head=span1, tail=span3, children points to children of tail)
  78. * |- span 2 |- as they are inserted into |- other span (parent points to autogrouped node)
  79. * |- span 3 <-| the tree.
  80. * |- other span
  81. *
  82. * When the autogrouped node is expanded the UI needs to show the entire collapsed chain, so we swap the tail children to point
  83. * back to the tail, and have autogrouped node point to it's head as the children.
  84. *
  85. * - root - root
  86. * - trace - trace
  87. * |- transaction |- transaction
  88. * |- autogrouped (head=span1, tail=span3) <- when expanding |- autogrouped (head=span1, tail=span3, children points to head)
  89. * | other span (paren points to autogrouped) |- span 1 (head)
  90. * |- span 2
  91. * |- span 3 (tail)
  92. * |- other span (children of tail, parent points to tail)
  93. *
  94. * Notes and improvements:
  95. * - the notion of expanded and zoomed is confusing, they stand for the same idea from a UI pov
  96. * - there is an annoying thing wrt span and transaction nodes where we either store data on _children or _spanChildren
  97. * this is because we want to be able to store both transaction and span nodes in the same tree, but it makes for an
  98. * annoying API. A better design would have been to create an invisible meta node that just points to the correct children
  99. * - instead of storing span children separately, we should have meta tree nodes that handle pointing to the correct children
  100. */
  101. export declare namespace TraceTree {
  102. type Transaction = TraceFullDetailed;
  103. interface Span extends RawSpanType {
  104. childTransaction: Transaction | undefined;
  105. event: EventTransaction;
  106. }
  107. type Trace = TraceSplitResults<Transaction>;
  108. type TraceError = TraceErrorType;
  109. type Profile = {profile_id: string; space: [number, number]};
  110. interface MissingInstrumentationSpan {
  111. start_timestamp: number;
  112. timestamp: number;
  113. type: 'missing_instrumentation';
  114. }
  115. interface SiblingAutogroup extends RawSpanType {
  116. autogrouped_by: {
  117. description: string;
  118. op: string;
  119. };
  120. }
  121. interface ChildrenAutogroup extends RawSpanType {
  122. autogrouped_by: {
  123. op: string;
  124. };
  125. }
  126. type NodeValue =
  127. | Trace
  128. | Transaction
  129. | TraceError
  130. | Span
  131. | MissingInstrumentationSpan
  132. | SiblingAutogroup
  133. | ChildrenAutogroup
  134. | null;
  135. type NodePath = `${'txn' | 'span' | 'ag' | 'trace' | 'ms' | 'error'}:${string}`;
  136. type Metadata = {
  137. event_id: string | undefined;
  138. project_slug: string | undefined;
  139. };
  140. type Indicator = {
  141. duration: number;
  142. label: string;
  143. measurement: Measurement;
  144. poor: boolean;
  145. start: number;
  146. type: 'cls' | 'fcp' | 'fp' | 'lcp' | 'ttfb';
  147. };
  148. }
  149. function cacheKey(organization: Organization, project_slug: string, event_id: string) {
  150. return organization.slug + ':' + project_slug + ':' + event_id;
  151. }
  152. function fetchTransactionSpans(
  153. api: Client,
  154. organization: Organization,
  155. project_slug: string,
  156. event_id: string
  157. ): Promise<EventTransaction> {
  158. return api.requestPromise(
  159. `/organizations/${organization.slug}/events/${project_slug}:${event_id}/`
  160. );
  161. }
  162. function measurementToTimestamp(
  163. start_timestamp: number,
  164. measurement: number,
  165. unit: string
  166. ) {
  167. if (unit === 'second') {
  168. return start_timestamp + measurement;
  169. }
  170. if (unit === 'millisecond') {
  171. return start_timestamp + measurement / 1e3;
  172. }
  173. if (unit === 'nanosecond') {
  174. return start_timestamp + measurement / 1e9;
  175. }
  176. throw new TypeError(`Unsupported measurement unit', ${unit}`);
  177. }
  178. function maybeInsertMissingInstrumentationSpan(
  179. parent: TraceTreeNode<TraceTree.NodeValue>,
  180. node: TraceTreeNode<TraceTree.Span>
  181. ) {
  182. const previousSpan = parent.spanChildren[parent.spanChildren.length - 1];
  183. if (!previousSpan || !isSpanNode(previousSpan)) {
  184. return;
  185. }
  186. if (node.value.start_timestamp - previousSpan.value.timestamp < 0.1) {
  187. return;
  188. }
  189. const missingInstrumentationSpan = new MissingInstrumentationNode(
  190. parent,
  191. {
  192. type: 'missing_instrumentation',
  193. start_timestamp: previousSpan.value.timestamp,
  194. timestamp: node.value.start_timestamp,
  195. },
  196. {
  197. event_id: undefined,
  198. project_slug: undefined,
  199. },
  200. previousSpan,
  201. node
  202. );
  203. parent.spanChildren.push(missingInstrumentationSpan);
  204. }
  205. export function makeTraceNodeBarColor(
  206. theme: Theme,
  207. node: TraceTreeNode<TraceTree.NodeValue>
  208. ): string {
  209. if (isTransactionNode(node)) {
  210. return pickBarColor(node.value['transaction.op']);
  211. }
  212. if (isSpanNode(node)) {
  213. return pickBarColor(node.value.op);
  214. }
  215. if (isAutogroupedNode(node)) {
  216. return theme.blue300;
  217. }
  218. if (isMissingInstrumentationNode(node)) {
  219. return theme.gray300;
  220. }
  221. if (isTraceErrorNode(node)) {
  222. return theme.red300;
  223. }
  224. return pickBarColor('default');
  225. }
  226. function shouldCollapseNodeByDefault(node: TraceTreeNode<TraceTree.NodeValue>) {
  227. if (isSpanNode(node)) {
  228. // Android creates TCP connection spans which are noisy and not useful in most cases
  229. if (node.value.op === 'http.client' && node.value.origin === 'auto.http.okhttp') {
  230. return true;
  231. }
  232. }
  233. return false;
  234. }
  235. // cls is not included as it is a cumulative layout shift and not a single point in time
  236. const RENDERABLE_MEASUREMENTS = [
  237. WebVital.TTFB,
  238. WebVital.FP,
  239. WebVital.FCP,
  240. WebVital.LCP,
  241. MobileVital.TIME_TO_FULL_DISPLAY,
  242. MobileVital.TIME_TO_INITIAL_DISPLAY,
  243. ].map(n => n.replace('measurements.', ''));
  244. const MEASUREMENT_ACRONYM_MAPPING = {
  245. [MobileVital.TIME_TO_FULL_DISPLAY.replace('measurements.', '')]: 'TTFD',
  246. [MobileVital.TIME_TO_INITIAL_DISPLAY.replace('measurements.', '')]: 'TTID',
  247. };
  248. const MEASUREMENT_THRESHOLDS = {
  249. [WebVital.TTFB.replace('measurements.', '')]: 600,
  250. [WebVital.FP.replace('measurements.', '')]: 3000,
  251. [WebVital.FCP.replace('measurements.', '')]: 3000,
  252. [WebVital.LCP.replace('measurements.', '')]: 4000,
  253. [MobileVital.TIME_TO_INITIAL_DISPLAY.replace('measurements.', '')]: 2000,
  254. };
  255. export class TraceTree {
  256. type: 'loading' | 'empty' | 'error' | 'trace' = 'trace';
  257. root: TraceTreeNode<null> = TraceTreeNode.Root();
  258. indicators: TraceTree.Indicator[] = [];
  259. eventsCount: number = 0;
  260. private _spanPromises: Map<string, Promise<Event>> = new Map();
  261. private _list: TraceTreeNode<TraceTree.NodeValue>[] = [];
  262. static Empty() {
  263. const tree = new TraceTree().build();
  264. tree.type = 'empty';
  265. return tree;
  266. }
  267. static Loading(metadata: TraceTree.Metadata, tree?: TraceTree | null): TraceTree {
  268. const t = tree ? TraceTree.FromTree(tree) : makeExampleTrace(metadata);
  269. t.type = 'loading';
  270. return t;
  271. }
  272. static Error(metadata: TraceTree.Metadata, tree?: TraceTree | null): TraceTree {
  273. const t = tree ? TraceTree.FromTree(tree) : makeExampleTrace(metadata);
  274. t.type = 'error';
  275. return t;
  276. }
  277. static FromTree(tree: TraceTree): TraceTree {
  278. const newTree = new TraceTree();
  279. newTree.root = tree.root.cloneDeep() as TraceTreeNode<null>;
  280. newTree.indicators = tree.indicators;
  281. newTree._list = tree._list;
  282. return newTree;
  283. }
  284. static FromTrace(trace: TraceTree.Trace): TraceTree {
  285. const tree = new TraceTree();
  286. let traceStart = Number.POSITIVE_INFINITY;
  287. let traceEnd = Number.NEGATIVE_INFINITY;
  288. const traceNode = new TraceTreeNode(tree.root, trace, {
  289. event_id: undefined,
  290. project_slug: undefined,
  291. });
  292. // Trace is always expanded by default
  293. tree.root.children.push(traceNode);
  294. function visit(
  295. parent: TraceTreeNode<TraceTree.NodeValue | null>,
  296. value: TraceFullDetailed | TraceTree.TraceError
  297. ) {
  298. const node = new TraceTreeNode(parent, value, {
  299. project_slug: value && 'project_slug' in value ? value.project_slug : undefined,
  300. event_id: value && 'event_id' in value ? value.event_id : undefined,
  301. });
  302. node.canFetch = true;
  303. tree.eventsCount += 1;
  304. if (isTraceTransaction(value)) {
  305. for (const error of value.errors) {
  306. traceNode.errors.add(error);
  307. }
  308. for (const performanceIssue of value.performance_issues) {
  309. traceNode.performance_issues.add(performanceIssue);
  310. }
  311. } else {
  312. traceNode.errors.add(value);
  313. }
  314. if (parent) {
  315. parent.children.push(node as TraceTreeNode<TraceTree.NodeValue>);
  316. }
  317. if ('start_timestamp' in value && value.start_timestamp < traceStart) {
  318. traceStart = value.start_timestamp;
  319. }
  320. if ('timestamp' in value && typeof value.timestamp === 'number') {
  321. // Errors don't have 'start_timestamp', so we adjust traceStart
  322. // with an errors 'timestamp'
  323. if (isTraceError(value)) {
  324. traceStart = Math.min(value.timestamp, traceStart);
  325. }
  326. traceEnd = Math.max(value.timestamp, traceEnd);
  327. }
  328. if (value && 'measurements' in value) {
  329. tree.collectMeasurements(
  330. traceStart,
  331. value.measurements as Record<string, Measurement>,
  332. tree.indicators
  333. );
  334. }
  335. if (value && 'children' in value) {
  336. for (const child of value.children) {
  337. visit(node, child);
  338. }
  339. }
  340. return node;
  341. }
  342. const transactionQueue = trace.transactions ?? [];
  343. const orphanErrorsQueue = trace.orphan_errors ?? [];
  344. let tIdx = 0;
  345. let oIdx = 0;
  346. const tLen = transactionQueue.length;
  347. const oLen = orphanErrorsQueue.length;
  348. while (tIdx < tLen || oIdx < oLen) {
  349. const transaction = transactionQueue[tIdx];
  350. const orphan = orphanErrorsQueue[oIdx];
  351. if (transaction && orphan) {
  352. if (
  353. typeof orphan.timestamp === 'number' &&
  354. transaction.start_timestamp <= orphan.timestamp
  355. ) {
  356. visit(traceNode, transaction);
  357. tIdx++;
  358. } else {
  359. visit(traceNode, orphan);
  360. oIdx++;
  361. }
  362. } else if (transaction) {
  363. visit(traceNode, transaction);
  364. tIdx++;
  365. } else if (orphan) {
  366. visit(traceNode, orphan);
  367. oIdx++;
  368. }
  369. }
  370. if (tree.indicators.length > 0) {
  371. tree.indicators.sort((a, b) => a.start - b.start);
  372. for (const indicator of tree.indicators) {
  373. if (indicator.start > traceEnd) {
  374. traceEnd = indicator.start;
  375. }
  376. indicator.start *= traceNode.multiplier;
  377. }
  378. }
  379. traceNode.space = [
  380. traceStart * traceNode.multiplier,
  381. (traceEnd - traceStart) * traceNode.multiplier,
  382. ];
  383. tree.root.space = [
  384. traceStart * traceNode.multiplier,
  385. (traceEnd - traceStart) * traceNode.multiplier,
  386. ];
  387. return tree.build();
  388. }
  389. get shape(): TraceType {
  390. const trace = this.root.children[0];
  391. if (!trace) {
  392. return TraceType.EMPTY_TRACE;
  393. }
  394. if (!isTraceNode(trace)) {
  395. throw new TypeError('Not trace node');
  396. }
  397. const {transactions, orphan_errors} = trace.value;
  398. const {roots, orphans} = (transactions ?? []).reduce(
  399. (counts, transaction) => {
  400. if (isRootTransaction(transaction)) {
  401. counts.roots++;
  402. } else {
  403. counts.orphans++;
  404. }
  405. return counts;
  406. },
  407. {roots: 0, orphans: 0}
  408. );
  409. if (roots === 0) {
  410. if (orphans > 0) {
  411. return TraceType.NO_ROOT;
  412. }
  413. if (orphan_errors && orphan_errors.length > 0) {
  414. return TraceType.ONLY_ERRORS;
  415. }
  416. return TraceType.EMPTY_TRACE;
  417. }
  418. if (roots === 1) {
  419. if (orphans > 0) {
  420. return TraceType.BROKEN_SUBTRACES;
  421. }
  422. return TraceType.ONE_ROOT;
  423. }
  424. if (roots > 1) {
  425. return TraceType.MULTIPLE_ROOTS;
  426. }
  427. throw new Error('Unknown trace type');
  428. }
  429. static FromSpans(
  430. parent: TraceTreeNode<TraceTree.NodeValue>,
  431. data: Event,
  432. spans: RawSpanType[],
  433. options: {sdk: string | undefined} | undefined
  434. ): TraceTreeNode<TraceTree.NodeValue> {
  435. parent.invalidate(parent);
  436. const platformHasMissingSpans = shouldAddMissingInstrumentationSpan(options?.sdk);
  437. const parentIsSpan = isSpanNode(parent);
  438. const lookuptable: Record<
  439. RawSpanType['span_id'],
  440. TraceTreeNode<TraceTree.Span | TraceTree.Transaction>
  441. > = {};
  442. if (parent.spanChildren.length > 0) {
  443. parent.zoomedIn = true;
  444. return parent;
  445. }
  446. if (parentIsSpan) {
  447. if (parent.value && 'span_id' in parent.value) {
  448. lookuptable[parent.value.span_id] = parent as TraceTreeNode<TraceTree.Span>;
  449. }
  450. }
  451. const transactionsToSpanMap = new Map<string, TraceTreeNode<TraceTree.Transaction>>();
  452. for (const child of parent.children) {
  453. if (
  454. isTransactionNode(child) &&
  455. 'parent_span_id' in child.value &&
  456. typeof child.value.parent_span_id === 'string'
  457. ) {
  458. transactionsToSpanMap.set(child.value.parent_span_id, child);
  459. }
  460. continue;
  461. }
  462. for (const span of spans) {
  463. const childTransaction = transactionsToSpanMap.get(span.span_id);
  464. const spanNodeValue: TraceTree.Span = {
  465. ...span,
  466. event: data as EventTransaction,
  467. childTransaction: childTransaction?.value,
  468. };
  469. const node: TraceTreeNode<TraceTree.Span> = new TraceTreeNode(null, spanNodeValue, {
  470. event_id: undefined,
  471. project_slug: undefined,
  472. });
  473. for (const error of getRelatedSpanErrorsFromTransaction(span, parent)) {
  474. node.errors.add(error);
  475. }
  476. for (const performanceIssue of getRelatedPerformanceIssuesFromTransaction(
  477. span,
  478. parent
  479. )) {
  480. node.performance_issues.add(performanceIssue);
  481. }
  482. // This is the case where the current span is the parent of a txn at the
  483. // trace level. When zooming into the parent of the txn, we want to place a copy
  484. // of the txn as a child of the parenting span.
  485. if (childTransaction) {
  486. const clonedChildTxn =
  487. childTransaction.cloneDeep() as unknown as TraceTreeNode<TraceTree.Span>;
  488. node.spanChildren.push(clonedChildTxn);
  489. clonedChildTxn.parent = node;
  490. }
  491. lookuptable[span.span_id] = node;
  492. if (span.parent_span_id) {
  493. const spanParentNode = lookuptable[span.parent_span_id];
  494. if (spanParentNode) {
  495. node.parent = spanParentNode;
  496. if (platformHasMissingSpans) {
  497. maybeInsertMissingInstrumentationSpan(spanParentNode, node);
  498. }
  499. spanParentNode.spanChildren.push(node);
  500. continue;
  501. }
  502. }
  503. if (platformHasMissingSpans) {
  504. maybeInsertMissingInstrumentationSpan(parent, node);
  505. }
  506. parent.spanChildren.push(node);
  507. node.parent = parent;
  508. }
  509. parent.zoomedIn = true;
  510. TraceTree.AutogroupSiblingSpanNodes(parent);
  511. TraceTree.AutogroupDirectChildrenSpanNodes(parent);
  512. return parent;
  513. }
  514. static AutogroupDirectChildrenSpanNodes(
  515. root: TraceTreeNode<TraceTree.NodeValue>
  516. ): void {
  517. const queue = [root];
  518. while (queue.length > 0) {
  519. const node = queue.pop()!;
  520. if (node.children.length > 1 || !isSpanNode(node)) {
  521. for (const child of node.children) {
  522. queue.push(child);
  523. }
  524. continue;
  525. }
  526. const head = node;
  527. let tail = node;
  528. let groupMatchCount = 0;
  529. const errors: TraceErrorType[] = [];
  530. const performance_issues: TracePerformanceIssue[] = [];
  531. let start = head.value.start_timestamp;
  532. let end = head.value.timestamp;
  533. while (
  534. tail &&
  535. tail.children.length === 1 &&
  536. isSpanNode(tail.children[0]) &&
  537. tail.children[0].value.op === head.value.op
  538. ) {
  539. if ((tail?.errors?.size ?? 0) > 0) {
  540. errors.push(...tail?.errors);
  541. }
  542. if ((tail?.performance_issues?.size ?? 0) > 0) {
  543. performance_issues.push(...tail.performance_issues);
  544. }
  545. // Collect start/end of all nodes in the list
  546. // so that we can properly render a autogrouped bar that
  547. // encapsulates all the nodes in the list
  548. if (tail.value.start_timestamp < start) {
  549. start = tail.value.start_timestamp;
  550. }
  551. if (tail.value.timestamp > end) {
  552. end = tail.value.timestamp;
  553. }
  554. groupMatchCount++;
  555. tail = tail.children[0];
  556. }
  557. // Checking the tail node for errors as it is not included in the grouping
  558. // while loop, but is hidden when the autogrouped node is collapsed
  559. if ((tail?.errors?.size ?? 0) > 0) {
  560. errors.push(...tail?.errors);
  561. }
  562. if ((tail?.performance_issues?.size ?? 0) > 0) {
  563. performance_issues.push(...tail.performance_issues);
  564. }
  565. if (groupMatchCount < 1) {
  566. for (const child of head.children) {
  567. queue.push(child);
  568. }
  569. continue;
  570. }
  571. const autoGroupedNode = new ParentAutogroupNode(
  572. node.parent,
  573. {
  574. ...head.value,
  575. start_timestamp: start,
  576. timestamp: end,
  577. autogrouped_by: {
  578. op: head.value && 'op' in head.value ? head.value.op ?? '' : '',
  579. },
  580. },
  581. {
  582. event_id: undefined,
  583. project_slug: undefined,
  584. },
  585. head,
  586. tail
  587. );
  588. if (!node.parent) {
  589. throw new Error('Parent node is missing, this should be unreachable code');
  590. }
  591. autoGroupedNode.groupCount = groupMatchCount + 1;
  592. for (const error of errors) {
  593. autoGroupedNode.errors.add(error);
  594. }
  595. for (const performanceIssue of performance_issues) {
  596. autoGroupedNode.performance_issues.add(performanceIssue);
  597. }
  598. autoGroupedNode.space = [
  599. start * autoGroupedNode.multiplier,
  600. (end - start) * autoGroupedNode.multiplier,
  601. ];
  602. for (const c of tail.children) {
  603. c.parent = autoGroupedNode;
  604. queue.push(c);
  605. }
  606. const index = node.parent.children.indexOf(node);
  607. node.parent.children[index] = autoGroupedNode;
  608. }
  609. }
  610. static AutogroupSiblingSpanNodes(root: TraceTreeNode<TraceTree.NodeValue>): void {
  611. const queue = [root];
  612. while (queue.length > 0) {
  613. const node = queue.pop()!;
  614. for (const child of node.children) {
  615. queue.push(child);
  616. }
  617. if (node.children.length < 5) {
  618. continue;
  619. }
  620. let index = 0;
  621. let matchCount = 0;
  622. while (index < node.children.length) {
  623. const current = node.children[index] as TraceTreeNode<TraceTree.Span>;
  624. const next = node.children[index + 1] as TraceTreeNode<TraceTree.Span>;
  625. if (
  626. next &&
  627. next.children.length === 0 &&
  628. current.children.length === 0 &&
  629. next.value.op === current.value.op &&
  630. next.value.description === current.value.description
  631. ) {
  632. matchCount++;
  633. // If the next node is the last node in the list, we keep iterating
  634. if (index + 1 < node.children.length) {
  635. index++;
  636. continue;
  637. }
  638. }
  639. if (matchCount >= 4) {
  640. const autoGroupedNode = new SiblingAutogroupNode(
  641. node,
  642. {
  643. ...current.value,
  644. autogrouped_by: {
  645. op: current.value.op ?? '',
  646. description: current.value.description ?? '',
  647. },
  648. },
  649. {
  650. event_id: undefined,
  651. project_slug: undefined,
  652. }
  653. );
  654. autoGroupedNode.groupCount = matchCount + 1;
  655. const start = index - matchCount;
  656. let start_timestamp = Number.MAX_SAFE_INTEGER;
  657. let timestamp = Number.MIN_SAFE_INTEGER;
  658. for (let j = start; j < start + matchCount + 1; j++) {
  659. const child = node.children[j];
  660. if (
  661. child.value &&
  662. 'timestamp' in child.value &&
  663. typeof child.value.timestamp === 'number' &&
  664. child.value.timestamp > timestamp
  665. ) {
  666. timestamp = child.value.timestamp;
  667. }
  668. if (
  669. child.value &&
  670. 'start_timestamp' in child.value &&
  671. typeof child.value.start_timestamp === 'number' &&
  672. child.value.start_timestamp < start_timestamp
  673. ) {
  674. start_timestamp = child.value.start_timestamp;
  675. }
  676. if (!isSpanNode(child)) {
  677. throw new TypeError(
  678. 'Expected child of autogrouped node to be a span node.'
  679. );
  680. }
  681. if (child.has_errors) {
  682. for (const error of child.errors) {
  683. autoGroupedNode.errors.add(error);
  684. }
  685. for (const performanceIssue of child.performance_issues) {
  686. autoGroupedNode.performance_issues.add(performanceIssue);
  687. }
  688. }
  689. autoGroupedNode.children.push(node.children[j]);
  690. autoGroupedNode.children[autoGroupedNode.children.length - 1].parent =
  691. autoGroupedNode;
  692. }
  693. autoGroupedNode.space = [
  694. start_timestamp * autoGroupedNode.multiplier,
  695. (timestamp - start_timestamp) * autoGroupedNode.multiplier,
  696. ];
  697. node.children.splice(start, matchCount + 1, autoGroupedNode);
  698. index = start + 1;
  699. matchCount = 0;
  700. } else {
  701. index++;
  702. matchCount = 0;
  703. }
  704. }
  705. }
  706. }
  707. collectMeasurements(
  708. start_timestamp: number,
  709. measurements: Record<string, Measurement>,
  710. indicators: TraceTree.Indicator[]
  711. ): void {
  712. for (const measurement of RENDERABLE_MEASUREMENTS) {
  713. const value = measurements[measurement];
  714. if (!value) {
  715. continue;
  716. }
  717. const timestamp = measurementToTimestamp(
  718. start_timestamp,
  719. value.value,
  720. value.unit ?? 'millisecond'
  721. );
  722. indicators.push({
  723. start: timestamp,
  724. duration: 0,
  725. measurement: value,
  726. poor: MEASUREMENT_THRESHOLDS[measurement]
  727. ? value.value > MEASUREMENT_THRESHOLDS[measurement]
  728. : false,
  729. type: measurement as TraceTree.Indicator['type'],
  730. label: (MEASUREMENT_ACRONYM_MAPPING[measurement] ?? measurement).toUpperCase(),
  731. });
  732. }
  733. }
  734. // Returns boolean to indicate if node was updated
  735. expand(node: TraceTreeNode<TraceTree.NodeValue>, expanded: boolean): boolean {
  736. if (expanded === node.expanded) {
  737. return false;
  738. }
  739. // Expanding is not allowed for zoomed in nodes
  740. if (node.zoomedIn) {
  741. return false;
  742. }
  743. if (node instanceof ParentAutogroupNode) {
  744. // In parent autogrouping, we perform a node swap and either point the
  745. // head or tails of the autogrouped sequence to the autogrouped node
  746. if (node.expanded) {
  747. const index = this._list.indexOf(node);
  748. const autogroupedChildren = node.getVisibleChildren();
  749. this._list.splice(index + 1, autogroupedChildren.length);
  750. const newChildren = node.tail.getVisibleChildren();
  751. for (const c of node.tail.children) {
  752. c.parent = node;
  753. }
  754. this._list.splice(index + 1, 0, ...newChildren);
  755. } else {
  756. node.head.parent = node;
  757. const index = this._list.indexOf(node);
  758. const childrenCount = node.getVisibleChildrenCount();
  759. this._list.splice(index + 1, childrenCount);
  760. node.getVisibleChildrenCount();
  761. const newChildren = [node.head].concat(
  762. node.head.getVisibleChildren() as TraceTreeNode<TraceTree.Span>[]
  763. );
  764. for (const c of node.children) {
  765. c.parent = node.tail;
  766. }
  767. this._list.splice(index + 1, 0, ...newChildren);
  768. }
  769. node.invalidate(node);
  770. node.expanded = expanded;
  771. return true;
  772. }
  773. if (node.expanded) {
  774. const index = this._list.indexOf(node);
  775. this._list.splice(index + 1, node.getVisibleChildrenCount());
  776. // Flip expanded after collecting visible children
  777. node.expanded = expanded;
  778. } else {
  779. const index = this._list.indexOf(node);
  780. // Flip expanded so that we can collect visible children
  781. node.expanded = expanded;
  782. this._list.splice(index + 1, 0, ...node.getVisibleChildren());
  783. }
  784. node.expanded = expanded;
  785. return true;
  786. }
  787. zoomIn(
  788. node: TraceTreeNode<TraceTree.NodeValue>,
  789. zoomedIn: boolean,
  790. options: {
  791. api: Client;
  792. organization: Organization;
  793. }
  794. ): Promise<Event | null> {
  795. if (zoomedIn === node.zoomedIn) {
  796. return Promise.resolve(null);
  797. }
  798. if (!zoomedIn) {
  799. const index = this._list.indexOf(node);
  800. const childrenCount = node.getVisibleChildrenCount();
  801. this._list.splice(index + 1, childrenCount);
  802. node.zoomedIn = zoomedIn;
  803. node.invalidate(node);
  804. if (node.expanded) {
  805. this._list.splice(index + 1, 0, ...node.getVisibleChildren());
  806. }
  807. return Promise.resolve(null);
  808. }
  809. const key = cacheKey(
  810. options.organization,
  811. node.metadata.project_slug!,
  812. node.metadata.event_id!
  813. );
  814. const promise =
  815. this._spanPromises.get(key) ??
  816. fetchTransactionSpans(
  817. options.api,
  818. options.organization,
  819. node.metadata.project_slug!,
  820. node.metadata.event_id!
  821. );
  822. node.fetchStatus = 'loading';
  823. promise
  824. .then(data => {
  825. node.fetchStatus = 'resolved';
  826. const spans = data.entries.find(s => s.type === 'spans');
  827. if (!spans) {
  828. return data;
  829. }
  830. // Remove existing entries from the list
  831. const index = this._list.indexOf(node);
  832. if (node.expanded) {
  833. const childrenCount = node.getVisibleChildrenCount();
  834. if (childrenCount > 0) {
  835. this._list.splice(index + 1, childrenCount);
  836. }
  837. }
  838. // Api response is not sorted
  839. if (spans.data) {
  840. spans.data.sort((a, b) => a.start_timestamp - b.start_timestamp);
  841. }
  842. TraceTree.FromSpans(node, data, spans.data, {sdk: data.sdk?.name});
  843. const spanChildren = node.getVisibleChildren();
  844. this._list.splice(index + 1, 0, ...spanChildren);
  845. return data;
  846. })
  847. .catch(_e => {
  848. node.fetchStatus = 'error';
  849. });
  850. this._spanPromises.set(key, promise);
  851. return promise;
  852. }
  853. toList(): TraceTreeNode<TraceTree.NodeValue>[] {
  854. const list: TraceTreeNode<TraceTree.NodeValue>[] = [];
  855. function visit(node: TraceTreeNode<TraceTree.NodeValue>) {
  856. list.push(node);
  857. if (!node.expanded) {
  858. return;
  859. }
  860. for (const child of node.children) {
  861. visit(child);
  862. }
  863. }
  864. for (const child of this.root.children) {
  865. visit(child);
  866. }
  867. return list;
  868. }
  869. get list(): ReadonlyArray<TraceTreeNode<TraceTree.NodeValue>> {
  870. return this._list;
  871. }
  872. /**
  873. * Prints the tree in a human readable format, useful for debugging and testing
  874. */
  875. print() {
  876. // root nodes are -1 indexed, so we add 1 to the depth so .repeat doesnt throw
  877. const print = this.list
  878. .map(t => printNode(t, 0))
  879. .filter(Boolean)
  880. .join('\n');
  881. // eslint-disable-next-line no-console
  882. console.log(print);
  883. }
  884. build() {
  885. this._list = this.toList();
  886. return this;
  887. }
  888. }
  889. export class TraceTreeNode<T extends TraceTree.NodeValue> {
  890. canFetch: boolean = false;
  891. fetchStatus: 'resolved' | 'error' | 'idle' | 'loading' = 'idle';
  892. parent: TraceTreeNode<TraceTree.NodeValue> | null = null;
  893. value: T;
  894. expanded: boolean = false;
  895. zoomedIn: boolean = false;
  896. metadata: TraceTree.Metadata = {
  897. project_slug: undefined,
  898. event_id: undefined,
  899. };
  900. errors: Set<TraceErrorType> = new Set<TraceErrorType>();
  901. performance_issues: Set<TracePerformanceIssue> = new Set<TracePerformanceIssue>();
  902. multiplier: number;
  903. space: [number, number] | null = null;
  904. profiles: TraceTree.Profile[] = [];
  905. private unit: 'milliseconds' = 'milliseconds';
  906. private _depth: number | undefined;
  907. private _children: TraceTreeNode<TraceTree.NodeValue>[] = [];
  908. private _spanChildren: TraceTreeNode<
  909. TraceTree.Span | TraceTree.MissingInstrumentationSpan
  910. >[] = [];
  911. private _connectors: number[] | undefined = undefined;
  912. constructor(
  913. parent: TraceTreeNode<TraceTree.NodeValue> | null,
  914. value: T,
  915. metadata: TraceTree.Metadata
  916. ) {
  917. this.parent = parent ?? null;
  918. this.value = value;
  919. this.metadata = metadata;
  920. this.multiplier = this.unit === 'milliseconds' ? 1e3 : 1;
  921. if (value && 'timestamp' in value && 'start_timestamp' in value) {
  922. this.space = [
  923. value.start_timestamp * this.multiplier,
  924. (value.timestamp - value.start_timestamp) * this.multiplier,
  925. ];
  926. } else if (value && 'timestamp' in value && typeof value.timestamp === 'number') {
  927. this.space = [value.timestamp * this.multiplier, 0];
  928. }
  929. if (
  930. isTraceErrorNode(this) &&
  931. 'timestamp' in this.value &&
  932. typeof this.value.timestamp === 'number'
  933. ) {
  934. this.space = [this.value.timestamp * this.multiplier, 0];
  935. }
  936. if (value && 'profile_id' in value && typeof value.profile_id === 'string') {
  937. this.profiles.push({profile_id: value.profile_id, space: this.space ?? [0, 0]});
  938. }
  939. if (isTransactionNode(this)) {
  940. this.canFetch = true;
  941. }
  942. if (isTransactionNode(this) || isTraceNode(this) || isSpanNode(this)) {
  943. this.expanded = true;
  944. }
  945. if (shouldCollapseNodeByDefault(this)) {
  946. this.expanded = false;
  947. }
  948. if (isTransactionNode(this)) {
  949. this.errors = new Set(this.value.errors);
  950. this.performance_issues = new Set(this.value.performance_issues);
  951. }
  952. // For error nodes, its value is the only associated issue.
  953. if (isTraceErrorNode(this)) {
  954. this.errors = new Set([this.value]);
  955. }
  956. }
  957. cloneDeep(): TraceTreeNode<T> | ParentAutogroupNode | SiblingAutogroupNode {
  958. let node: TraceTreeNode<T> | ParentAutogroupNode | SiblingAutogroupNode;
  959. if (isParentAutogroupedNode(this)) {
  960. node = new ParentAutogroupNode(
  961. this.parent,
  962. this.value,
  963. this.metadata,
  964. this.head,
  965. this.tail
  966. );
  967. node.groupCount = this.groupCount;
  968. } else {
  969. node = new TraceTreeNode(this.parent, this.value, this.metadata);
  970. }
  971. if (!node) {
  972. throw new Error('CloneDeep is not implemented');
  973. }
  974. node.expanded = this.expanded;
  975. node.zoomedIn = this.zoomedIn;
  976. node.canFetch = this.canFetch;
  977. node.space = this.space;
  978. node.metadata = this.metadata;
  979. if (isParentAutogroupedNode(node)) {
  980. node.head = node.head.cloneDeep() as TraceTreeNode<TraceTree.Span>;
  981. node.tail = node.tail.cloneDeep() as TraceTreeNode<TraceTree.Span>;
  982. node.head.parent = node;
  983. // If the node is not expanded, the parent of the tail points to the
  984. // autogrouped node. If the node is expanded, the parent of the children
  985. // of the tail points to the autogrouped node.
  986. if (!node.expanded) {
  987. for (const c of node.tail.children) {
  988. c.parent = node;
  989. }
  990. } else {
  991. for (const c of node.children) {
  992. c.parent = node.tail;
  993. }
  994. }
  995. node.head.parent = node;
  996. node.tail.parent = node;
  997. } else {
  998. for (const child of this.children) {
  999. const childClone = child.cloneDeep() as TraceTreeNode<TraceTree.Span>;
  1000. node.children.push(childClone);
  1001. childClone.parent = node;
  1002. }
  1003. }
  1004. return node;
  1005. }
  1006. get isOrphaned() {
  1007. return this.parent?.value && 'orphan_errors' in this.parent.value;
  1008. }
  1009. get isLastChild() {
  1010. if (!this.parent || this.parent.children.length === 0) {
  1011. return true;
  1012. }
  1013. return this.parent.children[this.parent.children.length - 1] === this;
  1014. }
  1015. /**
  1016. * Return a lazily calculated depth of the node in the tree.
  1017. * Root node has a value of -1 as it is abstract.
  1018. */
  1019. get depth(): number {
  1020. if (typeof this._depth === 'number') {
  1021. return this._depth;
  1022. }
  1023. let depth = -2;
  1024. let node: TraceTreeNode<any> | null = this;
  1025. while (node) {
  1026. if (typeof node.parent?.depth === 'number') {
  1027. this._depth = node.parent.depth + 1;
  1028. return this._depth;
  1029. }
  1030. depth++;
  1031. node = node.parent;
  1032. }
  1033. this._depth = depth;
  1034. return this._depth;
  1035. }
  1036. get has_errors(): boolean {
  1037. return this.errors.size > 0 || this.performance_issues.size > 0;
  1038. }
  1039. get parent_transaction(): TraceTreeNode<TraceTree.Transaction> | null {
  1040. let node: TraceTreeNode<TraceTree.NodeValue> | null = this.parent;
  1041. while (node) {
  1042. if (isTransactionNode(node)) {
  1043. return node;
  1044. }
  1045. node = node.parent;
  1046. }
  1047. return null;
  1048. }
  1049. /**
  1050. * Returns the depth levels at which the row should draw vertical connectors
  1051. * negative values mean connector points to an orphaned node
  1052. */
  1053. get connectors(): number[] {
  1054. if (this._connectors !== undefined) {
  1055. return this._connectors!;
  1056. }
  1057. this._connectors = [];
  1058. if (!this.parent) {
  1059. return this._connectors;
  1060. }
  1061. if (this.parent?.connectors !== undefined) {
  1062. this._connectors = [...this.parent.connectors];
  1063. if (this.isLastChild || this.value === null) {
  1064. return this._connectors;
  1065. }
  1066. this.connectors.push(this.isOrphaned ? -this.depth : this.depth);
  1067. return this._connectors;
  1068. }
  1069. let node: TraceTreeNode<T> | TraceTreeNode<TraceTree.NodeValue> | null = this.parent;
  1070. while (node) {
  1071. if (node.value === null) {
  1072. break;
  1073. }
  1074. if (node.isLastChild) {
  1075. node = node.parent;
  1076. continue;
  1077. }
  1078. this._connectors.push(node.isOrphaned ? -node.depth : node.depth);
  1079. node = node.parent;
  1080. }
  1081. return this._connectors;
  1082. }
  1083. /**
  1084. * Returns the children that the node currently points to.
  1085. * The logic here is a consequence of the tree design, where we want to be able to store
  1086. * both transaction and span nodes in the same tree. This results in an annoying API where
  1087. * we either store span children separately or transaction children separately. A better design
  1088. * would have been to create an invisible meta node that always points to the correct children.
  1089. */
  1090. get children(): TraceTreeNode<TraceTree.NodeValue>[] {
  1091. if (isAutogroupedNode(this)) {
  1092. return this._children;
  1093. }
  1094. if (isSpanNode(this)) {
  1095. return this.canFetch && !this.zoomedIn ? [] : this.spanChildren;
  1096. }
  1097. if (isTransactionNode(this)) {
  1098. return this.zoomedIn ? this._spanChildren : this._children;
  1099. }
  1100. return this._children;
  1101. }
  1102. set children(children: TraceTreeNode<TraceTree.NodeValue>[]) {
  1103. this._children = children;
  1104. }
  1105. get spanChildren(): TraceTreeNode<
  1106. TraceTree.Span | TraceTree.MissingInstrumentationSpan
  1107. >[] {
  1108. return this._spanChildren;
  1109. }
  1110. /**
  1111. * Invalidate the visual data used to render the tree, forcing it
  1112. * to be recalculated on the next render. This is useful when for example
  1113. * the tree is expanded or collapsed, or when the tree is mutated and
  1114. * the visual data is no longer valid as the indentation changes
  1115. */
  1116. invalidate(root?: TraceTreeNode<TraceTree.NodeValue>) {
  1117. this._connectors = undefined;
  1118. this._depth = undefined;
  1119. if (root) {
  1120. const queue = [...this.children];
  1121. if (isParentAutogroupedNode(this)) {
  1122. queue.push(this.head);
  1123. }
  1124. while (queue.length > 0) {
  1125. const next = queue.pop()!;
  1126. next.invalidate();
  1127. if (isParentAutogroupedNode(next)) {
  1128. queue.push(next.head);
  1129. }
  1130. for (let i = 0; i < next.children.length; i++) {
  1131. queue.push(next.children[i]);
  1132. }
  1133. }
  1134. }
  1135. }
  1136. getVisibleChildrenCount(): number {
  1137. const stack: TraceTreeNode<TraceTree.NodeValue>[] = [];
  1138. let count = 0;
  1139. if (
  1140. this.expanded ||
  1141. isParentAutogroupedNode(this) ||
  1142. isMissingInstrumentationNode(this)
  1143. ) {
  1144. for (let i = this.children.length - 1; i >= 0; i--) {
  1145. stack.push(this.children[i]);
  1146. }
  1147. }
  1148. while (stack.length > 0) {
  1149. const node = stack.pop()!;
  1150. count++;
  1151. // Since we're using a stack and it's LIFO, reverse the children before pushing them
  1152. // to ensure they are processed in the original left-to-right order.
  1153. if (node.expanded || isParentAutogroupedNode(node)) {
  1154. for (let i = node.children.length - 1; i >= 0; i--) {
  1155. stack.push(node.children[i]);
  1156. }
  1157. }
  1158. }
  1159. return count;
  1160. }
  1161. getVisibleChildren(): TraceTreeNode<TraceTree.NodeValue>[] {
  1162. const stack: TraceTreeNode<TraceTree.NodeValue>[] = [];
  1163. const children: TraceTreeNode<TraceTree.NodeValue>[] = [];
  1164. if (
  1165. this.expanded ||
  1166. isParentAutogroupedNode(this) ||
  1167. isMissingInstrumentationNode(this)
  1168. ) {
  1169. for (let i = this.children.length - 1; i >= 0; i--) {
  1170. stack.push(this.children[i]);
  1171. }
  1172. }
  1173. while (stack.length > 0) {
  1174. const node = stack.pop()!;
  1175. children.push(node);
  1176. // Since we're using a stack and it's LIFO, reverse the children before pushing them
  1177. // to ensure they are processed in the original left-to-right order.
  1178. if (node.expanded || isParentAutogroupedNode(node)) {
  1179. for (let i = node.children.length - 1; i >= 0; i--) {
  1180. stack.push(node.children[i]);
  1181. }
  1182. }
  1183. }
  1184. return children;
  1185. }
  1186. // Returns the min path required to reach the node from the root.
  1187. // @TODO: skip nodes that do not require fetching
  1188. get path(): TraceTree.NodePath[] {
  1189. const nodes: TraceTreeNode<TraceTree.NodeValue>[] = [this];
  1190. let current: TraceTreeNode<TraceTree.NodeValue> | null = this.parent;
  1191. if (isSpanNode(this) || isAutogroupedNode(this)) {
  1192. while (
  1193. current &&
  1194. (isSpanNode(current) || (isAutogroupedNode(current) && !current.expanded))
  1195. ) {
  1196. current = current.parent;
  1197. }
  1198. }
  1199. while (current) {
  1200. if (isTransactionNode(current)) {
  1201. nodes.push(current);
  1202. }
  1203. if (isSpanNode(current)) {
  1204. nodes.push(current);
  1205. while (current.parent) {
  1206. if (isTransactionNode(current.parent)) {
  1207. break;
  1208. }
  1209. if (isAutogroupedNode(current.parent) && current.parent.expanded) {
  1210. break;
  1211. }
  1212. current = current.parent;
  1213. }
  1214. }
  1215. if (isAutogroupedNode(current)) {
  1216. nodes.push(current);
  1217. }
  1218. current = current.parent;
  1219. }
  1220. return nodes.map(nodeToId);
  1221. }
  1222. print() {
  1223. // root nodes are -1 indexed, so we add 1 to the depth so .repeat doesnt throw
  1224. const offset = this.depth === -1 ? 1 : 0;
  1225. const nodes = [this, ...this.getVisibleChildren()];
  1226. const print = nodes
  1227. .map(t => printNode(t, offset))
  1228. .filter(Boolean)
  1229. .join('\n');
  1230. // eslint-disable-next-line no-console
  1231. console.log(print);
  1232. }
  1233. static Find(
  1234. root: TraceTreeNode<TraceTree.NodeValue>,
  1235. predicate: (node: TraceTreeNode<TraceTree.NodeValue>) => boolean
  1236. ): TraceTreeNode<TraceTree.NodeValue> | null {
  1237. const queue = [root];
  1238. while (queue.length > 0) {
  1239. const next = queue.pop()!;
  1240. if (predicate(next)) return next;
  1241. for (const child of next.children) {
  1242. queue.push(child);
  1243. }
  1244. }
  1245. return null;
  1246. }
  1247. static Root() {
  1248. return new TraceTreeNode(null, null, {
  1249. event_id: undefined,
  1250. project_slug: undefined,
  1251. });
  1252. }
  1253. }
  1254. export class MissingInstrumentationNode extends TraceTreeNode<TraceTree.MissingInstrumentationSpan> {
  1255. next: TraceTreeNode<TraceTree.Span>;
  1256. previous: TraceTreeNode<TraceTree.Span>;
  1257. constructor(
  1258. parent: TraceTreeNode<TraceTree.NodeValue>,
  1259. node: TraceTree.MissingInstrumentationSpan,
  1260. metadata: TraceTree.Metadata,
  1261. previous: TraceTreeNode<TraceTree.Span>,
  1262. next: TraceTreeNode<TraceTree.Span>
  1263. ) {
  1264. super(parent, node, metadata);
  1265. this.next = next;
  1266. this.previous = previous;
  1267. }
  1268. }
  1269. export class ParentAutogroupNode extends TraceTreeNode<TraceTree.ChildrenAutogroup> {
  1270. head: TraceTreeNode<TraceTree.Span>;
  1271. tail: TraceTreeNode<TraceTree.Span>;
  1272. groupCount: number = 0;
  1273. profiles: TraceTree.Profile[] = [];
  1274. private _autogroupedSegments: [number, number][] | undefined;
  1275. constructor(
  1276. parent: TraceTreeNode<TraceTree.NodeValue> | null,
  1277. node: TraceTree.ChildrenAutogroup,
  1278. metadata: TraceTree.Metadata,
  1279. head: TraceTreeNode<TraceTree.Span>,
  1280. tail: TraceTreeNode<TraceTree.Span>
  1281. ) {
  1282. super(parent, node, metadata);
  1283. this.expanded = false;
  1284. this.head = head;
  1285. this.tail = tail;
  1286. }
  1287. get children() {
  1288. if (this.expanded) {
  1289. return [this.head];
  1290. }
  1291. return this.tail.children;
  1292. }
  1293. get has_errors(): boolean {
  1294. return this.errors.size > 0 || this.performance_issues.size > 0;
  1295. }
  1296. get autogroupedSegments(): [number, number][] {
  1297. if (this._autogroupedSegments) {
  1298. return this._autogroupedSegments;
  1299. }
  1300. const children: TraceTreeNode<TraceTree.NodeValue>[] = [];
  1301. let start: TraceTreeNode<TraceTree.NodeValue> | undefined = this.head;
  1302. while (start && start !== this.tail) {
  1303. children.push(start);
  1304. start = start.children[0];
  1305. }
  1306. children.push(this.tail);
  1307. this._autogroupedSegments = computeAutogroupedBarSegments(children);
  1308. return this._autogroupedSegments;
  1309. }
  1310. }
  1311. export class SiblingAutogroupNode extends TraceTreeNode<TraceTree.SiblingAutogroup> {
  1312. groupCount: number = 0;
  1313. profiles: TraceTree.Profile[] = [];
  1314. private _autogroupedSegments: [number, number][] | undefined;
  1315. constructor(
  1316. parent: TraceTreeNode<TraceTree.NodeValue> | null,
  1317. node: TraceTree.SiblingAutogroup,
  1318. metadata: TraceTree.Metadata
  1319. ) {
  1320. super(parent, node, metadata);
  1321. this.expanded = false;
  1322. }
  1323. get has_errors(): boolean {
  1324. return this.errors.size > 0 || this.performance_issues.size > 0;
  1325. }
  1326. get autogroupedSegments(): [number, number][] {
  1327. if (this._autogroupedSegments) {
  1328. return this._autogroupedSegments;
  1329. }
  1330. this._autogroupedSegments = computeAutogroupedBarSegments(this.children);
  1331. return this._autogroupedSegments;
  1332. }
  1333. }
  1334. function partialTransaction(
  1335. partial: Partial<TraceTree.Transaction>
  1336. ): TraceTree.Transaction {
  1337. return {
  1338. start_timestamp: 0,
  1339. timestamp: 0,
  1340. errors: [],
  1341. performance_issues: [],
  1342. parent_span_id: '',
  1343. span_id: '',
  1344. parent_event_id: '',
  1345. project_id: 0,
  1346. 'transaction.duration': 0,
  1347. 'transaction.op': 'db',
  1348. 'transaction.status': 'ok',
  1349. generation: 0,
  1350. project_slug: '',
  1351. event_id: `event_id`,
  1352. transaction: `transaction`,
  1353. children: [],
  1354. ...partial,
  1355. };
  1356. }
  1357. export function makeExampleTrace(metadata: TraceTree.Metadata): TraceTree {
  1358. const trace: TraceTree.Trace = {
  1359. transactions: [],
  1360. orphan_errors: [],
  1361. };
  1362. function randomBetween(min: number, max: number) {
  1363. return Math.floor(Math.random() * (max - min + 1) + min);
  1364. }
  1365. let start = new Date().getTime();
  1366. const root = partialTransaction({
  1367. ...metadata,
  1368. generation: 0,
  1369. start_timestamp: start,
  1370. transaction: 'root transaction',
  1371. timestamp: start + randomBetween(100, 200),
  1372. });
  1373. trace.transactions.push(root);
  1374. for (let i = 0; i < 50; i++) {
  1375. const end = start + randomBetween(100, 200);
  1376. const nest = i > 0 && Math.random() > 0.33;
  1377. if (nest) {
  1378. const parent = root.children[root.children.length - 1];
  1379. parent.children.push(
  1380. partialTransaction({
  1381. ...metadata,
  1382. generation: 0,
  1383. start_timestamp: start,
  1384. transaction: `parent transaction ${i}`,
  1385. timestamp: end,
  1386. })
  1387. );
  1388. parent.timestamp = end;
  1389. } else {
  1390. root.children.push(
  1391. partialTransaction({
  1392. ...metadata,
  1393. generation: 0,
  1394. start_timestamp: start,
  1395. transaction: 'loading...',
  1396. ['transaction.op']: 'loading',
  1397. timestamp: end,
  1398. })
  1399. );
  1400. }
  1401. start = end;
  1402. }
  1403. const tree = TraceTree.FromTrace(trace);
  1404. return tree;
  1405. }
  1406. function nodeToId(n: TraceTreeNode<TraceTree.NodeValue>): TraceTree.NodePath {
  1407. if (isTransactionNode(n)) {
  1408. return `txn:${n.value.event_id}`;
  1409. }
  1410. if (isSpanNode(n)) {
  1411. return `span:${n.value.span_id}`;
  1412. }
  1413. if (isAutogroupedNode(n)) {
  1414. if (isParentAutogroupedNode(n)) {
  1415. return `ag:${n.head.value.span_id}`;
  1416. }
  1417. if (isSiblingAutogroupedNode(n)) {
  1418. const child = n.children[0];
  1419. if (isSpanNode(child)) {
  1420. return `ag:${child.value.span_id}`;
  1421. }
  1422. }
  1423. }
  1424. if (isTraceNode(n)) {
  1425. return `trace:root`;
  1426. }
  1427. if (isTraceErrorNode(n)) {
  1428. return `error:${n.value.event_id}`;
  1429. }
  1430. if (isRootNode(n)) {
  1431. throw new Error('A path to root node does not exist as the node is virtual');
  1432. }
  1433. if (isMissingInstrumentationNode(n)) {
  1434. if (n.previous) {
  1435. return `ms:${n.previous.value.span_id}`;
  1436. }
  1437. if (n.next) {
  1438. return `ms:${n.next.value.span_id}`;
  1439. }
  1440. throw new Error('Missing instrumentation node must have a previous or next node');
  1441. }
  1442. throw new Error('Not implemented');
  1443. }
  1444. export function computeAutogroupedBarSegments(
  1445. nodes: TraceTreeNode<TraceTree.NodeValue>[]
  1446. ): [number, number][] {
  1447. if (nodes.length === 0) {
  1448. return [];
  1449. }
  1450. if (nodes.length === 1) {
  1451. const space = nodes[0].space;
  1452. if (!space) {
  1453. throw new Error(
  1454. 'Autogrouped node child has no defined space. This should not happen.'
  1455. );
  1456. }
  1457. return [space];
  1458. }
  1459. const first = nodes[0];
  1460. const multiplier = first.multiplier;
  1461. if (!isSpanNode(first)) {
  1462. throw new Error('Autogrouped node must have span children');
  1463. }
  1464. const segments: [number, number][] = [];
  1465. let start = first.value.start_timestamp;
  1466. let end = first.value.timestamp;
  1467. let i = 1;
  1468. while (i < nodes.length) {
  1469. const next = nodes[i];
  1470. if (!isSpanNode(next)) {
  1471. throw new Error('Autogrouped node must have span children');
  1472. }
  1473. if (next.value.start_timestamp > end) {
  1474. segments.push([start * multiplier, (end - start) * multiplier]);
  1475. start = next.value.start_timestamp;
  1476. end = next.value.timestamp;
  1477. i++;
  1478. } else {
  1479. end = next.value.timestamp;
  1480. i++;
  1481. }
  1482. }
  1483. segments.push([start * multiplier, (end - start) * multiplier]);
  1484. return segments;
  1485. }
  1486. // Returns a list of errors related to the txn with ids matching the span id
  1487. function getRelatedSpanErrorsFromTransaction(
  1488. span: RawSpanType,
  1489. node?: TraceTreeNode<TraceTree.NodeValue>
  1490. ): TraceErrorType[] {
  1491. if (!node || !node.value || !isTransactionNode(node)) {
  1492. return [];
  1493. }
  1494. if (!node?.value?.errors?.length) {
  1495. return [];
  1496. }
  1497. const errors: TraceErrorType[] = [];
  1498. for (const error of node.value.errors) {
  1499. if (error.span === span.span_id) {
  1500. errors.push(error);
  1501. }
  1502. }
  1503. return errors;
  1504. }
  1505. // Returns a list of performance errors related to the txn with ids matching the span id
  1506. function getRelatedPerformanceIssuesFromTransaction(
  1507. span: RawSpanType,
  1508. node?: TraceTreeNode<TraceTree.NodeValue>
  1509. ): TracePerformanceIssue[] {
  1510. if (!node || !node.value || !isTransactionNode(node)) {
  1511. return [];
  1512. }
  1513. if (!node?.value?.performance_issues?.length && !node?.value?.errors?.length) {
  1514. return [];
  1515. }
  1516. const performanceIssues: TracePerformanceIssue[] = [];
  1517. for (const perfIssue of node.value.performance_issues) {
  1518. for (const s of perfIssue.span) {
  1519. if (s === span.span_id) {
  1520. performanceIssues.push(perfIssue);
  1521. }
  1522. }
  1523. for (const suspect of perfIssue.suspect_spans) {
  1524. if (suspect === span.span_id) {
  1525. performanceIssues.push(perfIssue);
  1526. }
  1527. }
  1528. }
  1529. return performanceIssues;
  1530. }
  1531. function printNode(t: TraceTreeNode<TraceTree.NodeValue>, offset: number): string {
  1532. // +1 because we may be printing from the root which is -1 indexed
  1533. const padding = ' '.repeat(t.depth + offset);
  1534. if (isAutogroupedNode(t)) {
  1535. if (isParentAutogroupedNode(t)) {
  1536. return padding + `parent autogroup (${t.groupCount})`;
  1537. }
  1538. if (isSiblingAutogroupedNode(t)) {
  1539. return padding + `sibling autogroup (${t.groupCount})`;
  1540. }
  1541. return padding + 'autogroup';
  1542. }
  1543. if (isSpanNode(t)) {
  1544. return padding + (t.value.op || t.value.span_id || 'unknown span');
  1545. }
  1546. if (isTransactionNode(t)) {
  1547. return padding + (t.value.transaction || 'unknown transaction');
  1548. }
  1549. if (isMissingInstrumentationNode(t)) {
  1550. return padding + 'missing_instrumentation';
  1551. }
  1552. if (isRootNode(t)) {
  1553. return padding + 'Root';
  1554. }
  1555. if (isTraceNode(t)) {
  1556. return padding + 'Trace';
  1557. }
  1558. if (isTraceErrorNode(t)) {
  1559. return padding + (t.value.event_id || t.value.level) || 'unknown trace error';
  1560. }
  1561. return 'unknown node';
  1562. }