traceTree.tsx 83 KB

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