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. if (!isSpanNode(node.children[index])) {
  681. index++;
  682. matchCount = 0;
  683. continue;
  684. }
  685. const current = node.children[index] as TraceTreeNode<TraceTree.Span>;
  686. const next = node.children[index + 1] as TraceTreeNode<TraceTree.Span>;
  687. if (
  688. next &&
  689. isSpanNode(next) &&
  690. next.children.length === 0 &&
  691. current.children.length === 0 &&
  692. next.value.op === current.value.op &&
  693. next.value.description === current.value.description
  694. ) {
  695. matchCount++;
  696. // If the next node is the last node in the list, we keep iterating
  697. if (index + 1 < node.children.length) {
  698. index++;
  699. continue;
  700. }
  701. }
  702. if (matchCount >= 4) {
  703. const autoGroupedNode = new SiblingAutogroupNode(
  704. node,
  705. {
  706. ...current.value,
  707. autogrouped_by: {
  708. op: current.value.op ?? '',
  709. description: current.value.description ?? '',
  710. },
  711. },
  712. {
  713. event_id: undefined,
  714. project_slug: undefined,
  715. }
  716. );
  717. autoGroupedNode.groupCount = matchCount + 1;
  718. const start = index - matchCount;
  719. let start_timestamp = Number.MAX_SAFE_INTEGER;
  720. let timestamp = Number.MIN_SAFE_INTEGER;
  721. for (let j = start; j < start + matchCount + 1; j++) {
  722. const child = node.children[j];
  723. if (
  724. child.value &&
  725. 'timestamp' in child.value &&
  726. typeof child.value.timestamp === 'number' &&
  727. child.value.timestamp > timestamp
  728. ) {
  729. timestamp = child.value.timestamp;
  730. }
  731. if (
  732. child.value &&
  733. 'start_timestamp' in child.value &&
  734. typeof child.value.start_timestamp === 'number' &&
  735. child.value.start_timestamp < start_timestamp
  736. ) {
  737. start_timestamp = child.value.start_timestamp;
  738. }
  739. if (child.has_errors) {
  740. for (const error of child.errors) {
  741. autoGroupedNode.errors.add(error);
  742. }
  743. for (const performanceIssue of child.performance_issues) {
  744. autoGroupedNode.performance_issues.add(performanceIssue);
  745. }
  746. }
  747. autoGroupedNode.children.push(node.children[j]);
  748. autoGroupedNode.children[autoGroupedNode.children.length - 1].parent =
  749. autoGroupedNode;
  750. }
  751. autoGroupedNode.space = [
  752. start_timestamp * autoGroupedNode.multiplier,
  753. (timestamp - start_timestamp) * autoGroupedNode.multiplier,
  754. ];
  755. node.children.splice(start, matchCount + 1, autoGroupedNode);
  756. index = start + 1;
  757. matchCount = 0;
  758. } else {
  759. index++;
  760. matchCount = 0;
  761. }
  762. }
  763. }
  764. }
  765. collectMeasurements(
  766. node: TraceTreeNode<TraceTree.NodeValue>,
  767. start_timestamp: number,
  768. measurements: Record<string, Measurement>,
  769. vitals: Map<TraceTreeNode<TraceTree.NodeValue>, TraceTree.CollectedVital[]>,
  770. vital_types: Set<'web' | 'mobile'>,
  771. indicators: TraceTree.Indicator[]
  772. ): void {
  773. for (const measurement of COLLECTABLE_MEASUREMENTS) {
  774. const value = measurements[measurement];
  775. if (!value || typeof value.value !== 'number') {
  776. continue;
  777. }
  778. if (!vitals.has(node)) {
  779. vitals.set(node, []);
  780. }
  781. WEB_VITALS_LOOKUP.has(measurement) && vital_types.add('web');
  782. MOBILE_VITALS_LOOKUP.has(measurement) && vital_types.add('mobile');
  783. const vital = vitals.get(node)!;
  784. vital.push({
  785. key: measurement,
  786. measurement: value,
  787. });
  788. if (!RENDERABLE_MEASUREMENTS[measurement]) {
  789. continue;
  790. }
  791. const timestamp = measurementToTimestamp(
  792. start_timestamp,
  793. value.value,
  794. value.unit ?? 'millisecond'
  795. );
  796. indicators.push({
  797. start: timestamp,
  798. duration: 0,
  799. measurement: value,
  800. poor: MEASUREMENT_THRESHOLDS[measurement]
  801. ? value.value > MEASUREMENT_THRESHOLDS[measurement]
  802. : false,
  803. type: measurement as TraceTree.Indicator['type'],
  804. label: (MEASUREMENT_ACRONYM_MAPPING[measurement] ?? measurement).toUpperCase(),
  805. });
  806. }
  807. }
  808. // Returns boolean to indicate if node was updated
  809. expand(node: TraceTreeNode<TraceTree.NodeValue>, expanded: boolean): boolean {
  810. if (expanded === node.expanded) {
  811. return false;
  812. }
  813. // Expanding is not allowed for zoomed in nodes
  814. if (node.zoomedIn) {
  815. return false;
  816. }
  817. if (node instanceof ParentAutogroupNode) {
  818. // In parent autogrouping, we perform a node swap and either point the
  819. // head or tails of the autogrouped sequence to the autogrouped node
  820. if (node.expanded) {
  821. const index = this._list.indexOf(node);
  822. const autogroupedChildren = node.getVisibleChildren();
  823. this._list.splice(index + 1, autogroupedChildren.length);
  824. const newChildren = node.tail.getVisibleChildren();
  825. for (const c of node.tail.children) {
  826. c.parent = node;
  827. }
  828. this._list.splice(index + 1, 0, ...newChildren);
  829. } else {
  830. node.head.parent = node;
  831. const index = this._list.indexOf(node);
  832. const childrenCount = node.getVisibleChildrenCount();
  833. this._list.splice(index + 1, childrenCount);
  834. node.getVisibleChildrenCount();
  835. const newChildren = [node.head].concat(
  836. node.head.getVisibleChildren() as TraceTreeNode<TraceTree.Span>[]
  837. );
  838. for (const c of node.children) {
  839. c.parent = node.tail;
  840. }
  841. this._list.splice(index + 1, 0, ...newChildren);
  842. }
  843. node.invalidate(node);
  844. node.expanded = expanded;
  845. return true;
  846. }
  847. if (node.expanded) {
  848. const index = this._list.indexOf(node);
  849. this._list.splice(index + 1, node.getVisibleChildrenCount());
  850. // Flip expanded after collecting visible children
  851. node.expanded = expanded;
  852. } else {
  853. const index = this._list.indexOf(node);
  854. // Flip expanded so that we can collect visible children
  855. node.expanded = expanded;
  856. this._list.splice(index + 1, 0, ...node.getVisibleChildren());
  857. }
  858. node.expanded = expanded;
  859. return true;
  860. }
  861. zoomIn(
  862. node: TraceTreeNode<TraceTree.NodeValue>,
  863. zoomedIn: boolean,
  864. options: {
  865. api: Client;
  866. organization: Organization;
  867. }
  868. ): Promise<Event | null> {
  869. if (zoomedIn === node.zoomedIn) {
  870. return Promise.resolve(null);
  871. }
  872. if (!zoomedIn) {
  873. const index = this._list.indexOf(node);
  874. const childrenCount = node.getVisibleChildrenCount();
  875. this._list.splice(index + 1, childrenCount);
  876. node.zoomedIn = zoomedIn;
  877. node.invalidate(node);
  878. if (node.expanded) {
  879. this._list.splice(index + 1, 0, ...node.getVisibleChildren());
  880. }
  881. return Promise.resolve(null);
  882. }
  883. const key = cacheKey(
  884. options.organization,
  885. node.metadata.project_slug!,
  886. node.metadata.event_id!
  887. );
  888. const promise =
  889. this._spanPromises.get(key) ??
  890. fetchTransactionSpans(
  891. options.api,
  892. options.organization,
  893. node.metadata.project_slug!,
  894. node.metadata.event_id!
  895. );
  896. node.fetchStatus = 'loading';
  897. promise
  898. .then(data => {
  899. // The user may have collapsed the node before the promise resolved. When that
  900. // happens, dont update the tree with the resolved data. Alternatively, we could implement
  901. // a cancellable promise and avoid this cumbersome heuristic.
  902. node.fetchStatus = 'resolved';
  903. if (!node.expanded) {
  904. return data;
  905. }
  906. const spans = data.entries.find(s => s.type === 'spans') ?? {data: []};
  907. // Remove existing entries from the list
  908. const index = this._list.indexOf(node);
  909. if (node.expanded) {
  910. const childrenCount = node.getVisibleChildrenCount();
  911. if (childrenCount > 0) {
  912. this._list.splice(index + 1, childrenCount);
  913. }
  914. }
  915. // Api response is not sorted
  916. spans.data.sort((a, b) => a.start_timestamp - b.start_timestamp);
  917. TraceTree.FromSpans(node, data, spans.data, {sdk: data.sdk?.name});
  918. const spanChildren = node.getVisibleChildren();
  919. this._list.splice(index + 1, 0, ...spanChildren);
  920. return data;
  921. })
  922. .catch(_e => {
  923. node.fetchStatus = 'error';
  924. });
  925. this._spanPromises.set(key, promise);
  926. return promise;
  927. }
  928. toList(): TraceTreeNode<TraceTree.NodeValue>[] {
  929. const list: TraceTreeNode<TraceTree.NodeValue>[] = [];
  930. function visit(node: TraceTreeNode<TraceTree.NodeValue>) {
  931. list.push(node);
  932. if (!node.expanded) {
  933. return;
  934. }
  935. for (const child of node.children) {
  936. visit(child);
  937. }
  938. }
  939. for (const child of this.root.children) {
  940. visit(child);
  941. }
  942. return list;
  943. }
  944. get list(): ReadonlyArray<TraceTreeNode<TraceTree.NodeValue>> {
  945. return this._list;
  946. }
  947. /**
  948. * Prints the tree in a human readable format, useful for debugging and testing
  949. */
  950. print() {
  951. // root nodes are -1 indexed, so we add 1 to the depth so .repeat doesnt throw
  952. const print = this.list
  953. .map(t => printNode(t, 0))
  954. .filter(Boolean)
  955. .join('\n');
  956. // eslint-disable-next-line no-console
  957. console.log(print);
  958. }
  959. build() {
  960. this._list = this.toList();
  961. return this;
  962. }
  963. }
  964. export class TraceTreeNode<T extends TraceTree.NodeValue> {
  965. canFetch: boolean = false;
  966. fetchStatus: 'resolved' | 'error' | 'idle' | 'loading' = 'idle';
  967. parent: TraceTreeNode<TraceTree.NodeValue> | null = null;
  968. value: T;
  969. expanded: boolean = false;
  970. zoomedIn: boolean = false;
  971. metadata: TraceTree.Metadata = {
  972. project_slug: undefined,
  973. event_id: undefined,
  974. };
  975. errors: Set<TraceErrorType> = new Set<TraceErrorType>();
  976. performance_issues: Set<TracePerformanceIssue> = new Set<TracePerformanceIssue>();
  977. multiplier: number;
  978. space: [number, number] | null = null;
  979. profiles: TraceTree.Profile[] = [];
  980. private unit: 'milliseconds' = 'milliseconds';
  981. private _depth: number | undefined;
  982. private _children: TraceTreeNode<TraceTree.NodeValue>[] = [];
  983. private _spanChildren: TraceTreeNode<
  984. TraceTree.Span | TraceTree.MissingInstrumentationSpan
  985. >[] = [];
  986. private _connectors: number[] | undefined = undefined;
  987. constructor(
  988. parent: TraceTreeNode<TraceTree.NodeValue> | null,
  989. value: T,
  990. metadata: TraceTree.Metadata
  991. ) {
  992. this.parent = parent ?? null;
  993. this.value = value;
  994. this.metadata = metadata;
  995. this.multiplier = this.unit === 'milliseconds' ? 1e3 : 1;
  996. if (value && 'timestamp' in value && 'start_timestamp' in value) {
  997. this.space = [
  998. value.start_timestamp * this.multiplier,
  999. (value.timestamp - value.start_timestamp) * this.multiplier,
  1000. ];
  1001. } else if (value && 'timestamp' in value && typeof value.timestamp === 'number') {
  1002. this.space = [value.timestamp * this.multiplier, 0];
  1003. }
  1004. if (
  1005. isTraceErrorNode(this) &&
  1006. 'timestamp' in this.value &&
  1007. typeof this.value.timestamp === 'number'
  1008. ) {
  1009. this.space = [this.value.timestamp * this.multiplier, 0];
  1010. }
  1011. if (value && 'profile_id' in value && typeof value.profile_id === 'string') {
  1012. this.profiles.push({profile_id: value.profile_id, space: this.space ?? [0, 0]});
  1013. }
  1014. if (isTransactionNode(this)) {
  1015. this.canFetch = true;
  1016. }
  1017. if (isTransactionNode(this) || isTraceNode(this) || isSpanNode(this)) {
  1018. this.expanded = true;
  1019. }
  1020. if (shouldCollapseNodeByDefault(this)) {
  1021. this.expanded = false;
  1022. }
  1023. if (isTransactionNode(this)) {
  1024. this.errors = new Set(this.value.errors);
  1025. this.performance_issues = new Set(this.value.performance_issues);
  1026. }
  1027. // For error nodes, its value is the only associated issue.
  1028. if (isTraceErrorNode(this)) {
  1029. this.errors = new Set([this.value]);
  1030. }
  1031. }
  1032. cloneDeep():
  1033. | TraceTreeNode<T>
  1034. | ParentAutogroupNode
  1035. | SiblingAutogroupNode
  1036. | NoDataNode {
  1037. let clone: TraceTreeNode<T> | ParentAutogroupNode | SiblingAutogroupNode | NoDataNode;
  1038. if (isParentAutogroupedNode(this)) {
  1039. clone = new ParentAutogroupNode(
  1040. this.parent,
  1041. this.value,
  1042. this.metadata,
  1043. this.head,
  1044. this.tail
  1045. );
  1046. clone.groupCount = this.groupCount;
  1047. } else if (isSiblingAutogroupedNode(this)) {
  1048. clone = new SiblingAutogroupNode(this.parent, this.value, this.metadata);
  1049. clone.groupCount = this.groupCount;
  1050. } else if (isNoDataNode(this)) {
  1051. clone = new NoDataNode(this.parent);
  1052. } else {
  1053. clone = new TraceTreeNode(this.parent, this.value, this.metadata);
  1054. }
  1055. if (!clone) {
  1056. throw new Error('CloneDeep is not implemented');
  1057. }
  1058. clone.expanded = this.expanded;
  1059. clone.zoomedIn = this.zoomedIn;
  1060. clone.canFetch = this.canFetch;
  1061. clone.space = this.space;
  1062. clone.metadata = this.metadata;
  1063. if (isParentAutogroupedNode(clone)) {
  1064. clone.head = clone.head.cloneDeep() as TraceTreeNode<TraceTree.Span>;
  1065. clone.tail = clone.tail.cloneDeep() as TraceTreeNode<TraceTree.Span>;
  1066. clone.head.parent = clone;
  1067. // If the node is not expanded, the parent of the tail points to the
  1068. // autogrouped clone. If the node is expanded, the parent of the children
  1069. // of the tail points to the autogrouped clone.
  1070. if (!clone.expanded) {
  1071. for (const c of clone.tail.children) {
  1072. c.parent = clone;
  1073. }
  1074. } else {
  1075. for (const c of clone.children) {
  1076. c.parent = clone.tail;
  1077. }
  1078. }
  1079. clone.head.parent = clone;
  1080. clone.tail.parent = clone;
  1081. } else if (isSiblingAutogroupedNode(clone)) {
  1082. for (const child of this.children) {
  1083. const childClone = child.cloneDeep() as TraceTreeNode<TraceTree.Span>;
  1084. clone.children.push(childClone);
  1085. childClone.parent = clone;
  1086. }
  1087. } else {
  1088. for (const child of this.children) {
  1089. const childClone = child.cloneDeep() as TraceTreeNode<TraceTree.Span>;
  1090. clone.children.push(childClone);
  1091. childClone.parent = clone;
  1092. }
  1093. }
  1094. return clone;
  1095. }
  1096. get isOrphaned() {
  1097. return this.parent?.value && 'orphan_errors' in this.parent.value;
  1098. }
  1099. get isLastChild() {
  1100. if (!this.parent || this.parent.children.length === 0) {
  1101. return true;
  1102. }
  1103. return this.parent.children[this.parent.children.length - 1] === this;
  1104. }
  1105. /**
  1106. * Return a lazily calculated depth of the node in the tree.
  1107. * Root node has a value of -1 as it is abstract.
  1108. */
  1109. get depth(): number {
  1110. if (typeof this._depth === 'number') {
  1111. return this._depth;
  1112. }
  1113. let depth = -2;
  1114. let node: TraceTreeNode<any> | null = this;
  1115. while (node) {
  1116. if (typeof node.parent?.depth === 'number') {
  1117. this._depth = node.parent.depth + 1;
  1118. return this._depth;
  1119. }
  1120. depth++;
  1121. node = node.parent;
  1122. }
  1123. this._depth = depth;
  1124. return this._depth;
  1125. }
  1126. get has_errors(): boolean {
  1127. return this.errors.size > 0 || this.performance_issues.size > 0;
  1128. }
  1129. get parent_transaction(): TraceTreeNode<TraceTree.Transaction> | null {
  1130. let node: TraceTreeNode<TraceTree.NodeValue> | null = this.parent;
  1131. while (node) {
  1132. if (isTransactionNode(node)) {
  1133. return node;
  1134. }
  1135. node = node.parent;
  1136. }
  1137. return null;
  1138. }
  1139. /**
  1140. * Returns the depth levels at which the row should draw vertical connectors
  1141. * negative values mean connector points to an orphaned node
  1142. */
  1143. get connectors(): number[] {
  1144. if (this._connectors !== undefined) {
  1145. return this._connectors!;
  1146. }
  1147. this._connectors = [];
  1148. if (!this.parent) {
  1149. return this._connectors;
  1150. }
  1151. if (this.parent?.connectors !== undefined) {
  1152. this._connectors = [...this.parent.connectors];
  1153. if (this.isLastChild || this.value === null) {
  1154. return this._connectors;
  1155. }
  1156. this.connectors.push(this.isOrphaned ? -this.depth : this.depth);
  1157. return this._connectors;
  1158. }
  1159. let node: TraceTreeNode<T> | TraceTreeNode<TraceTree.NodeValue> | null = this.parent;
  1160. while (node) {
  1161. if (node.value === null) {
  1162. break;
  1163. }
  1164. if (node.isLastChild) {
  1165. node = node.parent;
  1166. continue;
  1167. }
  1168. this._connectors.push(node.isOrphaned ? -node.depth : node.depth);
  1169. node = node.parent;
  1170. }
  1171. return this._connectors;
  1172. }
  1173. /**
  1174. * Returns the children that the node currently points to.
  1175. * The logic here is a consequence of the tree design, where we want to be able to store
  1176. * both transaction and span nodes in the same tree. This results in an annoying API where
  1177. * we either store span children separately or transaction children separately. A better design
  1178. * would have been to create an invisible meta node that always points to the correct children.
  1179. */
  1180. get children(): TraceTreeNode<TraceTree.NodeValue>[] {
  1181. if (isAutogroupedNode(this)) {
  1182. return this._children;
  1183. }
  1184. if (isSpanNode(this)) {
  1185. return this.canFetch && !this.zoomedIn ? [] : this.spanChildren;
  1186. }
  1187. if (isTransactionNode(this)) {
  1188. return this.zoomedIn ? this._spanChildren : this._children;
  1189. }
  1190. return this._children;
  1191. }
  1192. set children(children: TraceTreeNode<TraceTree.NodeValue>[]) {
  1193. this._children = children;
  1194. }
  1195. get spanChildren(): (
  1196. | TraceTreeNode<TraceTree.Span | TraceTree.MissingInstrumentationSpan>
  1197. | NoDataNode
  1198. )[] {
  1199. return this._spanChildren;
  1200. }
  1201. /**
  1202. * Invalidate the visual data used to render the tree, forcing it
  1203. * to be recalculated on the next render. This is useful when for example
  1204. * the tree is expanded or collapsed, or when the tree is mutated and
  1205. * the visual data is no longer valid as the indentation changes
  1206. */
  1207. invalidate(root?: TraceTreeNode<TraceTree.NodeValue>) {
  1208. this._connectors = undefined;
  1209. this._depth = undefined;
  1210. if (root) {
  1211. const queue = [...this.children];
  1212. if (isParentAutogroupedNode(this)) {
  1213. queue.push(this.head);
  1214. }
  1215. while (queue.length > 0) {
  1216. const next = queue.pop()!;
  1217. next.invalidate();
  1218. if (isParentAutogroupedNode(next)) {
  1219. queue.push(next.head);
  1220. }
  1221. for (let i = 0; i < next.children.length; i++) {
  1222. queue.push(next.children[i]);
  1223. }
  1224. }
  1225. }
  1226. }
  1227. getVisibleChildrenCount(): number {
  1228. const stack: TraceTreeNode<TraceTree.NodeValue>[] = [];
  1229. let count = 0;
  1230. if (
  1231. this.expanded ||
  1232. isParentAutogroupedNode(this) ||
  1233. isMissingInstrumentationNode(this)
  1234. ) {
  1235. for (let i = this.children.length - 1; i >= 0; i--) {
  1236. stack.push(this.children[i]);
  1237. }
  1238. }
  1239. while (stack.length > 0) {
  1240. const node = stack.pop()!;
  1241. count++;
  1242. // Since we're using a stack and it's LIFO, reverse the children before pushing them
  1243. // to ensure they are processed in the original left-to-right order.
  1244. if (node.expanded || isParentAutogroupedNode(node)) {
  1245. for (let i = node.children.length - 1; i >= 0; i--) {
  1246. stack.push(node.children[i]);
  1247. }
  1248. }
  1249. }
  1250. return count;
  1251. }
  1252. getVisibleChildren(): TraceTreeNode<TraceTree.NodeValue>[] {
  1253. const stack: TraceTreeNode<TraceTree.NodeValue>[] = [];
  1254. const children: TraceTreeNode<TraceTree.NodeValue>[] = [];
  1255. if (
  1256. this.expanded ||
  1257. isParentAutogroupedNode(this) ||
  1258. isMissingInstrumentationNode(this)
  1259. ) {
  1260. for (let i = this.children.length - 1; i >= 0; i--) {
  1261. stack.push(this.children[i]);
  1262. }
  1263. }
  1264. while (stack.length > 0) {
  1265. const node = stack.pop()!;
  1266. children.push(node);
  1267. // Since we're using a stack and it's LIFO, reverse the children before pushing them
  1268. // to ensure they are processed in the original left-to-right order.
  1269. if (node.expanded || isParentAutogroupedNode(node)) {
  1270. for (let i = node.children.length - 1; i >= 0; i--) {
  1271. stack.push(node.children[i]);
  1272. }
  1273. }
  1274. }
  1275. return children;
  1276. }
  1277. // Returns the min path required to reach the node from the root.
  1278. // @TODO: skip nodes that do not require fetching
  1279. get path(): TraceTree.NodePath[] {
  1280. const nodes: TraceTreeNode<TraceTree.NodeValue>[] = [this];
  1281. let current: TraceTreeNode<TraceTree.NodeValue> | null = this.parent;
  1282. if (isSpanNode(this) || isAutogroupedNode(this)) {
  1283. while (
  1284. current &&
  1285. (isSpanNode(current) || (isAutogroupedNode(current) && !current.expanded))
  1286. ) {
  1287. current = current.parent;
  1288. }
  1289. }
  1290. while (current) {
  1291. if (isTransactionNode(current)) {
  1292. nodes.push(current);
  1293. }
  1294. if (isSpanNode(current)) {
  1295. nodes.push(current);
  1296. while (current.parent) {
  1297. if (isTransactionNode(current.parent)) {
  1298. break;
  1299. }
  1300. if (isAutogroupedNode(current.parent) && current.parent.expanded) {
  1301. break;
  1302. }
  1303. current = current.parent;
  1304. }
  1305. }
  1306. if (isAutogroupedNode(current)) {
  1307. nodes.push(current);
  1308. }
  1309. current = current.parent;
  1310. }
  1311. return nodes.map(nodeToId);
  1312. }
  1313. print() {
  1314. // root nodes are -1 indexed, so we add 1 to the depth so .repeat doesnt throw
  1315. const offset = this.depth === -1 ? 1 : 0;
  1316. const nodes = [this, ...this.getVisibleChildren()];
  1317. const print = nodes
  1318. .map(t => printNode(t, offset))
  1319. .filter(Boolean)
  1320. .join('\n');
  1321. // eslint-disable-next-line no-console
  1322. console.log(print);
  1323. }
  1324. static Find(
  1325. root: TraceTreeNode<TraceTree.NodeValue>,
  1326. predicate: (node: TraceTreeNode<TraceTree.NodeValue>) => boolean
  1327. ): TraceTreeNode<TraceTree.NodeValue> | null {
  1328. const queue = [root];
  1329. while (queue.length > 0) {
  1330. const next = queue.pop()!;
  1331. if (predicate(next)) return next;
  1332. for (const child of next.children) {
  1333. queue.push(child);
  1334. }
  1335. }
  1336. return null;
  1337. }
  1338. static Root() {
  1339. return new TraceTreeNode(null, null, {
  1340. event_id: undefined,
  1341. project_slug: undefined,
  1342. });
  1343. }
  1344. }
  1345. export class MissingInstrumentationNode extends TraceTreeNode<TraceTree.MissingInstrumentationSpan> {
  1346. next: TraceTreeNode<TraceTree.Span>;
  1347. previous: TraceTreeNode<TraceTree.Span>;
  1348. constructor(
  1349. parent: TraceTreeNode<TraceTree.NodeValue>,
  1350. node: TraceTree.MissingInstrumentationSpan,
  1351. metadata: TraceTree.Metadata,
  1352. previous: TraceTreeNode<TraceTree.Span>,
  1353. next: TraceTreeNode<TraceTree.Span>
  1354. ) {
  1355. super(parent, node, metadata);
  1356. this.next = next;
  1357. this.previous = previous;
  1358. }
  1359. }
  1360. export class ParentAutogroupNode extends TraceTreeNode<TraceTree.ChildrenAutogroup> {
  1361. head: TraceTreeNode<TraceTree.Span>;
  1362. tail: TraceTreeNode<TraceTree.Span>;
  1363. groupCount: number = 0;
  1364. profiles: TraceTree.Profile[] = [];
  1365. private _autogroupedSegments: [number, number][] | undefined;
  1366. constructor(
  1367. parent: TraceTreeNode<TraceTree.NodeValue> | null,
  1368. node: TraceTree.ChildrenAutogroup,
  1369. metadata: TraceTree.Metadata,
  1370. head: TraceTreeNode<TraceTree.Span>,
  1371. tail: TraceTreeNode<TraceTree.Span>
  1372. ) {
  1373. super(parent, node, metadata);
  1374. this.expanded = false;
  1375. this.head = head;
  1376. this.tail = tail;
  1377. }
  1378. get children() {
  1379. if (this.expanded) {
  1380. return [this.head];
  1381. }
  1382. return this.tail.children;
  1383. }
  1384. get has_errors(): boolean {
  1385. return this.errors.size > 0 || this.performance_issues.size > 0;
  1386. }
  1387. get autogroupedSegments(): [number, number][] {
  1388. if (this._autogroupedSegments) {
  1389. return this._autogroupedSegments;
  1390. }
  1391. const children: TraceTreeNode<TraceTree.NodeValue>[] = [];
  1392. let start: TraceTreeNode<TraceTree.NodeValue> | undefined = this.head;
  1393. while (start && start !== this.tail) {
  1394. children.push(start);
  1395. start = start.children[0];
  1396. }
  1397. children.push(this.tail);
  1398. this._autogroupedSegments = computeAutogroupedBarSegments(children);
  1399. return this._autogroupedSegments;
  1400. }
  1401. }
  1402. export class SiblingAutogroupNode extends TraceTreeNode<TraceTree.SiblingAutogroup> {
  1403. groupCount: number = 0;
  1404. profiles: TraceTree.Profile[] = [];
  1405. private _autogroupedSegments: [number, number][] | undefined;
  1406. constructor(
  1407. parent: TraceTreeNode<TraceTree.NodeValue> | null,
  1408. node: TraceTree.SiblingAutogroup,
  1409. metadata: TraceTree.Metadata
  1410. ) {
  1411. super(parent, node, metadata);
  1412. this.expanded = false;
  1413. }
  1414. get has_errors(): boolean {
  1415. return this.errors.size > 0 || this.performance_issues.size > 0;
  1416. }
  1417. get autogroupedSegments(): [number, number][] {
  1418. if (this._autogroupedSegments) {
  1419. return this._autogroupedSegments;
  1420. }
  1421. this._autogroupedSegments = computeAutogroupedBarSegments(this.children);
  1422. return this._autogroupedSegments;
  1423. }
  1424. }
  1425. export class NoDataNode extends TraceTreeNode<null> {
  1426. constructor(parent: TraceTreeNode<TraceTree.NodeValue> | null) {
  1427. super(parent, null, {
  1428. event_id: undefined,
  1429. project_slug: undefined,
  1430. });
  1431. }
  1432. }
  1433. function partialTransaction(
  1434. partial: Partial<TraceTree.Transaction>
  1435. ): TraceTree.Transaction {
  1436. return {
  1437. start_timestamp: 0,
  1438. timestamp: 0,
  1439. errors: [],
  1440. performance_issues: [],
  1441. parent_span_id: '',
  1442. span_id: '',
  1443. parent_event_id: '',
  1444. project_id: 0,
  1445. 'transaction.duration': 0,
  1446. 'transaction.op': 'db',
  1447. 'transaction.status': 'ok',
  1448. generation: 0,
  1449. project_slug: '',
  1450. event_id: `event_id`,
  1451. transaction: `transaction`,
  1452. children: [],
  1453. ...partial,
  1454. };
  1455. }
  1456. export function makeExampleTrace(metadata: TraceTree.Metadata): TraceTree {
  1457. const trace: TraceTree.Trace = {
  1458. transactions: [],
  1459. orphan_errors: [],
  1460. };
  1461. function randomBetween(min: number, max: number) {
  1462. return Math.floor(Math.random() * (max - min + 1) + min);
  1463. }
  1464. let start = new Date().getTime();
  1465. const root = partialTransaction({
  1466. ...metadata,
  1467. generation: 0,
  1468. start_timestamp: start,
  1469. transaction: 'root transaction',
  1470. timestamp: start + randomBetween(100, 200),
  1471. });
  1472. trace.transactions.push(root);
  1473. for (let i = 0; i < 50; i++) {
  1474. const end = start + randomBetween(100, 200);
  1475. const nest = i > 0 && Math.random() > 0.33;
  1476. if (nest) {
  1477. const parent = root.children[root.children.length - 1];
  1478. parent.children.push(
  1479. partialTransaction({
  1480. ...metadata,
  1481. generation: 0,
  1482. start_timestamp: start,
  1483. transaction: `parent transaction ${i}`,
  1484. timestamp: end,
  1485. })
  1486. );
  1487. parent.timestamp = end;
  1488. } else {
  1489. root.children.push(
  1490. partialTransaction({
  1491. ...metadata,
  1492. generation: 0,
  1493. start_timestamp: start,
  1494. transaction: 'loading...',
  1495. ['transaction.op']: 'loading',
  1496. timestamp: end,
  1497. })
  1498. );
  1499. }
  1500. start = end;
  1501. }
  1502. const tree = TraceTree.FromTrace(trace);
  1503. return tree;
  1504. }
  1505. function nodeToId(n: TraceTreeNode<TraceTree.NodeValue>): TraceTree.NodePath {
  1506. if (isTransactionNode(n)) {
  1507. return `txn-${n.value.event_id}`;
  1508. }
  1509. if (isSpanNode(n)) {
  1510. return `span-${n.value.span_id}`;
  1511. }
  1512. if (isAutogroupedNode(n)) {
  1513. if (isParentAutogroupedNode(n)) {
  1514. return `ag-${n.head.value.span_id}`;
  1515. }
  1516. if (isSiblingAutogroupedNode(n)) {
  1517. const child = n.children[0];
  1518. if (isSpanNode(child)) {
  1519. return `ag-${child.value.span_id}`;
  1520. }
  1521. }
  1522. }
  1523. if (isTraceNode(n)) {
  1524. return `trace-root`;
  1525. }
  1526. if (isTraceErrorNode(n)) {
  1527. return `error-${n.value.event_id}`;
  1528. }
  1529. if (isNoDataNode(n)) {
  1530. return `empty-node`;
  1531. }
  1532. if (isRootNode(n)) {
  1533. throw new Error('A path to root node does not exist as the node is virtual');
  1534. }
  1535. if (isMissingInstrumentationNode(n)) {
  1536. if (n.previous) {
  1537. return `ms-${n.previous.value.span_id}`;
  1538. }
  1539. if (n.next) {
  1540. return `ms-${n.next.value.span_id}`;
  1541. }
  1542. throw new Error('Missing instrumentation node must have a previous or next node');
  1543. }
  1544. throw new Error('Not implemented');
  1545. }
  1546. export function computeAutogroupedBarSegments(
  1547. nodes: TraceTreeNode<TraceTree.NodeValue>[]
  1548. ): [number, number][] {
  1549. if (nodes.length === 0) {
  1550. return [];
  1551. }
  1552. if (nodes.length === 1) {
  1553. const space = nodes[0].space;
  1554. if (!space) {
  1555. throw new Error(
  1556. 'Autogrouped node child has no defined space. This should not happen.'
  1557. );
  1558. }
  1559. return [space];
  1560. }
  1561. const first = nodes[0];
  1562. const multiplier = first.multiplier;
  1563. if (!isSpanNode(first)) {
  1564. throw new Error('Autogrouped node must have span children');
  1565. }
  1566. const segments: [number, number][] = [];
  1567. let start = first.value.start_timestamp;
  1568. let end = first.value.timestamp;
  1569. let i = 1;
  1570. while (i < nodes.length) {
  1571. const next = nodes[i];
  1572. if (!isSpanNode(next)) {
  1573. throw new Error('Autogrouped node must have span children');
  1574. }
  1575. if (next.value.start_timestamp > end) {
  1576. segments.push([start * multiplier, (end - start) * multiplier]);
  1577. start = next.value.start_timestamp;
  1578. end = next.value.timestamp;
  1579. i++;
  1580. } else {
  1581. end = next.value.timestamp;
  1582. i++;
  1583. }
  1584. }
  1585. segments.push([start * multiplier, (end - start) * multiplier]);
  1586. return segments;
  1587. }
  1588. // Returns a list of errors related to the txn with ids matching the span id
  1589. function getRelatedSpanErrorsFromTransaction(
  1590. span: RawSpanType,
  1591. node?: TraceTreeNode<TraceTree.NodeValue>
  1592. ): TraceErrorType[] {
  1593. if (!node || !node.value || !isTransactionNode(node)) {
  1594. return [];
  1595. }
  1596. if (!node?.value?.errors?.length) {
  1597. return [];
  1598. }
  1599. const errors: TraceErrorType[] = [];
  1600. for (const error of node.value.errors) {
  1601. if (error.span === span.span_id) {
  1602. errors.push(error);
  1603. }
  1604. }
  1605. return errors;
  1606. }
  1607. // Returns a list of performance errors related to the txn with ids matching the span id
  1608. function getRelatedPerformanceIssuesFromTransaction(
  1609. span: RawSpanType,
  1610. node?: TraceTreeNode<TraceTree.NodeValue>
  1611. ): TracePerformanceIssue[] {
  1612. if (!node || !node.value || !isTransactionNode(node)) {
  1613. return [];
  1614. }
  1615. if (!node?.value?.performance_issues?.length && !node?.value?.errors?.length) {
  1616. return [];
  1617. }
  1618. const performanceIssues: TracePerformanceIssue[] = [];
  1619. for (const perfIssue of node.value.performance_issues) {
  1620. for (const s of perfIssue.span) {
  1621. if (s === span.span_id) {
  1622. performanceIssues.push(perfIssue);
  1623. }
  1624. }
  1625. for (const suspect of perfIssue.suspect_spans) {
  1626. if (suspect === span.span_id) {
  1627. performanceIssues.push(perfIssue);
  1628. }
  1629. }
  1630. }
  1631. return performanceIssues;
  1632. }
  1633. function printNode(t: TraceTreeNode<TraceTree.NodeValue>, offset: number): string {
  1634. // +1 because we may be printing from the root which is -1 indexed
  1635. const padding = ' '.repeat(t.depth + offset);
  1636. if (isAutogroupedNode(t)) {
  1637. if (isParentAutogroupedNode(t)) {
  1638. return padding + `parent autogroup (${t.groupCount})`;
  1639. }
  1640. if (isSiblingAutogroupedNode(t)) {
  1641. return padding + `sibling autogroup (${t.groupCount})`;
  1642. }
  1643. return padding + 'autogroup';
  1644. }
  1645. if (isSpanNode(t)) {
  1646. return padding + (t.value.op || t.value.span_id || 'unknown span');
  1647. }
  1648. if (isTransactionNode(t)) {
  1649. return padding + (t.value.transaction || 'unknown transaction');
  1650. }
  1651. if (isMissingInstrumentationNode(t)) {
  1652. return padding + 'missing_instrumentation';
  1653. }
  1654. if (isRootNode(t)) {
  1655. return padding + 'Root';
  1656. }
  1657. if (isTraceNode(t)) {
  1658. return padding + 'Trace';
  1659. }
  1660. if (isNoDataNode(t)) {
  1661. return padding + 'No Data';
  1662. }
  1663. if (isTraceErrorNode(t)) {
  1664. return padding + (t.value.event_id || t.value.level) || 'unknown trace error';
  1665. }
  1666. return 'unknown node';
  1667. }