traceTree.tsx 74 KB

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