traceTree.tsx 73 KB

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