traceTree.tsx 63 KB

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