traceTree.tsx 73 KB

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