-
-
Notifications
You must be signed in to change notification settings - Fork 466
Expand file tree
/
Copy pathTraceHeaderParserTrait.php
More file actions
188 lines (158 loc) · 6.68 KB
/
TraceHeaderParserTrait.php
File metadata and controls
188 lines (158 loc) · 6.68 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
<?php
declare(strict_types=1);
namespace Sentry\Tracing\Traits;
use Sentry\SentrySdk;
use Sentry\Tracing\DynamicSamplingContext;
use Sentry\Tracing\SpanId;
use Sentry\Tracing\TraceId;
/**
* @internal
*/
trait TraceHeaderParserTrait
{
/**
* @var string The regex for parsing the sentry-trace header
*/
private static $sentryTraceparentHeaderRegex = '/^[ \\t]*(?<trace_id>[0-9a-f]{32})?-?(?<span_id>[0-9a-f]{16})?-?(?<sampled>[01])?[ \\t]*$/i';
/**
* Parses the sentry-trace and baggage headers and returns the extracted data.
*
* @param string $sentryTrace The sentry-trace header value
* @param string $baggage The baggage header value
*
* @return array{
* traceId: TraceId|null,
* parentSpanId: SpanId|null,
* parentSampled: bool|null,
* dynamicSamplingContext: DynamicSamplingContext|null,
* sampleRand: float|null,
* parentSamplingRate: float|null
* }
*/
protected static function parseTraceAndBaggageHeaders(string $sentryTrace, string $baggage): array
{
$result = [
'traceId' => null,
'parentSpanId' => null,
'parentSampled' => null,
'dynamicSamplingContext' => null,
'sampleRand' => null,
'parentSamplingRate' => null,
];
$hasSentryTrace = false;
if (preg_match(self::$sentryTraceparentHeaderRegex, $sentryTrace, $matches)) {
if (!empty($matches['trace_id'])) {
$result['traceId'] = new TraceId($matches['trace_id']);
$hasSentryTrace = true;
}
if (!empty($matches['span_id'])) {
$result['parentSpanId'] = new SpanId($matches['span_id']);
$hasSentryTrace = true;
}
if (isset($matches['sampled'])) {
$result['parentSampled'] = $matches['sampled'] === '1';
$hasSentryTrace = true;
}
}
$samplingContext = DynamicSamplingContext::fromHeader($baggage);
if ($hasSentryTrace && !self::shouldContinueTrace($samplingContext)) {
$result['traceId'] = null;
$result['parentSpanId'] = null;
$result['parentSampled'] = null;
return $result;
}
if ($hasSentryTrace) {
// The request comes from an old SDK which does not support Dynamic Sampling.
// Propagate the Dynamic Sampling Context as is, but frozen, even without sentry-* entries.
if (!$samplingContext->hasEntries()) {
$samplingContext->freeze();
}
// The baggage header contains Dynamic Sampling Context data from an upstream SDK.
// Propagate this Dynamic Sampling Context.
$result['dynamicSamplingContext'] = $samplingContext;
// Store the propagated traces sample rate
if ($samplingContext->has('sample_rate')) {
$result['parentSamplingRate'] = (float) $samplingContext->get('sample_rate');
}
}
// Store the propagated trace sample rand or generate a new one
if ($hasSentryTrace) {
$incomingSampleRand = self::parseSampleRand($samplingContext);
if ($incomingSampleRand !== null) {
$result['sampleRand'] = $incomingSampleRand;
} elseif ($samplingContext->has('sample_rate') && $result['parentSampled'] !== null) {
if ($result['parentSampled'] === true) {
// [0, rate)
$result['sampleRand'] = round(mt_rand(0, mt_getrandmax() - 1) / mt_getrandmax() * (float) $samplingContext->get('sample_rate'), 6);
} else {
// [rate, 1)
$result['sampleRand'] = round(mt_rand(0, mt_getrandmax() - 1) / mt_getrandmax() * (1 - (float) $samplingContext->get('sample_rate')) + (float) $samplingContext->get('sample_rate'), 6);
}
} elseif ($result['parentSampled'] !== null) {
// [0, 1)
$result['sampleRand'] = round(mt_rand(0, mt_getrandmax() - 1) / mt_getrandmax(), 6);
}
}
return $result;
}
private static function parseSampleRand(DynamicSamplingContext $samplingContext): ?float
{
$sampleRand = $samplingContext->get('sample_rand');
if ($sampleRand === null) {
return null;
}
if (is_numeric($sampleRand)) {
$sampleRandAsFloat = (float) $sampleRand;
if ($sampleRandAsFloat >= 0.0 && $sampleRandAsFloat < 1.0) {
return $sampleRandAsFloat;
}
}
$hub = SentrySdk::getCurrentHub();
$client = $hub->getClient();
if ($client !== null) {
$client->getOptions()->getLoggerOrNullLogger()->debug(
'Ignoring invalid sentry-sample_rand baggage value because it must be a numeric value in the range [0, 1).',
['sample_rand' => $sampleRand]
);
}
return null;
}
private static function shouldContinueTrace(DynamicSamplingContext $samplingContext): bool
{
$hub = SentrySdk::getCurrentHub();
$client = $hub->getClient();
if ($client === null) {
return true;
}
$options = $client->getOptions();
$clientOrgId = $options->getOrgId();
if ($clientOrgId === null && $options->getDsn() !== null) {
$clientOrgId = $options->getDsn()->getOrgId();
}
$baggageOrgId = $samplingContext->get('org_id');
$logger = $options->getLoggerOrNullLogger();
// both org IDs are set but are not equals
if ($clientOrgId !== null && $baggageOrgId !== null && ((string) $clientOrgId !== $baggageOrgId)) {
$logger->debug(
\sprintf(
"Starting a new trace because org IDs don't match (incoming baggage org_id: %s, SDK org_id: %s)",
$baggageOrgId,
$clientOrgId
)
);
return false;
}
// One org ID is not set and strict trace continuation is enabled
if ($options->isStrictTraceContinuationEnabled() && ($clientOrgId === null) !== ($baggageOrgId === null)) {
$logger->debug(
\sprintf(
'Starting a new trace because strict trace continuation is enabled and one org ID is missing (incoming baggage org_id: %s, SDK org_id: %s)',
$baggageOrgId !== null ? $baggageOrgId : 'none',
$clientOrgId !== null ? (string) $clientOrgId : 'none'
)
);
return false;
}
return true;
}
}