Skip to content

Commit 7975864

Browse files
committed
create helper for tracing context
1 parent d6f1b11 commit 7975864

File tree

1 file changed

+41
-1
lines changed

1 file changed

+41
-1
lines changed

packages/utils/src/tracing.ts

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
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';
25

36
export const TRACEPARENT_REGEXP = new RegExp(
47
'^[ \\t]*' + // whitespace
@@ -36,3 +39,40 @@ export function extractTraceparentData(traceparent: string): TraceparentData | u
3639
parentSpanId: matches[2],
3740
};
3841
}
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

Comments
 (0)