traceTree.tsx 64 KB

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