traceTree.tsx 50 KB

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