traceTree.tsx 51 KB

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