-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathtracing.ts
87 lines (75 loc) · 2.49 KB
/
tracing.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import type { PropagationContext, TraceparentData } from '../types-hoist';
import { baggageHeaderToDynamicSamplingContext } from './baggage';
import { generateSpanId, generateTraceId } from './propagationContext';
// eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor -- RegExp is used for readability here
export const TRACEPARENT_REGEXP = new RegExp(
'^[ \\t]*' + // whitespace
'([0-9a-f]{32})?' + // trace_id
'-?([0-9a-f]{16})?' + // span_id
'-?([01])?' + // sampled
'[ \\t]*$', // whitespace
);
/**
* Extract transaction context data from a `sentry-trace` header.
*
* @param traceparent Traceparent string
*
* @returns Object containing data from the header, or undefined if traceparent string is malformed
*/
export function extractTraceparentData(traceparent?: string): TraceparentData | undefined {
if (!traceparent) {
return undefined;
}
const matches = traceparent.match(TRACEPARENT_REGEXP);
if (!matches) {
return undefined;
}
let parentSampled: boolean | undefined;
if (matches[3] === '1') {
parentSampled = true;
} else if (matches[3] === '0') {
parentSampled = false;
}
return {
traceId: matches[1],
parentSampled,
parentSpanId: matches[2],
};
}
/**
* Create a propagation context from incoming headers or
* creates a minimal new one if the headers are undefined.
*/
export function propagationContextFromHeaders(
sentryTrace: string | undefined,
baggage: string | number | boolean | string[] | null | undefined,
): PropagationContext {
const traceparentData = extractTraceparentData(sentryTrace);
const dynamicSamplingContext = baggageHeaderToDynamicSamplingContext(baggage);
if (!traceparentData || !traceparentData.traceId) {
return { traceId: generateTraceId(), spanId: generateSpanId() };
}
const { traceId, parentSpanId, parentSampled } = traceparentData;
const virtualSpanId = generateSpanId();
return {
traceId,
parentSpanId,
spanId: virtualSpanId,
sampled: parentSampled,
dsc: dynamicSamplingContext || {}, // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it
};
}
/**
* Create sentry-trace header from span context values.
*/
export function generateSentryTraceHeader(
traceId: string = generateTraceId(),
spanId: string = generateSpanId(),
sampled?: boolean,
): string {
let sampledString = '';
if (sampled !== undefined) {
sampledString = sampled ? '-1' : '-0';
}
return `${traceId}-${spanId}${sampledString}`;
}