traceTree.tsx 68 KB

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