11import type { Baggage , Context , SpanContext , TextMapGetter , TextMapSetter } from '@opentelemetry/api' ;
22import { propagation , trace , TraceFlags } from '@opentelemetry/api' ;
33import { isTracingSuppressed , W3CBaggagePropagator } from '@opentelemetry/core' ;
4- import type { PropagationContext } from '@sentry/types' ;
4+ import { getDynamicSamplingContextFromClient } from '@sentry/core' ;
5+ import type { DynamicSamplingContext , PropagationContext } from '@sentry/types' ;
56import { generateSentryTraceHeader , SENTRY_BAGGAGE_KEY_PREFIX , tracingContextFromHeaders } from '@sentry/utils' ;
67
8+ import { getCurrentHub } from '../sdk/hub' ;
79import { SENTRY_BAGGAGE_HEADER , SENTRY_PROPAGATION_CONTEXT_CONTEXT_KEY , SENTRY_TRACE_HEADER } from './../constants' ;
10+ import { getSpanScope } from './spanData' ;
811
912/**
1013 * Injects and extracts `sentry-trace` and `baggage` headers from carriers.
@@ -23,7 +26,10 @@ export class SentryPropagator extends W3CBaggagePropagator {
2326 const propagationContext = context . getValue ( SENTRY_PROPAGATION_CONTEXT_CONTEXT_KEY ) as
2427 | PropagationContext
2528 | undefined ;
26- const dynamicSamplingContext = propagationContext ?. dsc ;
29+
30+ const { spanId, traceId, sampled } = getSentryTraceData ( context , propagationContext ) ;
31+
32+ const dynamicSamplingContext = propagationContext ? getDsc ( context , propagationContext , traceId ) : undefined ;
2733
2834 if ( dynamicSamplingContext ) {
2935 baggage = Object . entries ( dynamicSamplingContext ) . reduce < Baggage > ( ( b , [ dscKey , dscValue ] ) => {
@@ -34,8 +40,6 @@ export class SentryPropagator extends W3CBaggagePropagator {
3440 } , baggage ) ;
3541 }
3642
37- const { spanId, traceId, sampled } = getSentryTraceData ( context , propagationContext ) ;
38-
3943 setter . set ( carrier , SENTRY_TRACE_HEADER , generateSentryTraceHeader ( traceId , spanId , sampled ) ) ;
4044
4145 super . inject ( propagation . setBaggage ( context , baggage ) , carrier , setter ) ;
@@ -78,6 +82,28 @@ export class SentryPropagator extends W3CBaggagePropagator {
7882 }
7983}
8084
85+ function getDsc (
86+ context : Context ,
87+ propagationContext : PropagationContext ,
88+ traceId : string | undefined ,
89+ ) : DynamicSamplingContext | undefined {
90+ // If we have a DSC on the propagation context, we just use it
91+ if ( propagationContext . dsc ) {
92+ return propagationContext . dsc ;
93+ }
94+
95+ // Else, we try to generate a new one
96+ const client = getCurrentHub ( ) . getClient ( ) ;
97+ const activeSpan = trace . getSpan ( context ) ;
98+ const scope = activeSpan ? getSpanScope ( activeSpan ) : undefined ;
99+
100+ if ( client ) {
101+ return getDynamicSamplingContextFromClient ( traceId || propagationContext . traceId , client , scope ) ;
102+ }
103+
104+ return undefined ;
105+ }
106+
81107function getSentryTraceData (
82108 context : Context ,
83109 propagationContext : PropagationContext | undefined ,
0 commit comments