traceTree.tsx 82 KB

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