traceTree.tsx 67 KB

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