traceTree.tsx 51 KB

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