traceTree.tsx 56 KB

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