traceTree.tsx 69 KB

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