@@ -156,6 +156,10 @@ export function startInactiveSpan(context: StartSpanOptions): Span | undefined {
156156 } ) ;
157157 }
158158
159+ if ( parentSpan ) {
160+ addChildSpanToSpan ( parentSpan , span ) ;
161+ }
162+
159163 setCapturedScopesOnSpan ( span , scope , isolationScope ) ;
160164
161165 return span ;
@@ -307,6 +311,10 @@ function createChildSpanOrTransaction(
307311 } ) ;
308312 }
309313
314+ if ( parentSpan ) {
315+ addChildSpanToSpan ( parentSpan , span ) ;
316+ }
317+
310318 setCapturedScopesOnSpan ( span , scope , isolationScope ) ;
311319
312320 return span ;
@@ -330,6 +338,47 @@ function normalizeContext(context: StartSpanOptions): TransactionContext {
330338 return context ;
331339}
332340
341+ const CHILD_SPANS_FIELD = '_sentryChildSpans' ;
342+
343+ type SpanWithPotentialChildren = Span & {
344+ [ CHILD_SPANS_FIELD ] ?: Set < Span > ;
345+ } ;
346+
347+ /**
348+ * Adds an opaque child span reference to a span.
349+ */
350+ export function addChildSpanToSpan ( span : SpanWithPotentialChildren , childSpan : Span ) : void {
351+ if ( span [ CHILD_SPANS_FIELD ] && span [ CHILD_SPANS_FIELD ] . size < 1000 ) {
352+ span [ CHILD_SPANS_FIELD ] . add ( childSpan ) ;
353+ } else {
354+ span [ CHILD_SPANS_FIELD ] = new Set ( [ childSpan ] ) ;
355+ }
356+ }
357+
358+ /**
359+ * Obtains the entire span tree, meaning a span + all of its descendants for a particular span.
360+ */
361+ export function getSpanTree ( span : SpanWithPotentialChildren ) : Span [ ] {
362+ const resultSet = new Set < Span > ( ) ;
363+
364+ function addSpanChildren ( span : SpanWithPotentialChildren ) : void {
365+ // This exit condition is required to not infinitely loop in case of a circular dependency.
366+ if ( resultSet . has ( span ) ) {
367+ return ;
368+ } else {
369+ resultSet . add ( span ) ;
370+ const childSpans = span [ CHILD_SPANS_FIELD ] ? Array . from ( span [ CHILD_SPANS_FIELD ] ) : [ ] ;
371+ for ( const childSpan of childSpans ) {
372+ addSpanChildren ( childSpan ) ;
373+ }
374+ }
375+ }
376+
377+ addSpanChildren ( span ) ;
378+
379+ return Array . from ( resultSet ) ;
380+ }
381+
333382const SCOPE_ON_START_SPAN_FIELD = '_sentryScope' ;
334383const ISOLATION_SCOPE_ON_START_SPAN_FIELD = '_sentryIsolationScope' ;
335384
0 commit comments