|
1 |
| -import type { TraceparentData } from '@sentry/types'; |
| 1 | +import type { DynamicSamplingContext, PropagationContext, TraceparentData } from '@sentry/types'; |
| 2 | + |
| 3 | +import { baggageHeaderToDynamicSamplingContext } from './baggage'; |
| 4 | +import { uuid4 } from './misc'; |
2 | 5 |
|
3 | 6 | export const TRACEPARENT_REGEXP = new RegExp(
|
4 | 7 | '^[ \\t]*' + // whitespace
|
@@ -36,3 +39,40 @@ export function extractTraceparentData(traceparent: string): TraceparentData | u
|
36 | 39 | parentSpanId: matches[2],
|
37 | 40 | };
|
38 | 41 | }
|
| 42 | + |
| 43 | +/** |
| 44 | + * Create tracing context from incoming headers. |
| 45 | + */ |
| 46 | +export function tracingContextFromHeaders( |
| 47 | + sentryTrace: Parameters<typeof extractTraceparentData>[0] = '', |
| 48 | + baggage: Parameters<typeof baggageHeaderToDynamicSamplingContext>[0] = '', |
| 49 | +): { |
| 50 | + traceparentData: TraceparentData | undefined; |
| 51 | + dynamicSamplingContext: Partial<DynamicSamplingContext> | undefined; |
| 52 | + propagationContext: PropagationContext; |
| 53 | +} { |
| 54 | + const traceparentData = extractTraceparentData(sentryTrace); |
| 55 | + const dynamicSamplingContext = baggageHeaderToDynamicSamplingContext(baggage); |
| 56 | + |
| 57 | + const { traceId, parentSpanId, parentSampled } = traceparentData || {}; |
| 58 | + |
| 59 | + const propagationContext: PropagationContext = { |
| 60 | + traceId: traceId || uuid4(), |
| 61 | + spanId: uuid4().substring(16), |
| 62 | + sampled: parentSampled === undefined ? false : parentSampled, |
| 63 | + }; |
| 64 | + |
| 65 | + if (parentSpanId) { |
| 66 | + propagationContext.parentSpanId = parentSpanId; |
| 67 | + } |
| 68 | + |
| 69 | + if (dynamicSamplingContext) { |
| 70 | + propagationContext.dsc = dynamicSamplingContext as DynamicSamplingContext; |
| 71 | + } |
| 72 | + |
| 73 | + return { |
| 74 | + traceparentData, |
| 75 | + dynamicSamplingContext, |
| 76 | + propagationContext, |
| 77 | + }; |
| 78 | +} |
0 commit comments