traceTree.tsx 67 KB

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