traceTree.tsx 83 KB

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