traceTree.tsx 73 KB

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