traceTree.tsx 83 KB

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