traceTree.tsx 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712
  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 erroredChildren: TraceTreeNode<TraceTree.NodeValue>[] = [];
  462. while (
  463. tail &&
  464. tail.children.length === 1 &&
  465. isSpanNode(tail.children[0]) &&
  466. tail.children[0].value.op === head.value.op
  467. ) {
  468. if (
  469. isTraceErrorNode(tail) &&
  470. (tail.value.errors.length > 0 || tail.value.performance_issues.length > 0)
  471. ) {
  472. erroredChildren.push(tail);
  473. }
  474. groupMatchCount++;
  475. tail = tail.children[0];
  476. }
  477. // Checking the tail node for errors as it is not included in the grouping
  478. // while loop, but is hidden when the autogrouped node is collapsed
  479. if (tail.hasErrors()) {
  480. erroredChildren.push(tail);
  481. }
  482. if (groupMatchCount < 1) {
  483. for (const child of head.children) {
  484. queue.push(child);
  485. }
  486. continue;
  487. }
  488. const autoGroupedNode = new ParentAutogroupNode(
  489. node.parent,
  490. {
  491. ...head.value,
  492. autogrouped_by: {
  493. op: head.value && 'op' in head.value ? head.value.op ?? '' : '',
  494. },
  495. },
  496. {
  497. event_id: undefined,
  498. project_slug: undefined,
  499. },
  500. head,
  501. tail
  502. );
  503. if (!node.parent) {
  504. throw new Error('Parent node is missing, this should be unreachable code');
  505. }
  506. autoGroupedNode.groupCount = groupMatchCount + 1;
  507. autoGroupedNode.errored_children = erroredChildren;
  508. autoGroupedNode.space = [
  509. Math.min(head.value.start_timestamp, tail.value.timestamp) *
  510. autoGroupedNode.multiplier,
  511. Math.max(
  512. tail.value.timestamp - head.value.start_timestamp,
  513. head.value.timestamp - tail.value.timestamp
  514. ) * autoGroupedNode.multiplier,
  515. ];
  516. for (const c of tail.children) {
  517. c.parent = autoGroupedNode;
  518. queue.push(c);
  519. }
  520. const index = node.parent.children.indexOf(node);
  521. node.parent.children[index] = autoGroupedNode;
  522. }
  523. }
  524. static AutogroupSiblingSpanNodes(root: TraceTreeNode<TraceTree.NodeValue>): void {
  525. const queue = [root];
  526. while (queue.length > 0) {
  527. const node = queue.pop()!;
  528. if (node.children.length < 5) {
  529. for (const child of node.children) {
  530. queue.push(child);
  531. }
  532. continue;
  533. }
  534. let index = 0;
  535. let matchCount = 0;
  536. while (index < node.children.length) {
  537. const current = node.children[index] as TraceTreeNode<TraceTree.Span>;
  538. const next = node.children[index + 1] as TraceTreeNode<TraceTree.Span>;
  539. if (
  540. next &&
  541. next.children.length === 0 &&
  542. current.children.length === 0 &&
  543. next.value.op === current.value.op &&
  544. next.value.description === current.value.description
  545. ) {
  546. matchCount++;
  547. // If the next node is the last node in the list, we keep iterating
  548. if (index + 1 < node.children.length) {
  549. index++;
  550. continue;
  551. }
  552. }
  553. if (matchCount >= 4) {
  554. const autoGroupedNode = new SiblingAutogroupNode(
  555. node,
  556. {
  557. ...current.value,
  558. autogrouped_by: {
  559. op: current.value.op ?? '',
  560. description: current.value.description ?? '',
  561. },
  562. },
  563. {
  564. event_id: undefined,
  565. project_slug: undefined,
  566. }
  567. );
  568. autoGroupedNode.groupCount = matchCount + 1;
  569. const start = index - matchCount;
  570. let start_timestamp = Number.MAX_SAFE_INTEGER;
  571. let timestamp = Number.MIN_SAFE_INTEGER;
  572. for (let j = start; j < start + matchCount + 1; j++) {
  573. const child = node.children[j];
  574. if (
  575. child.value &&
  576. 'timestamp' in child.value &&
  577. typeof child.value.timestamp === 'number' &&
  578. child.value.timestamp > timestamp
  579. ) {
  580. timestamp = child.value.timestamp;
  581. }
  582. if (
  583. child.value &&
  584. 'start_timestamp' in child.value &&
  585. typeof child.value.start_timestamp === 'number' &&
  586. child.value.start_timestamp > start_timestamp
  587. ) {
  588. start_timestamp = child.value.start_timestamp;
  589. }
  590. if (!isSpanNode(child)) {
  591. throw new TypeError(
  592. 'Expected child of autogrouped node to be a span node.'
  593. );
  594. }
  595. if (child.hasErrors()) {
  596. autoGroupedNode.errored_children.push(child);
  597. }
  598. autoGroupedNode.children.push(node.children[j]);
  599. autoGroupedNode.children[autoGroupedNode.children.length - 1].parent =
  600. autoGroupedNode;
  601. }
  602. autoGroupedNode.space = [
  603. start_timestamp * autoGroupedNode.multiplier,
  604. (timestamp - start_timestamp) * autoGroupedNode.multiplier,
  605. ];
  606. node.children.splice(start, matchCount + 1, autoGroupedNode);
  607. index = start + 1;
  608. matchCount = 0;
  609. } else {
  610. index++;
  611. matchCount = 0;
  612. }
  613. }
  614. }
  615. }
  616. collectMeasurements(
  617. start_timestamp: number,
  618. measurements: Record<string, Measurement>
  619. ): TraceTree.Indicator[] {
  620. const indicators: TraceTree.Indicator[] = [];
  621. for (const measurement of RENDERABLE_MEASUREMENTS) {
  622. const value = measurements[measurement];
  623. if (!value) {
  624. continue;
  625. }
  626. const timestamp = measurementToTimestamp(
  627. start_timestamp,
  628. value.value,
  629. value.unit ?? 'milliseconds'
  630. );
  631. indicators.push({
  632. start: timestamp,
  633. duration: 0,
  634. measurement: value,
  635. type: measurement as TraceTree.Indicator['type'],
  636. label: measurement.toUpperCase(),
  637. });
  638. }
  639. return indicators;
  640. }
  641. // Returns boolean to indicate if node was updated
  642. expand(node: TraceTreeNode<TraceTree.NodeValue>, expanded: boolean): boolean {
  643. if (expanded === node.expanded) {
  644. return false;
  645. }
  646. // Expanding is not allowed for zoomed in nodes
  647. if (node.zoomedIn) {
  648. return false;
  649. }
  650. if (node instanceof ParentAutogroupNode) {
  651. // In parent autogrouping, we perform a node swap and either point the
  652. // head or tails of the autogrouped sequence to the autogrouped node
  653. if (node.expanded) {
  654. const index = this._list.indexOf(node);
  655. const autogroupedChildren = node.getVisibleChildren();
  656. this._list.splice(index + 1, autogroupedChildren.length);
  657. const newChildren = node.tail.getVisibleChildren();
  658. for (const c of node.tail.children) {
  659. c.parent = node;
  660. }
  661. this._list.splice(index + 1, 0, ...newChildren);
  662. } else {
  663. node.head.parent = node;
  664. const index = this._list.indexOf(node);
  665. const childrenCount = node.getVisibleChildrenCount();
  666. this._list.splice(index + 1, childrenCount);
  667. node.getVisibleChildrenCount();
  668. const newChildren = [node.head].concat(
  669. node.head.getVisibleChildren() as TraceTreeNode<TraceTree.Span>[]
  670. );
  671. for (const c of node.children) {
  672. c.parent = node.tail;
  673. }
  674. this._list.splice(index + 1, 0, ...newChildren);
  675. }
  676. node.invalidate(node);
  677. node.expanded = expanded;
  678. return true;
  679. }
  680. if (node.expanded) {
  681. const index = this._list.indexOf(node);
  682. this._list.splice(index + 1, node.getVisibleChildrenCount());
  683. // Flip expanded after collecting visible children
  684. node.expanded = expanded;
  685. } else {
  686. const index = this._list.indexOf(node);
  687. // Flip expanded so that we can collect visible children
  688. node.expanded = expanded;
  689. this._list.splice(index + 1, 0, ...node.getVisibleChildren());
  690. }
  691. node.expanded = expanded;
  692. return true;
  693. }
  694. zoomIn(
  695. node: TraceTreeNode<TraceTree.NodeValue>,
  696. zoomedIn: boolean,
  697. options: {
  698. api: Client;
  699. organization: Organization;
  700. }
  701. ): Promise<Event | null> {
  702. if (zoomedIn === node.zoomedIn) {
  703. return Promise.resolve(null);
  704. }
  705. if (!zoomedIn) {
  706. const index = this._list.indexOf(node);
  707. const childrenCount = node.getVisibleChildrenCount();
  708. this._list.splice(index + 1, childrenCount);
  709. node.zoomedIn = zoomedIn;
  710. node.invalidate(node);
  711. if (node.expanded) {
  712. this._list.splice(index + 1, 0, ...node.getVisibleChildren());
  713. }
  714. return Promise.resolve(null);
  715. }
  716. const key = cacheKey(
  717. options.organization,
  718. node.metadata.project_slug!,
  719. node.metadata.event_id!
  720. );
  721. const promise =
  722. this._spanPromises.get(key) ??
  723. fetchTransactionSpans(
  724. options.api,
  725. options.organization,
  726. node.metadata.project_slug!,
  727. node.metadata.event_id!
  728. );
  729. node.fetchStatus = 'loading';
  730. promise
  731. .then(data => {
  732. node.fetchStatus = 'resolved';
  733. const spans = data.entries.find(s => s.type === 'spans');
  734. if (!spans) {
  735. return data;
  736. }
  737. // Remove existing entries from the list
  738. const index = this._list.indexOf(node);
  739. if (node.expanded) {
  740. const childrenCount = node.getVisibleChildrenCount();
  741. if (childrenCount > 0) {
  742. this._list.splice(index + 1, childrenCount);
  743. }
  744. }
  745. // Api response is not sorted
  746. if (spans.data) {
  747. spans.data.sort((a, b) => a.start_timestamp - b.start_timestamp);
  748. }
  749. TraceTree.FromSpans(node, data, spans.data, {sdk: data.sdk?.name});
  750. const spanChildren = node.getVisibleChildren();
  751. this._list.splice(index + 1, 0, ...spanChildren);
  752. return data;
  753. })
  754. .catch(_e => {
  755. node.fetchStatus = 'error';
  756. });
  757. this._spanPromises.set(key, promise);
  758. return promise;
  759. }
  760. toList(): TraceTreeNode<TraceTree.NodeValue>[] {
  761. const list: TraceTreeNode<TraceTree.NodeValue>[] = [];
  762. function visit(node: TraceTreeNode<TraceTree.NodeValue>) {
  763. list.push(node);
  764. if (!node.expanded) {
  765. return;
  766. }
  767. for (const child of node.children) {
  768. visit(child);
  769. }
  770. }
  771. for (const child of this.root.children) {
  772. visit(child);
  773. }
  774. return list;
  775. }
  776. get list(): ReadonlyArray<TraceTreeNode<TraceTree.NodeValue>> {
  777. return this._list;
  778. }
  779. /**
  780. * Prints the tree in a human readable format, useful for debugging and testing
  781. */
  782. print() {
  783. // root nodes are -1 indexed, so we add 1 to the depth so .repeat doesnt throw
  784. const print = this.list
  785. .map(t => printNode(t, 0))
  786. .filter(Boolean)
  787. .join('\n');
  788. // eslint-disable-next-line no-console
  789. console.log(print);
  790. }
  791. build() {
  792. this._list = this.toList();
  793. return this;
  794. }
  795. }
  796. export class TraceTreeNode<T extends TraceTree.NodeValue> {
  797. canFetch: boolean = false;
  798. fetchStatus: 'resolved' | 'error' | 'idle' | 'loading' = 'idle';
  799. parent: TraceTreeNode<TraceTree.NodeValue> | null = null;
  800. value: T;
  801. expanded: boolean = false;
  802. zoomedIn: boolean = false;
  803. metadata: TraceTree.Metadata = {
  804. project_slug: undefined,
  805. event_id: undefined,
  806. };
  807. space: [number, number] | null = null;
  808. multiplier: number;
  809. private unit: 'milliseconds' = 'milliseconds';
  810. private _depth: number | undefined;
  811. private _children: TraceTreeNode<TraceTree.NodeValue>[] = [];
  812. private _spanChildren: TraceTreeNode<
  813. TraceTree.Span | TraceTree.MissingInstrumentationSpan
  814. >[] = [];
  815. private _connectors: number[] | undefined = undefined;
  816. constructor(
  817. parent: TraceTreeNode<TraceTree.NodeValue> | null,
  818. value: T,
  819. metadata: TraceTree.Metadata
  820. ) {
  821. this.parent = parent ?? null;
  822. this.value = value;
  823. this.metadata = metadata;
  824. this.multiplier = this.unit === 'milliseconds' ? 1e3 : 1;
  825. if (value && 'timestamp' in value && 'start_timestamp' in value) {
  826. this.space = [
  827. value.start_timestamp * this.multiplier,
  828. (value.timestamp - value.start_timestamp) * this.multiplier,
  829. ];
  830. }
  831. if (
  832. isTraceErrorNode(this) &&
  833. 'timestamp' in this.value &&
  834. typeof this.value.timestamp === 'number'
  835. ) {
  836. this.space = [this.value.timestamp * this.multiplier, 0];
  837. }
  838. if (isTransactionNode(this) || isTraceNode(this) || isSpanNode(this)) {
  839. this.expanded = true;
  840. }
  841. if (shouldCollapseNodeByDefault(this)) {
  842. this.expanded = false;
  843. }
  844. }
  845. cloneDeep(): TraceTreeNode<T> | ParentAutogroupNode | SiblingAutogroupNode {
  846. let node: TraceTreeNode<T> | ParentAutogroupNode | SiblingAutogroupNode;
  847. if (isParentAutogroupedNode(this)) {
  848. node = new ParentAutogroupNode(
  849. this.parent,
  850. this.value,
  851. this.metadata,
  852. this.head,
  853. this.tail
  854. );
  855. node.groupCount = this.groupCount;
  856. } else {
  857. node = new TraceTreeNode(this.parent, this.value, this.metadata);
  858. }
  859. if (!node) {
  860. throw new Error('CloneDeep is not implemented');
  861. }
  862. node.expanded = this.expanded;
  863. node.zoomedIn = this.zoomedIn;
  864. node.canFetch = this.canFetch;
  865. node.space = this.space;
  866. node.metadata = this.metadata;
  867. if (isParentAutogroupedNode(node)) {
  868. node.head = node.head.cloneDeep() as TraceTreeNode<TraceTree.Span>;
  869. node.tail = node.tail.cloneDeep() as TraceTreeNode<TraceTree.Span>;
  870. node.head.parent = node;
  871. // If the node is not expanded, the parent of the tail points to the
  872. // autogrouped node. If the node is expanded, the parent of the children
  873. // of the tail points to the autogrouped node.
  874. if (!node.expanded) {
  875. for (const c of node.tail.children) {
  876. c.parent = node;
  877. }
  878. } else {
  879. for (const c of node.children) {
  880. c.parent = node.tail;
  881. }
  882. }
  883. node.head.parent = node;
  884. node.tail.parent = node;
  885. } else {
  886. for (const child of this.children) {
  887. const childClone = child.cloneDeep() as TraceTreeNode<TraceTree.Span>;
  888. node.children.push(childClone);
  889. childClone.parent = node;
  890. }
  891. }
  892. return node;
  893. }
  894. get isOrphaned() {
  895. return this.parent?.value && 'orphan_errors' in this.parent.value;
  896. }
  897. get isLastChild() {
  898. if (!this.parent || this.parent.children.length === 0) {
  899. return true;
  900. }
  901. return this.parent.children[this.parent.children.length - 1] === this;
  902. }
  903. /**
  904. * Return a lazily calculated depth of the node in the tree.
  905. * Root node has a value of -1 as it is abstract.
  906. */
  907. get depth(): number {
  908. if (typeof this._depth === 'number') {
  909. return this._depth;
  910. }
  911. let depth = -2;
  912. let node: TraceTreeNode<any> | null = this;
  913. while (node) {
  914. if (typeof node.parent?.depth === 'number') {
  915. this._depth = node.parent.depth + 1;
  916. return this._depth;
  917. }
  918. depth++;
  919. node = node.parent;
  920. }
  921. this._depth = depth;
  922. return this._depth;
  923. }
  924. hasErrors(): boolean {
  925. return (
  926. this.value &&
  927. (('errors' in this.value && this.value.errors.length > 0) ||
  928. ('performance_issues' in this.value && this.value.performance_issues.length > 0))
  929. );
  930. }
  931. /**
  932. * Returns the depth levels at which the row should draw vertical connectors
  933. * negative values mean connector points to an orphaned node
  934. */
  935. get connectors(): number[] {
  936. if (this._connectors !== undefined) {
  937. return this._connectors!;
  938. }
  939. this._connectors = [];
  940. if (!this.parent) {
  941. return this._connectors;
  942. }
  943. if (this.parent?.connectors !== undefined) {
  944. this._connectors = [...this.parent.connectors];
  945. if (this.isLastChild || this.value === null) {
  946. return this._connectors;
  947. }
  948. this.connectors.push(this.isOrphaned ? -this.depth : this.depth);
  949. return this._connectors;
  950. }
  951. let node: TraceTreeNode<T> | TraceTreeNode<TraceTree.NodeValue> | null = this.parent;
  952. while (node) {
  953. if (node.value === null) {
  954. break;
  955. }
  956. if (node.isLastChild) {
  957. node = node.parent;
  958. continue;
  959. }
  960. this._connectors.push(node.isOrphaned ? -node.depth : node.depth);
  961. node = node.parent;
  962. }
  963. return this._connectors;
  964. }
  965. /**
  966. * Returns the children that the node currently points to.
  967. * The logic here is a consequence of the tree design, where we want to be able to store
  968. * both transaction and span nodes in the same tree. This results in an annoying API where
  969. * we either store span children separately or transaction children separately. A better design
  970. * would have been to create an invisible meta node that always points to the correct children.
  971. */
  972. get children(): TraceTreeNode<TraceTree.NodeValue>[] {
  973. if (isAutogroupedNode(this)) {
  974. return this._children;
  975. }
  976. if (isSpanNode(this)) {
  977. return this.canFetch && !this.zoomedIn ? [] : this.spanChildren;
  978. }
  979. if (isTransactionNode(this)) {
  980. return this.zoomedIn ? this._spanChildren : this._children;
  981. }
  982. return this._children;
  983. }
  984. set children(children: TraceTreeNode<TraceTree.NodeValue>[]) {
  985. this._children = children;
  986. }
  987. get spanChildren(): TraceTreeNode<
  988. TraceTree.Span | TraceTree.MissingInstrumentationSpan
  989. >[] {
  990. return this._spanChildren;
  991. }
  992. /**
  993. * Invalidate the visual data used to render the tree, forcing it
  994. * to be recalculated on the next render. This is useful when for example
  995. * the tree is expanded or collapsed, or when the tree is mutated and
  996. * the visual data is no longer valid as the indentation changes
  997. */
  998. invalidate(root?: TraceTreeNode<TraceTree.NodeValue>) {
  999. this._connectors = undefined;
  1000. this._depth = undefined;
  1001. if (root) {
  1002. const queue = [...this.children];
  1003. if (isParentAutogroupedNode(this)) {
  1004. queue.push(this.head);
  1005. }
  1006. while (queue.length > 0) {
  1007. const next = queue.pop()!;
  1008. next.invalidate();
  1009. if (isParentAutogroupedNode(next)) {
  1010. queue.push(next.head);
  1011. }
  1012. for (let i = 0; i < next.children.length; i++) {
  1013. queue.push(next.children[i]);
  1014. }
  1015. }
  1016. }
  1017. }
  1018. getVisibleChildrenCount(): number {
  1019. const stack: TraceTreeNode<TraceTree.NodeValue>[] = [];
  1020. let count = 0;
  1021. if (
  1022. this.expanded ||
  1023. isParentAutogroupedNode(this) ||
  1024. isMissingInstrumentationNode(this)
  1025. ) {
  1026. for (let i = this.children.length - 1; i >= 0; i--) {
  1027. stack.push(this.children[i]);
  1028. }
  1029. }
  1030. while (stack.length > 0) {
  1031. const node = stack.pop()!;
  1032. count++;
  1033. // Since we're using a stack and it's LIFO, reverse the children before pushing them
  1034. // to ensure they are processed in the original left-to-right order.
  1035. if (node.expanded || isParentAutogroupedNode(node)) {
  1036. for (let i = node.children.length - 1; i >= 0; i--) {
  1037. stack.push(node.children[i]);
  1038. }
  1039. }
  1040. }
  1041. return count;
  1042. }
  1043. getVisibleChildren(): TraceTreeNode<TraceTree.NodeValue>[] {
  1044. const stack: TraceTreeNode<TraceTree.NodeValue>[] = [];
  1045. const children: TraceTreeNode<TraceTree.NodeValue>[] = [];
  1046. if (
  1047. this.expanded ||
  1048. isParentAutogroupedNode(this) ||
  1049. isMissingInstrumentationNode(this)
  1050. ) {
  1051. for (let i = this.children.length - 1; i >= 0; i--) {
  1052. stack.push(this.children[i]);
  1053. }
  1054. }
  1055. while (stack.length > 0) {
  1056. const node = stack.pop()!;
  1057. children.push(node);
  1058. // Since we're using a stack and it's LIFO, reverse the children before pushing them
  1059. // to ensure they are processed in the original left-to-right order.
  1060. if (node.expanded || isParentAutogroupedNode(node)) {
  1061. for (let i = node.children.length - 1; i >= 0; i--) {
  1062. stack.push(node.children[i]);
  1063. }
  1064. }
  1065. }
  1066. return children;
  1067. }
  1068. // Returns the min path required to reach the node from the root.
  1069. // @TODO: skip nodes that do not require fetching
  1070. get path(): TraceTree.NodePath[] {
  1071. const nodes: TraceTreeNode<TraceTree.NodeValue>[] = [this];
  1072. let current: TraceTreeNode<TraceTree.NodeValue> | null = this.parent;
  1073. if (isSpanNode(this) || isAutogroupedNode(this)) {
  1074. while (
  1075. current &&
  1076. (isSpanNode(current) || (isAutogroupedNode(current) && !current.expanded))
  1077. ) {
  1078. current = current.parent;
  1079. }
  1080. }
  1081. while (current) {
  1082. if (isTransactionNode(current)) {
  1083. nodes.push(current);
  1084. }
  1085. if (isSpanNode(current)) {
  1086. nodes.push(current);
  1087. while (current.parent) {
  1088. if (isTransactionNode(current.parent)) {
  1089. break;
  1090. }
  1091. if (isAutogroupedNode(current.parent) && current.parent.expanded) {
  1092. break;
  1093. }
  1094. current = current.parent;
  1095. }
  1096. }
  1097. if (isAutogroupedNode(current)) {
  1098. nodes.push(current);
  1099. }
  1100. current = current.parent;
  1101. }
  1102. return nodes.map(nodeToId);
  1103. }
  1104. print() {
  1105. // root nodes are -1 indexed, so we add 1 to the depth so .repeat doesnt throw
  1106. const offset = this.depth === -1 ? 1 : 0;
  1107. const nodes = [this, ...this.getVisibleChildren()];
  1108. const print = nodes
  1109. .map(t => printNode(t, offset))
  1110. .filter(Boolean)
  1111. .join('\n');
  1112. // eslint-disable-next-line no-console
  1113. console.log(print);
  1114. }
  1115. static Find(
  1116. root: TraceTreeNode<TraceTree.NodeValue>,
  1117. predicate: (node: TraceTreeNode<TraceTree.NodeValue>) => boolean
  1118. ): TraceTreeNode<TraceTree.NodeValue> | null {
  1119. const queue = [root];
  1120. while (queue.length > 0) {
  1121. const next = queue.pop()!;
  1122. if (predicate(next)) return next;
  1123. for (const child of next.children) {
  1124. queue.push(child);
  1125. }
  1126. }
  1127. return null;
  1128. }
  1129. static Root() {
  1130. return new TraceTreeNode(null, null, {
  1131. event_id: undefined,
  1132. project_slug: undefined,
  1133. });
  1134. }
  1135. }
  1136. export class MissingInstrumentationNode extends TraceTreeNode<TraceTree.MissingInstrumentationSpan> {
  1137. next: TraceTreeNode<TraceTree.Span>;
  1138. previous: TraceTreeNode<TraceTree.Span>;
  1139. constructor(
  1140. parent: TraceTreeNode<TraceTree.NodeValue>,
  1141. node: TraceTree.MissingInstrumentationSpan,
  1142. metadata: TraceTree.Metadata,
  1143. previous: TraceTreeNode<TraceTree.Span>,
  1144. next: TraceTreeNode<TraceTree.Span>
  1145. ) {
  1146. super(parent, node, metadata);
  1147. this.next = next;
  1148. this.previous = previous;
  1149. }
  1150. }
  1151. export class ParentAutogroupNode extends TraceTreeNode<TraceTree.ChildrenAutogroup> {
  1152. head: TraceTreeNode<TraceTree.Span>;
  1153. tail: TraceTreeNode<TraceTree.Span>;
  1154. errored_children: TraceTreeNode<TraceTree.NodeValue>[] = [];
  1155. groupCount: number = 0;
  1156. private _autogroupedSegments: [number, number][] | undefined;
  1157. constructor(
  1158. parent: TraceTreeNode<TraceTree.NodeValue> | null,
  1159. node: TraceTree.ChildrenAutogroup,
  1160. metadata: TraceTree.Metadata,
  1161. head: TraceTreeNode<TraceTree.Span>,
  1162. tail: TraceTreeNode<TraceTree.Span>
  1163. ) {
  1164. super(parent, node, metadata);
  1165. this.expanded = false;
  1166. this.head = head;
  1167. this.tail = tail;
  1168. }
  1169. get children() {
  1170. if (this.expanded) {
  1171. return [this.head];
  1172. }
  1173. return this.tail.children;
  1174. }
  1175. get has_error(): boolean {
  1176. return this.errored_children.length > 0;
  1177. }
  1178. get autogroupedSegments(): [number, number][] {
  1179. if (this._autogroupedSegments) {
  1180. return this._autogroupedSegments;
  1181. }
  1182. const children: TraceTreeNode<TraceTree.NodeValue>[] = [];
  1183. let start: TraceTreeNode<TraceTree.NodeValue> | undefined = this.head;
  1184. while (start && start !== this.tail) {
  1185. children.push(start);
  1186. start = start.children[0];
  1187. }
  1188. children.push(this.tail);
  1189. this._autogroupedSegments = computeAutogroupedBarSegments(children);
  1190. return this._autogroupedSegments;
  1191. }
  1192. }
  1193. export class SiblingAutogroupNode extends TraceTreeNode<TraceTree.SiblingAutogroup> {
  1194. groupCount: number = 0;
  1195. errored_children: TraceTreeNode<TraceTree.NodeValue>[] = [];
  1196. private _autogroupedSegments: [number, number][] | undefined;
  1197. constructor(
  1198. parent: TraceTreeNode<TraceTree.NodeValue> | null,
  1199. node: TraceTree.SiblingAutogroup,
  1200. metadata: TraceTree.Metadata
  1201. ) {
  1202. super(parent, node, metadata);
  1203. this.expanded = false;
  1204. }
  1205. get has_error(): boolean {
  1206. return this.errored_children.length > 0;
  1207. }
  1208. get autogroupedSegments(): [number, number][] {
  1209. if (this._autogroupedSegments) {
  1210. return this._autogroupedSegments;
  1211. }
  1212. this._autogroupedSegments = computeAutogroupedBarSegments(this.children);
  1213. return this._autogroupedSegments;
  1214. }
  1215. }
  1216. function partialTransaction(
  1217. partial: Partial<TraceTree.Transaction>
  1218. ): TraceTree.Transaction {
  1219. return {
  1220. start_timestamp: 0,
  1221. timestamp: 0,
  1222. errors: [],
  1223. performance_issues: [],
  1224. parent_span_id: '',
  1225. span_id: '',
  1226. parent_event_id: '',
  1227. project_id: 0,
  1228. 'transaction.duration': 0,
  1229. 'transaction.op': 'db',
  1230. 'transaction.status': 'ok',
  1231. generation: 0,
  1232. project_slug: '',
  1233. event_id: `event_id`,
  1234. transaction: `transaction`,
  1235. children: [],
  1236. ...partial,
  1237. };
  1238. }
  1239. export function makeExampleTrace(metadata: TraceTree.Metadata): TraceTree {
  1240. const trace: TraceTree.Trace = {
  1241. transactions: [],
  1242. orphan_errors: [],
  1243. };
  1244. function randomBetween(min: number, max: number) {
  1245. return Math.floor(Math.random() * (max - min + 1) + min);
  1246. }
  1247. let start = new Date().getTime();
  1248. const root = partialTransaction({
  1249. ...metadata,
  1250. generation: 0,
  1251. start_timestamp: start,
  1252. transaction: 'root transaction',
  1253. timestamp: start + randomBetween(100, 200),
  1254. });
  1255. trace.transactions.push(root);
  1256. for (let i = 0; i < 50; i++) {
  1257. const end = start + randomBetween(100, 200);
  1258. const nest = i > 0 && Math.random() > 0.33;
  1259. if (nest) {
  1260. const parent = root.children[root.children.length - 1];
  1261. parent.children.push(
  1262. partialTransaction({
  1263. ...metadata,
  1264. generation: 0,
  1265. start_timestamp: start,
  1266. transaction: `parent transaction ${i}`,
  1267. timestamp: end,
  1268. })
  1269. );
  1270. parent.timestamp = end;
  1271. } else {
  1272. root.children.push(
  1273. partialTransaction({
  1274. ...metadata,
  1275. generation: 0,
  1276. start_timestamp: start,
  1277. transaction: 'loading...',
  1278. ['transaction.op']: 'loading',
  1279. timestamp: end,
  1280. })
  1281. );
  1282. }
  1283. start = end;
  1284. }
  1285. const tree = TraceTree.FromTrace(trace);
  1286. return tree;
  1287. }
  1288. function nodeToId(n: TraceTreeNode<TraceTree.NodeValue>): TraceTree.NodePath {
  1289. if (isTransactionNode(n)) {
  1290. return `txn:${n.value.event_id}`;
  1291. }
  1292. if (isSpanNode(n)) {
  1293. return `span:${n.value.span_id}`;
  1294. }
  1295. if (isAutogroupedNode(n)) {
  1296. if (isParentAutogroupedNode(n)) {
  1297. return `ag:${n.head.value.span_id}`;
  1298. }
  1299. if (isSiblingAutogroupedNode(n)) {
  1300. const child = n.children[0];
  1301. if (isSpanNode(child)) {
  1302. return `ag:${child.value.span_id}`;
  1303. }
  1304. }
  1305. }
  1306. if (isTraceNode(n)) {
  1307. return `trace:root`;
  1308. }
  1309. if (isTraceErrorNode(n)) {
  1310. return `error:${n.value.event_id}`;
  1311. }
  1312. if (isRootNode(n)) {
  1313. throw new Error('A path to root node does not exist as the node is virtual');
  1314. }
  1315. if (isMissingInstrumentationNode(n)) {
  1316. if (n.previous) {
  1317. return `ms:${n.previous.value.span_id}`;
  1318. }
  1319. if (n.next) {
  1320. return `ms:${n.next.value.span_id}`;
  1321. }
  1322. throw new Error('Missing instrumentation node must have a previous or next node');
  1323. }
  1324. throw new Error('Not implemented');
  1325. }
  1326. export function computeAutogroupedBarSegments(
  1327. nodes: TraceTreeNode<TraceTree.NodeValue>[]
  1328. ): [number, number][] {
  1329. if (nodes.length === 0) {
  1330. return [];
  1331. }
  1332. if (nodes.length === 1) {
  1333. const space = nodes[0].space;
  1334. if (!space) {
  1335. throw new Error(
  1336. 'Autogrouped node child has no defined space. This should not happen.'
  1337. );
  1338. }
  1339. return [space];
  1340. }
  1341. const first = nodes[0];
  1342. const multiplier = first.multiplier;
  1343. if (!isSpanNode(first)) {
  1344. throw new Error('Autogrouped node must have span children');
  1345. }
  1346. const segments: [number, number][] = [];
  1347. let start = first.value.start_timestamp;
  1348. let end = first.value.timestamp;
  1349. let i = 1;
  1350. while (i < nodes.length) {
  1351. const next = nodes[i];
  1352. if (!isSpanNode(next)) {
  1353. throw new Error('Autogrouped node must have span children');
  1354. }
  1355. if (next.value.start_timestamp > end) {
  1356. segments.push([start * multiplier, (end - start) * multiplier]);
  1357. start = next.value.start_timestamp;
  1358. end = next.value.timestamp;
  1359. i++;
  1360. } else {
  1361. end = next.value.timestamp;
  1362. i++;
  1363. }
  1364. }
  1365. segments.push([start * multiplier, (end - start) * multiplier]);
  1366. return segments;
  1367. }
  1368. // Returns a list of errors related to the txn with ids matching the span id
  1369. function getRelatedSpanErrorsFromTransaction(
  1370. span: RawSpanType,
  1371. node?: TraceTreeNode<TraceTree.NodeValue>
  1372. ): TraceErrorType[] {
  1373. if (!node || !node.value || !isTransactionNode(node)) {
  1374. return [];
  1375. }
  1376. if (!node?.value?.errors?.length) {
  1377. return [];
  1378. }
  1379. const errors: TraceErrorType[] = [];
  1380. for (const error of node.value.errors) {
  1381. if (error.span === span.span_id) {
  1382. errors.push(error);
  1383. }
  1384. }
  1385. return errors;
  1386. }
  1387. // Returns a list of performance errors related to the txn with ids matching the span id
  1388. function getRelatedPerformanceIssuesFromTransaction(
  1389. span: RawSpanType,
  1390. node?: TraceTreeNode<TraceTree.NodeValue>
  1391. ): TracePerformanceIssue[] {
  1392. if (!node || !node.value || !isTransactionNode(node)) {
  1393. return [];
  1394. }
  1395. if (!node?.value?.performance_issues?.length && !node?.value?.errors?.length) {
  1396. return [];
  1397. }
  1398. const performanceIssues: TracePerformanceIssue[] = [];
  1399. for (const perfIssue of node.value.performance_issues) {
  1400. for (const s of perfIssue.span) {
  1401. if (s === span.span_id) {
  1402. performanceIssues.push(perfIssue);
  1403. }
  1404. }
  1405. for (const suspect of perfIssue.suspect_spans) {
  1406. if (suspect === span.span_id) {
  1407. performanceIssues.push(perfIssue);
  1408. }
  1409. }
  1410. }
  1411. return performanceIssues;
  1412. }
  1413. function printNode(t: TraceTreeNode<TraceTree.NodeValue>, offset: number): string {
  1414. // +1 because we may be printing from the root which is -1 indexed
  1415. const padding = ' '.repeat(t.depth + offset);
  1416. if (isAutogroupedNode(t)) {
  1417. if (isParentAutogroupedNode(t)) {
  1418. return padding + `parent autogroup (${t.groupCount})`;
  1419. }
  1420. if (isSiblingAutogroupedNode(t)) {
  1421. return padding + `sibling autogroup (${t.groupCount})`;
  1422. }
  1423. return padding + 'autogroup';
  1424. }
  1425. if (isSpanNode(t)) {
  1426. return padding + (t.value.op || t.value.span_id || 'unknown span');
  1427. }
  1428. if (isTransactionNode(t)) {
  1429. return padding + (t.value.transaction || 'unknown transaction');
  1430. }
  1431. if (isMissingInstrumentationNode(t)) {
  1432. return padding + 'missing_instrumentation';
  1433. }
  1434. if (isRootNode(t)) {
  1435. return padding + 'Root';
  1436. }
  1437. if (isTraceNode(t)) {
  1438. return padding + 'Trace';
  1439. }
  1440. if (isTraceErrorNode(t)) {
  1441. return padding + (t.value.event_id || t.value.level) || 'unknown trace error';
  1442. }
  1443. return 'unknown node';
  1444. }