traceTree.tsx 65 KB

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