@sentry/opentelemetry 10.50.0-alpha.0 → 10.51.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/cjs/index.browser.js +56 -0
- package/build/cjs/index.browser.js.map +1 -0
- package/build/cjs/index.js +166 -2720
- package/build/cjs/index.js.map +1 -1
- package/build/cjs/resource-XtlN3b7H.js +2584 -0
- package/build/cjs/resource-XtlN3b7H.js.map +1 -0
- package/build/cjs/tracingChannel.js.map +1 -1
- package/build/esm/index.browser.js +21 -0
- package/build/esm/index.browser.js.map +1 -0
- package/build/esm/index.js +139 -2694
- package/build/esm/index.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/esm/resource-CQdLBDrM.js +2553 -0
- package/build/esm/resource-CQdLBDrM.js.map +1 -0
- package/build/esm/tracingChannel.js.map +1 -1
- package/build/types/exports.d.ts +24 -0
- package/build/types/exports.d.ts.map +1 -0
- package/build/types/index.browser.d.ts +9 -0
- package/build/types/index.browser.d.ts.map +1 -0
- package/build/types/index.d.ts +1 -23
- package/build/types/index.d.ts.map +1 -1
- package/build/types/sampler.d.ts.map +1 -1
- package/build/types/spanExporter.d.ts.map +1 -1
- package/build/types/tracingChannel.d.ts +3 -4
- package/build/types/tracingChannel.d.ts.map +1 -1
- package/build/types-ts3.8/exports.d.ts +24 -0
- package/build/types-ts3.8/index.browser.d.ts +9 -0
- package/build/types-ts3.8/index.d.ts +1 -23
- package/build/types-ts3.8/tracingChannel.d.ts +3 -4
- package/package.json +18 -2
package/build/cjs/index.js
CHANGED
|
@@ -1,2778 +1,224 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
2
|
|
|
3
|
-
const
|
|
3
|
+
const resource = require('./resource-XtlN3b7H.js');
|
|
4
4
|
const core = require('@sentry/core');
|
|
5
5
|
const api = require('@opentelemetry/api');
|
|
6
|
-
const core$1 = require('@opentelemetry/core');
|
|
7
|
-
const debugBuild = require('./debug-build-ntZrglYX.js');
|
|
8
6
|
const node_async_hooks = require('node:async_hooks');
|
|
9
7
|
const node_events = require('node:events');
|
|
10
|
-
|
|
8
|
+
require('@opentelemetry/semantic-conventions');
|
|
9
|
+
require('@opentelemetry/core');
|
|
10
|
+
require('./debug-build-ntZrglYX.js');
|
|
11
|
+
require('@opentelemetry/sdk-trace-base');
|
|
11
12
|
|
|
12
|
-
|
|
13
|
-
const SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE = 'sentry.parentIsRemote';
|
|
14
|
-
|
|
15
|
-
// These are not standardized yet, but used by the graphql instrumentation
|
|
16
|
-
const SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION = 'sentry.graphql.operation';
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
* Get the parent span id from a span.
|
|
20
|
-
* In OTel v1, the parent span id is accessed as `parentSpanId`
|
|
21
|
-
* In OTel v2, the parent span id is accessed as `spanId` on the `parentSpanContext`
|
|
22
|
-
*/
|
|
23
|
-
function getParentSpanId(span) {
|
|
24
|
-
if ('parentSpanId' in span) {
|
|
25
|
-
return span.parentSpanId ;
|
|
26
|
-
} else if ('parentSpanContext' in span) {
|
|
27
|
-
return (span.parentSpanContext )?.spanId;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
return undefined;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
/**
|
|
34
|
-
* Check if a given span has attributes.
|
|
35
|
-
* This is necessary because the base `Span` type does not have attributes,
|
|
36
|
-
* so in places where we are passed a generic span, we need to check if we want to access them.
|
|
37
|
-
*/
|
|
38
|
-
function spanHasAttributes(
|
|
39
|
-
span,
|
|
40
|
-
) {
|
|
41
|
-
const castSpan = span ;
|
|
42
|
-
return !!castSpan.attributes && typeof castSpan.attributes === 'object';
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* Check if a given span has a kind.
|
|
47
|
-
* This is necessary because the base `Span` type does not have a kind,
|
|
48
|
-
* so in places where we are passed a generic span, we need to check if we want to access it.
|
|
49
|
-
*/
|
|
50
|
-
function spanHasKind(span) {
|
|
51
|
-
const castSpan = span ;
|
|
52
|
-
return typeof castSpan.kind === 'number';
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
/**
|
|
56
|
-
* Check if a given span has a status.
|
|
57
|
-
* This is necessary because the base `Span` type does not have a status,
|
|
58
|
-
* so in places where we are passed a generic span, we need to check if we want to access it.
|
|
59
|
-
*/
|
|
60
|
-
function spanHasStatus(
|
|
61
|
-
span,
|
|
62
|
-
) {
|
|
63
|
-
const castSpan = span ;
|
|
64
|
-
return !!castSpan.status;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
/**
|
|
68
|
-
* Check if a given span has a name.
|
|
69
|
-
* This is necessary because the base `Span` type does not have a name,
|
|
70
|
-
* so in places where we are passed a generic span, we need to check if we want to access it.
|
|
71
|
-
*/
|
|
72
|
-
function spanHasName(span) {
|
|
73
|
-
const castSpan = span ;
|
|
74
|
-
return !!castSpan.name;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
/**
|
|
78
|
-
* Check if a given span has a kind.
|
|
79
|
-
* This is necessary because the base `Span` type does not have a kind,
|
|
80
|
-
* so in places where we are passed a generic span, we need to check if we want to access it.
|
|
81
|
-
*/
|
|
82
|
-
function spanHasParentId(
|
|
83
|
-
span,
|
|
84
|
-
) {
|
|
85
|
-
const castSpan = span ;
|
|
86
|
-
return !!getParentSpanId(castSpan);
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
/**
|
|
90
|
-
* Check if a given span has events.
|
|
91
|
-
* This is necessary because the base `Span` type does not have events,
|
|
92
|
-
* so in places where we are passed a generic span, we need to check if we want to access it.
|
|
93
|
-
*/
|
|
94
|
-
function spanHasEvents(
|
|
95
|
-
span,
|
|
96
|
-
) {
|
|
97
|
-
const castSpan = span ;
|
|
98
|
-
return Array.isArray(castSpan.events);
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
/**
|
|
102
|
-
* Get sanitizied request data from an OTEL span.
|
|
103
|
-
*/
|
|
104
|
-
function getRequestSpanData(span) {
|
|
105
|
-
// The base `Span` type has no `attributes`, so we need to guard here against that
|
|
106
|
-
if (!spanHasAttributes(span)) {
|
|
107
|
-
return {};
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
// eslint-disable-next-line deprecation/deprecation
|
|
111
|
-
const maybeUrlAttribute = (span.attributes[semanticConventions.ATTR_URL_FULL] || span.attributes[semanticConventions.SEMATTRS_HTTP_URL])
|
|
112
|
-
|
|
113
|
-
;
|
|
114
|
-
|
|
115
|
-
const data = {
|
|
116
|
-
url: maybeUrlAttribute,
|
|
117
|
-
// eslint-disable-next-line deprecation/deprecation
|
|
118
|
-
'http.method': (span.attributes[semanticConventions.ATTR_HTTP_REQUEST_METHOD] || span.attributes[semanticConventions.SEMATTRS_HTTP_METHOD])
|
|
119
|
-
|
|
120
|
-
,
|
|
121
|
-
};
|
|
122
|
-
|
|
123
|
-
// Default to GET if URL is set but method is not
|
|
124
|
-
if (!data['http.method'] && data.url) {
|
|
125
|
-
data['http.method'] = 'GET';
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
try {
|
|
129
|
-
if (typeof maybeUrlAttribute === 'string') {
|
|
130
|
-
const url = core.parseUrl(maybeUrlAttribute);
|
|
131
|
-
|
|
132
|
-
data.url = core.getSanitizedUrlString(url);
|
|
133
|
-
|
|
134
|
-
if (url.search) {
|
|
135
|
-
data['http.query'] = url.search;
|
|
136
|
-
}
|
|
137
|
-
if (url.hash) {
|
|
138
|
-
data['http.fragment'] = url.hash;
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
} catch {
|
|
142
|
-
// ignore
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
return data;
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
// Typescript complains if we do not use `...args: any[]` for the mixin, with:
|
|
149
|
-
// A mixin class must have a constructor with a single rest parameter of type 'any[]'.ts(2545)
|
|
150
|
-
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
151
|
-
|
|
152
|
-
/**
|
|
153
|
-
* Wrap an Client class with things we need for OpenTelemetry support.
|
|
154
|
-
* Make sure that the Client class passed in is non-abstract!
|
|
155
|
-
*
|
|
156
|
-
* Usage:
|
|
157
|
-
* const OpenTelemetryClient = getWrappedClientClass(NodeClient);
|
|
158
|
-
* const client = new OpenTelemetryClient(options);
|
|
159
|
-
*/
|
|
160
|
-
function wrapClientClass
|
|
161
|
-
|
|
162
|
-
(ClientClass) {
|
|
163
|
-
// @ts-expect-error We just assume that this is non-abstract, if you pass in an abstract class this would make it non-abstract
|
|
164
|
-
class OpenTelemetryClient extends ClientClass {
|
|
165
|
-
|
|
166
|
-
constructor(...args) {
|
|
167
|
-
super(...args);
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
/** Get the OTEL tracer. */
|
|
171
|
-
get tracer() {
|
|
172
|
-
if (this._tracer) {
|
|
173
|
-
return this._tracer;
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
const name = '@sentry/opentelemetry';
|
|
177
|
-
const version = core.SDK_VERSION;
|
|
178
|
-
const tracer = api.trace.getTracer(name, version);
|
|
179
|
-
this._tracer = tracer;
|
|
180
|
-
|
|
181
|
-
return tracer;
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
/**
|
|
185
|
-
* @inheritDoc
|
|
186
|
-
*/
|
|
187
|
-
async flush(timeout) {
|
|
188
|
-
const provider = this.traceProvider;
|
|
189
|
-
await provider?.forceFlush();
|
|
190
|
-
return super.flush(timeout);
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
return OpenTelemetryClient ;
|
|
195
|
-
}
|
|
196
|
-
/* eslint-enable @typescript-eslint/no-explicit-any */
|
|
197
|
-
|
|
198
|
-
/**
|
|
199
|
-
* Get the span kind from a span.
|
|
200
|
-
* For whatever reason, this is not public API on the generic "Span" type,
|
|
201
|
-
* so we need to check if we actually have a `SDKTraceBaseSpan` where we can fetch this from.
|
|
202
|
-
* Otherwise, we fall back to `SpanKind.INTERNAL`.
|
|
203
|
-
*/
|
|
204
|
-
function getSpanKind(span) {
|
|
205
|
-
if (spanHasKind(span)) {
|
|
206
|
-
return span.kind;
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
return api.SpanKind.INTERNAL;
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
const SENTRY_TRACE_HEADER = 'sentry-trace';
|
|
213
|
-
const SENTRY_BAGGAGE_HEADER = 'baggage';
|
|
214
|
-
|
|
215
|
-
const SENTRY_TRACE_STATE_DSC = 'sentry.dsc';
|
|
216
|
-
const SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING = 'sentry.sampled_not_recording';
|
|
217
|
-
const SENTRY_TRACE_STATE_URL = 'sentry.url';
|
|
218
|
-
const SENTRY_TRACE_STATE_SAMPLE_RAND = 'sentry.sample_rand';
|
|
219
|
-
const SENTRY_TRACE_STATE_SAMPLE_RATE = 'sentry.sample_rate';
|
|
220
|
-
|
|
221
|
-
/**
|
|
222
|
-
* A flag marking a context as ignored because the span associated with the context
|
|
223
|
-
* is ignored (`ignoreSpans` filter).
|
|
224
|
-
*/
|
|
225
|
-
const SENTRY_TRACE_STATE_CHILD_IGNORED = 'sentry.ignored';
|
|
226
|
-
|
|
227
|
-
/**
|
|
228
|
-
* A flag marking a segment span as ignored because it matched the `ignoreSpans` filter.
|
|
229
|
-
* Unlike `SENTRY_TRACE_STATE_CHILD_IGNORED` (used for child spans), this flag is NOT consumed
|
|
230
|
-
* by the context manager for re-parenting. Instead, it propagates to child spans so they
|
|
231
|
-
* can record the correct client report outcome (`ignored` instead of `sample_rate`).
|
|
232
|
-
*/
|
|
233
|
-
const SENTRY_TRACE_STATE_SEGMENT_IGNORED = 'sentry.segment_ignored';
|
|
234
|
-
|
|
235
|
-
const SENTRY_SCOPES_CONTEXT_KEY = api.createContextKey('sentry_scopes');
|
|
236
|
-
|
|
237
|
-
const SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY = api.createContextKey('sentry_fork_isolation_scope');
|
|
238
|
-
|
|
239
|
-
const SENTRY_FORK_SET_SCOPE_CONTEXT_KEY = api.createContextKey('sentry_fork_set_scope');
|
|
240
|
-
|
|
241
|
-
const SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY = api.createContextKey('sentry_fork_set_isolation_scope');
|
|
242
|
-
|
|
243
|
-
const SCOPE_CONTEXT_FIELD = '_scopeContext';
|
|
244
|
-
|
|
245
|
-
/**
|
|
246
|
-
* Try to get the current scopes from the given OTEL context.
|
|
247
|
-
* This requires a Context Manager that was wrapped with getWrappedContextManager.
|
|
248
|
-
*/
|
|
249
|
-
function getScopesFromContext(context) {
|
|
250
|
-
return context.getValue(SENTRY_SCOPES_CONTEXT_KEY) ;
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
/**
|
|
254
|
-
* Set the current scopes on an OTEL context.
|
|
255
|
-
* This will return a forked context with the Propagation Context set.
|
|
256
|
-
*/
|
|
257
|
-
function setScopesOnContext(context, scopes) {
|
|
258
|
-
return context.setValue(SENTRY_SCOPES_CONTEXT_KEY, scopes);
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
/**
|
|
262
|
-
* Set the context on the scope so we can later look it up.
|
|
263
|
-
* We need this to get the context from the scope in the `trace` functions.
|
|
264
|
-
*
|
|
265
|
-
* We use WeakRef to avoid a circular reference between the scope and the context.
|
|
266
|
-
* The context holds scopes (via SENTRY_SCOPES_CONTEXT_KEY), and if the scope held
|
|
267
|
-
* a strong reference back to the context, neither could be garbage collected even
|
|
268
|
-
* when the context is no longer reachable from application code (e.g., after a
|
|
269
|
-
* request completes but pooled connections retain patched callbacks).
|
|
270
|
-
*/
|
|
271
|
-
function setContextOnScope(scope, context) {
|
|
272
|
-
core.addNonEnumerableProperty(scope, SCOPE_CONTEXT_FIELD, core.makeWeakRef(context));
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
/**
|
|
276
|
-
* Get the context related to a scope.
|
|
277
|
-
* Returns undefined if the context has been garbage collected (when WeakRef is used).
|
|
278
|
-
*/
|
|
279
|
-
function getContextFromScope(scope) {
|
|
280
|
-
return core.derefWeakRef((scope )[SCOPE_CONTEXT_FIELD]);
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
/**
|
|
284
|
-
*
|
|
285
|
-
* @param otelSpan Checks whether a given OTEL Span is an http request to sentry.
|
|
286
|
-
* @returns boolean
|
|
287
|
-
*/
|
|
288
|
-
function isSentryRequestSpan(span) {
|
|
289
|
-
if (!spanHasAttributes(span)) {
|
|
290
|
-
return false;
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
const { attributes } = span;
|
|
294
|
-
|
|
295
|
-
// `ATTR_URL_FULL` is the new attribute, but we still support the old one, `ATTR_HTTP_URL`, for now.
|
|
296
|
-
// eslint-disable-next-line deprecation/deprecation
|
|
297
|
-
const httpUrl = attributes[semanticConventions.SEMATTRS_HTTP_URL] || attributes[semanticConventions.ATTR_URL_FULL];
|
|
298
|
-
|
|
299
|
-
if (!httpUrl) {
|
|
300
|
-
return false;
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
return core.isSentryRequestUrl(httpUrl.toString(), core.getClient());
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
/**
|
|
307
|
-
* OpenTelemetry only knows about SAMPLED or NONE decision,
|
|
308
|
-
* but for us it is important to differentiate between unset and unsampled.
|
|
309
|
-
*
|
|
310
|
-
* Both of these are identified as `traceFlags === TracegFlags.NONE`,
|
|
311
|
-
* but we additionally look at a special trace state to differentiate between them.
|
|
312
|
-
*/
|
|
313
|
-
function getSamplingDecision(spanContext) {
|
|
314
|
-
const { traceFlags, traceState } = spanContext;
|
|
315
|
-
|
|
316
|
-
const sampledNotRecording = traceState ? traceState.get(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING) === '1' : false;
|
|
317
|
-
|
|
318
|
-
// If trace flag is `SAMPLED`, we interpret this as sampled
|
|
319
|
-
// If it is `NONE`, it could mean either it was sampled to be not recorder, or that it was not sampled at all
|
|
320
|
-
// For us this is an important difference, sow e look at the SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING
|
|
321
|
-
// to identify which it is
|
|
322
|
-
if (traceFlags === api.TraceFlags.SAMPLED) {
|
|
323
|
-
return true;
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
if (sampledNotRecording) {
|
|
327
|
-
return false;
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
// Fall back to DSC as a last resort, that may also contain `sampled`...
|
|
331
|
-
const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : undefined;
|
|
332
|
-
const dsc = dscString ? core.baggageHeaderToDynamicSamplingContext(dscString) : undefined;
|
|
333
|
-
|
|
334
|
-
if (dsc?.sampled === 'true') {
|
|
335
|
-
return true;
|
|
336
|
-
}
|
|
337
|
-
if (dsc?.sampled === 'false') {
|
|
338
|
-
return false;
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
return undefined;
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
/**
|
|
345
|
-
* Infer the op & description for a set of name, attributes and kind of a span.
|
|
346
|
-
*/
|
|
347
|
-
function inferSpanData(spanName, attributes, kind) {
|
|
348
|
-
// if http.method exists, this is an http request span
|
|
349
|
-
// eslint-disable-next-line deprecation/deprecation
|
|
350
|
-
const httpMethod = attributes[semanticConventions.ATTR_HTTP_REQUEST_METHOD] || attributes[semanticConventions.SEMATTRS_HTTP_METHOD];
|
|
351
|
-
if (httpMethod) {
|
|
352
|
-
return descriptionForHttpMethod({ attributes, name: spanName, kind }, httpMethod);
|
|
353
|
-
}
|
|
354
|
-
|
|
355
|
-
// eslint-disable-next-line deprecation/deprecation
|
|
356
|
-
const dbSystem = attributes[semanticConventions.ATTR_DB_SYSTEM_NAME] || attributes[semanticConventions.SEMATTRS_DB_SYSTEM];
|
|
357
|
-
const opIsCache =
|
|
358
|
-
typeof attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_OP] === 'string' &&
|
|
359
|
-
attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_OP].startsWith('cache.');
|
|
360
|
-
|
|
361
|
-
// If db.type exists then this is a database call span
|
|
362
|
-
// If the Redis DB is used as a cache, the span description should not be changed
|
|
363
|
-
if (dbSystem && !opIsCache) {
|
|
364
|
-
return descriptionForDbSystem({ attributes, name: spanName });
|
|
365
|
-
}
|
|
366
|
-
|
|
367
|
-
const customSourceOrRoute = attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] === 'custom' ? 'custom' : 'route';
|
|
368
|
-
|
|
369
|
-
// If rpc.service exists then this is a rpc call span.
|
|
370
|
-
// eslint-disable-next-line deprecation/deprecation
|
|
371
|
-
const rpcService = attributes[semanticConventions.SEMATTRS_RPC_SERVICE];
|
|
372
|
-
if (rpcService) {
|
|
373
|
-
return {
|
|
374
|
-
...getUserUpdatedNameAndSource(spanName, attributes, 'route'),
|
|
375
|
-
op: 'rpc',
|
|
376
|
-
};
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
// If messaging.system exists then this is a messaging system span.
|
|
380
|
-
// eslint-disable-next-line deprecation/deprecation
|
|
381
|
-
const messagingSystem = attributes[semanticConventions.SEMATTRS_MESSAGING_SYSTEM];
|
|
382
|
-
if (messagingSystem) {
|
|
383
|
-
return {
|
|
384
|
-
...getUserUpdatedNameAndSource(spanName, attributes, customSourceOrRoute),
|
|
385
|
-
op: 'message',
|
|
386
|
-
};
|
|
387
|
-
}
|
|
388
|
-
|
|
389
|
-
// If faas.trigger exists then this is a function as a service span.
|
|
390
|
-
// eslint-disable-next-line deprecation/deprecation
|
|
391
|
-
const faasTrigger = attributes[semanticConventions.SEMATTRS_FAAS_TRIGGER];
|
|
392
|
-
if (faasTrigger) {
|
|
393
|
-
return {
|
|
394
|
-
...getUserUpdatedNameAndSource(spanName, attributes, customSourceOrRoute),
|
|
395
|
-
op: faasTrigger.toString(),
|
|
396
|
-
};
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
return { op: undefined, description: spanName, source: 'custom' };
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
/**
|
|
403
|
-
* Extract better op/description from an otel span.
|
|
404
|
-
*
|
|
405
|
-
* Does not overwrite the span name if the source is already set to custom to ensure
|
|
406
|
-
* that user-updated span names are preserved. In this case, we only adjust the op but
|
|
407
|
-
* leave span description and source unchanged.
|
|
408
|
-
*
|
|
409
|
-
* Based on https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/7422ce2a06337f68a59b552b8c5a2ac125d6bae5/exporter/sentryexporter/sentry_exporter.go#L306
|
|
410
|
-
*/
|
|
411
|
-
function parseSpanDescription(span) {
|
|
412
|
-
const attributes = spanHasAttributes(span) ? span.attributes : {};
|
|
413
|
-
const name = spanHasName(span) ? span.name : '<unknown>';
|
|
414
|
-
const kind = getSpanKind(span);
|
|
415
|
-
|
|
416
|
-
return inferSpanData(name, attributes, kind);
|
|
417
|
-
}
|
|
418
|
-
|
|
419
|
-
function descriptionForDbSystem({ attributes, name }) {
|
|
420
|
-
// if we already have a custom name, we don't overwrite it but only set the op
|
|
421
|
-
const userDefinedName = attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];
|
|
422
|
-
if (typeof userDefinedName === 'string') {
|
|
423
|
-
return {
|
|
424
|
-
op: 'db',
|
|
425
|
-
description: userDefinedName,
|
|
426
|
-
source: (attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] ) || 'custom',
|
|
427
|
-
};
|
|
428
|
-
}
|
|
429
|
-
|
|
430
|
-
// if we already have the source set to custom, we don't overwrite the span description but only set the op
|
|
431
|
-
if (attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] === 'custom') {
|
|
432
|
-
return { op: 'db', description: name, source: 'custom' };
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
// Use DB statement (Ex "SELECT * FROM table") if possible as description.
|
|
436
|
-
// eslint-disable-next-line deprecation/deprecation
|
|
437
|
-
const statement = attributes[semanticConventions.SEMATTRS_DB_STATEMENT];
|
|
438
|
-
|
|
439
|
-
const description = statement ? statement.toString() : name;
|
|
440
|
-
|
|
441
|
-
return { op: 'db', description, source: 'task' };
|
|
442
|
-
}
|
|
443
|
-
|
|
444
|
-
/** Only exported for tests. */
|
|
445
|
-
function descriptionForHttpMethod(
|
|
446
|
-
{ name, kind, attributes },
|
|
447
|
-
httpMethod,
|
|
448
|
-
) {
|
|
449
|
-
const opParts = ['http'];
|
|
450
|
-
|
|
451
|
-
switch (kind) {
|
|
452
|
-
case api.SpanKind.CLIENT:
|
|
453
|
-
opParts.push('client');
|
|
454
|
-
break;
|
|
455
|
-
case api.SpanKind.SERVER:
|
|
456
|
-
opParts.push('server');
|
|
457
|
-
break;
|
|
458
|
-
}
|
|
459
|
-
|
|
460
|
-
// Spans for HTTP requests we have determined to be prefetch requests will have a `.prefetch` postfix in the op
|
|
461
|
-
if (attributes['sentry.http.prefetch']) {
|
|
462
|
-
opParts.push('prefetch');
|
|
463
|
-
}
|
|
464
|
-
|
|
465
|
-
const { urlPath, url, query, fragment, hasRoute } = getSanitizedUrl(attributes, kind);
|
|
466
|
-
|
|
467
|
-
if (!urlPath) {
|
|
468
|
-
return { ...getUserUpdatedNameAndSource(name, attributes), op: opParts.join('.') };
|
|
469
|
-
}
|
|
470
|
-
|
|
471
|
-
const graphqlOperationsAttribute = attributes[SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION];
|
|
472
|
-
|
|
473
|
-
// Ex. GET /api/users
|
|
474
|
-
const baseDescription = `${httpMethod} ${urlPath}`;
|
|
475
|
-
|
|
476
|
-
// When the http span has a graphql operation, append it to the description
|
|
477
|
-
// We add these in the graphqlIntegration
|
|
478
|
-
const inferredDescription = graphqlOperationsAttribute
|
|
479
|
-
? `${baseDescription} (${getGraphqlOperationNamesFromAttribute(graphqlOperationsAttribute)})`
|
|
480
|
-
: baseDescription;
|
|
481
|
-
|
|
482
|
-
// If `httpPath` is a root path, then we can categorize the transaction source as route.
|
|
483
|
-
const inferredSource = hasRoute || urlPath === '/' ? 'route' : 'url';
|
|
484
|
-
|
|
485
|
-
const data = {};
|
|
486
|
-
|
|
487
|
-
if (url) {
|
|
488
|
-
data.url = url;
|
|
489
|
-
}
|
|
490
|
-
if (query) {
|
|
491
|
-
data['http.query'] = query;
|
|
492
|
-
}
|
|
493
|
-
if (fragment) {
|
|
494
|
-
data['http.fragment'] = fragment;
|
|
495
|
-
}
|
|
496
|
-
|
|
497
|
-
// If the span kind is neither client nor server, we use the original name
|
|
498
|
-
// this infers that somebody manually started this span, in which case we don't want to overwrite the name
|
|
499
|
-
const isClientOrServerKind = kind === api.SpanKind.CLIENT || kind === api.SpanKind.SERVER;
|
|
500
|
-
|
|
501
|
-
// If the span is an auto-span (=it comes from one of our instrumentations),
|
|
502
|
-
// we always want to infer the name
|
|
503
|
-
// this is necessary because some of the auto-instrumentation we use uses kind=INTERNAL
|
|
504
|
-
const origin = attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] || 'manual';
|
|
505
|
-
const isManualSpan = !`${origin}`.startsWith('auto');
|
|
506
|
-
|
|
507
|
-
// If users (or in very rare occasions we) set the source to custom, we don't overwrite the name
|
|
508
|
-
const alreadyHasCustomSource = attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] === 'custom';
|
|
509
|
-
const customSpanName = attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];
|
|
510
|
-
|
|
511
|
-
const useInferredDescription =
|
|
512
|
-
!alreadyHasCustomSource && customSpanName == null && (isClientOrServerKind || !isManualSpan);
|
|
513
|
-
|
|
514
|
-
const { description, source } = useInferredDescription
|
|
515
|
-
? { description: inferredDescription, source: inferredSource }
|
|
516
|
-
: getUserUpdatedNameAndSource(name, attributes);
|
|
517
|
-
|
|
518
|
-
return {
|
|
519
|
-
op: opParts.join('.'),
|
|
520
|
-
description,
|
|
521
|
-
source,
|
|
522
|
-
data,
|
|
523
|
-
};
|
|
524
|
-
}
|
|
525
|
-
|
|
526
|
-
function getGraphqlOperationNamesFromAttribute(attr) {
|
|
527
|
-
if (Array.isArray(attr)) {
|
|
528
|
-
// oxlint-disable-next-line typescript/require-array-sort-compare
|
|
529
|
-
const sorted = attr.slice().sort();
|
|
530
|
-
|
|
531
|
-
// Up to 5 items, we just add all of them
|
|
532
|
-
if (sorted.length <= 5) {
|
|
533
|
-
return sorted.join(', ');
|
|
534
|
-
} else {
|
|
535
|
-
// Else, we add the first 5 and the diff of other operations
|
|
536
|
-
return `${sorted.slice(0, 5).join(', ')}, +${sorted.length - 5}`;
|
|
537
|
-
}
|
|
538
|
-
}
|
|
539
|
-
|
|
540
|
-
return `${attr}`;
|
|
541
|
-
}
|
|
542
|
-
|
|
543
|
-
/** Exported for tests only */
|
|
544
|
-
function getSanitizedUrl(
|
|
545
|
-
attributes,
|
|
546
|
-
kind,
|
|
547
|
-
)
|
|
548
|
-
|
|
549
|
-
{
|
|
550
|
-
// This is the relative path of the URL, e.g. /sub
|
|
551
|
-
// eslint-disable-next-line deprecation/deprecation
|
|
552
|
-
const httpTarget = attributes[semanticConventions.SEMATTRS_HTTP_TARGET];
|
|
553
|
-
// This is the full URL, including host & query params etc., e.g. https://example.com/sub?foo=bar
|
|
554
|
-
// eslint-disable-next-line deprecation/deprecation
|
|
555
|
-
const httpUrl = attributes[semanticConventions.SEMATTRS_HTTP_URL] || attributes[semanticConventions.ATTR_URL_FULL];
|
|
556
|
-
// This is the normalized route name - may not always be available!
|
|
557
|
-
const httpRoute = attributes[semanticConventions.ATTR_HTTP_ROUTE];
|
|
558
|
-
|
|
559
|
-
const parsedUrl = typeof httpUrl === 'string' ? core.parseUrl(httpUrl) : undefined;
|
|
560
|
-
const url = parsedUrl ? core.getSanitizedUrlString(parsedUrl) : undefined;
|
|
561
|
-
const query = parsedUrl?.search || undefined;
|
|
562
|
-
const fragment = parsedUrl?.hash || undefined;
|
|
563
|
-
|
|
564
|
-
if (typeof httpRoute === 'string') {
|
|
565
|
-
return { urlPath: httpRoute, url, query, fragment, hasRoute: true };
|
|
566
|
-
}
|
|
567
|
-
|
|
568
|
-
if (kind === api.SpanKind.SERVER && typeof httpTarget === 'string') {
|
|
569
|
-
return { urlPath: core.stripUrlQueryAndFragment(httpTarget), url, query, fragment, hasRoute: false };
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
if (parsedUrl) {
|
|
573
|
-
return { urlPath: url, url, query, fragment, hasRoute: false };
|
|
574
|
-
}
|
|
575
|
-
|
|
576
|
-
// fall back to target even for client spans, if no URL is present
|
|
577
|
-
if (typeof httpTarget === 'string') {
|
|
578
|
-
return { urlPath: core.stripUrlQueryAndFragment(httpTarget), url, query, fragment, hasRoute: false };
|
|
579
|
-
}
|
|
580
|
-
|
|
581
|
-
return { urlPath: undefined, url, query, fragment, hasRoute: false };
|
|
582
|
-
}
|
|
583
|
-
|
|
584
|
-
/**
|
|
585
|
-
* Because Otel instrumentation sometimes mutates span names via `span.updateName`, the only way
|
|
586
|
-
* to ensure that a user-set span name is preserved is to store it as a tmp attribute on the span.
|
|
587
|
-
* We delete this attribute once we're done with it when preparing the event envelope.
|
|
588
|
-
*
|
|
589
|
-
* This temp attribute always takes precedence over the original name.
|
|
590
|
-
*
|
|
591
|
-
* We also need to take care of setting the correct source. Users can always update the source
|
|
592
|
-
* after updating the name, so we need to respect that.
|
|
593
|
-
*
|
|
594
|
-
* @internal exported only for testing
|
|
595
|
-
*/
|
|
596
|
-
function getUserUpdatedNameAndSource(
|
|
597
|
-
originalName,
|
|
598
|
-
attributes,
|
|
599
|
-
fallbackSource = 'custom',
|
|
600
|
-
)
|
|
601
|
-
|
|
602
|
-
{
|
|
603
|
-
const source = (attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] ) || fallbackSource;
|
|
604
|
-
const description = attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];
|
|
605
|
-
|
|
606
|
-
if (description && typeof description === 'string') {
|
|
607
|
-
return {
|
|
608
|
-
description,
|
|
609
|
-
source,
|
|
610
|
-
};
|
|
611
|
-
}
|
|
612
|
-
|
|
613
|
-
return { description: originalName, source };
|
|
614
|
-
}
|
|
615
|
-
|
|
616
|
-
/**
|
|
617
|
-
* Setup a DSC handler on the passed client,
|
|
618
|
-
* ensuring that the transaction name is inferred from the span correctly.
|
|
619
|
-
*/
|
|
620
|
-
function enhanceDscWithOpenTelemetryRootSpanName(client) {
|
|
621
|
-
client.on('createDsc', (dsc, rootSpan) => {
|
|
622
|
-
if (!rootSpan) {
|
|
623
|
-
return;
|
|
624
|
-
}
|
|
625
|
-
|
|
626
|
-
// We want to overwrite the transaction on the DSC that is created by default in core
|
|
627
|
-
// The reason for this is that we want to infer the span name, not use the initial one
|
|
628
|
-
// Otherwise, we'll get names like "GET" instead of e.g. "GET /foo"
|
|
629
|
-
// `parseSpanDescription` takes the attributes of the span into account for the name
|
|
630
|
-
// This mutates the passed-in DSC
|
|
631
|
-
|
|
632
|
-
const jsonSpan = core.spanToJSON(rootSpan);
|
|
633
|
-
const attributes = jsonSpan.data;
|
|
634
|
-
const source = attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
|
|
635
|
-
|
|
636
|
-
const { description } = spanHasName(rootSpan) ? parseSpanDescription(rootSpan) : { description: undefined };
|
|
637
|
-
if (source !== 'url' && description) {
|
|
638
|
-
dsc.transaction = description;
|
|
639
|
-
}
|
|
640
|
-
|
|
641
|
-
// Also ensure sampling decision is correctly inferred
|
|
642
|
-
// In core, we use `spanIsSampled`, which just looks at the trace flags
|
|
643
|
-
// but in OTEL, we use a slightly more complex logic to be able to differntiate between unsampled and deferred sampling
|
|
644
|
-
if (core.hasSpansEnabled()) {
|
|
645
|
-
const sampled = getSamplingDecision(rootSpan.spanContext());
|
|
646
|
-
dsc.sampled = sampled == undefined ? undefined : String(sampled);
|
|
647
|
-
}
|
|
648
|
-
});
|
|
649
|
-
}
|
|
650
|
-
|
|
651
|
-
/**
|
|
652
|
-
* Returns the currently active span.
|
|
653
|
-
*/
|
|
654
|
-
function getActiveSpan() {
|
|
655
|
-
return api.trace.getActiveSpan();
|
|
656
|
-
}
|
|
657
|
-
|
|
658
|
-
/**
|
|
659
|
-
* Generate a TraceState for the given data.
|
|
660
|
-
*/
|
|
661
|
-
function makeTraceState({
|
|
662
|
-
dsc,
|
|
663
|
-
sampled,
|
|
664
|
-
}
|
|
665
|
-
|
|
666
|
-
) {
|
|
667
|
-
// We store the DSC as OTEL trace state on the span context
|
|
668
|
-
const dscString = dsc ? core.dynamicSamplingContextToSentryBaggageHeader(dsc) : undefined;
|
|
669
|
-
|
|
670
|
-
const traceStateBase = new core$1.TraceState();
|
|
671
|
-
|
|
672
|
-
const traceStateWithDsc = dscString ? traceStateBase.set(SENTRY_TRACE_STATE_DSC, dscString) : traceStateBase;
|
|
673
|
-
|
|
674
|
-
// We also specifically want to store if this is sampled to be not recording,
|
|
675
|
-
// or unsampled (=could be either sampled or not)
|
|
676
|
-
return sampled === false ? traceStateWithDsc.set(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING, '1') : traceStateWithDsc;
|
|
677
|
-
}
|
|
678
|
-
|
|
679
|
-
const setupElements = new Set();
|
|
680
|
-
|
|
681
|
-
/** Get all the OpenTelemetry elements that have been set up. */
|
|
682
|
-
function openTelemetrySetupCheck() {
|
|
683
|
-
return Array.from(setupElements);
|
|
684
|
-
}
|
|
685
|
-
|
|
686
|
-
/** Mark an OpenTelemetry element as setup. */
|
|
687
|
-
function setIsSetup(element) {
|
|
688
|
-
setupElements.add(element);
|
|
689
|
-
}
|
|
690
|
-
|
|
691
|
-
/**
|
|
692
|
-
* Injects and extracts `sentry-trace` and `baggage` headers from carriers.
|
|
693
|
-
*/
|
|
694
|
-
class SentryPropagator extends core$1.W3CBaggagePropagator {
|
|
695
|
-
/** A map of URLs that have already been checked for if they match tracePropagationTargets. */
|
|
696
|
-
|
|
697
|
-
constructor() {
|
|
698
|
-
super();
|
|
699
|
-
setIsSetup('SentryPropagator');
|
|
700
|
-
|
|
701
|
-
// We're caching results so we don't have to recompute regexp every time we create a request.
|
|
702
|
-
this._urlMatchesTargetsMap = new core.LRUMap(100);
|
|
703
|
-
}
|
|
704
|
-
|
|
705
|
-
/**
|
|
706
|
-
* @inheritDoc
|
|
707
|
-
*/
|
|
708
|
-
inject(context, carrier, setter) {
|
|
709
|
-
if (core$1.isTracingSuppressed(context)) {
|
|
710
|
-
debugBuild.DEBUG_BUILD && core.debug.log('[Tracing] Not injecting trace data for url because tracing is suppressed.');
|
|
711
|
-
return;
|
|
712
|
-
}
|
|
713
|
-
|
|
714
|
-
const activeSpan = api.trace.getSpan(context);
|
|
715
|
-
const url = activeSpan && getCurrentURL(activeSpan);
|
|
716
|
-
|
|
717
|
-
const { tracePropagationTargets, propagateTraceparent } = core.getClient()?.getOptions() || {};
|
|
718
|
-
if (!core.shouldPropagateTraceForUrl(url, tracePropagationTargets, this._urlMatchesTargetsMap)) {
|
|
719
|
-
debugBuild.DEBUG_BUILD &&
|
|
720
|
-
core.debug.log('[Tracing] Not injecting trace data for url because it does not match tracePropagationTargets:', url);
|
|
721
|
-
return;
|
|
722
|
-
}
|
|
723
|
-
|
|
724
|
-
const existingBaggageHeader = getExistingBaggage(carrier);
|
|
725
|
-
const existingSentryTraceHeader = getExistingSentryTrace(carrier);
|
|
726
|
-
|
|
727
|
-
let baggage = api.propagation.getBaggage(context) || api.propagation.createBaggage({});
|
|
728
|
-
|
|
729
|
-
const { dynamicSamplingContext, traceId, spanId, sampled } = getInjectionData(context);
|
|
730
|
-
|
|
731
|
-
if (existingBaggageHeader) {
|
|
732
|
-
const baggageEntries = core.parseBaggageHeader(existingBaggageHeader);
|
|
733
|
-
|
|
734
|
-
if (baggageEntries) {
|
|
735
|
-
Object.entries(baggageEntries).forEach(([key, value]) => {
|
|
736
|
-
if (!existingSentryTraceHeader && key.startsWith(core.SENTRY_BAGGAGE_KEY_PREFIX)) {
|
|
737
|
-
// Edge case: A baggage header with sentry- keys was added previously but no
|
|
738
|
-
// sentry-trace header. In this case we remove the old sentry-keys and add new
|
|
739
|
-
// ones below.
|
|
740
|
-
return;
|
|
741
|
-
}
|
|
742
|
-
baggage = baggage.setEntry(key, { value });
|
|
743
|
-
});
|
|
744
|
-
}
|
|
745
|
-
}
|
|
746
|
-
|
|
747
|
-
if (!existingSentryTraceHeader && dynamicSamplingContext) {
|
|
748
|
-
baggage = Object.entries(dynamicSamplingContext).reduce((b, [dscKey, dscValue]) => {
|
|
749
|
-
if (dscValue) {
|
|
750
|
-
return b.setEntry(`${core.SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`, { value: dscValue });
|
|
751
|
-
}
|
|
752
|
-
return b;
|
|
753
|
-
}, baggage);
|
|
754
|
-
}
|
|
755
|
-
|
|
756
|
-
// We also want to avoid setting the default OTEL trace ID, if we get that for whatever reason
|
|
757
|
-
if (!existingSentryTraceHeader && traceId && traceId !== api.INVALID_TRACEID) {
|
|
758
|
-
setter.set(carrier, SENTRY_TRACE_HEADER, core.generateSentryTraceHeader(traceId, spanId, sampled));
|
|
759
|
-
|
|
760
|
-
if (propagateTraceparent) {
|
|
761
|
-
setter.set(carrier, 'traceparent', core.generateTraceparentHeader(traceId, spanId, sampled));
|
|
762
|
-
}
|
|
763
|
-
}
|
|
764
|
-
|
|
765
|
-
super.inject(api.propagation.setBaggage(context, baggage), carrier, setter);
|
|
766
|
-
}
|
|
767
|
-
|
|
768
|
-
/**
|
|
769
|
-
* @inheritDoc
|
|
770
|
-
*/
|
|
771
|
-
extract(context, carrier, getter) {
|
|
772
|
-
const maybeSentryTraceHeader = getter.get(carrier, SENTRY_TRACE_HEADER);
|
|
773
|
-
const baggage = getter.get(carrier, SENTRY_BAGGAGE_HEADER);
|
|
774
|
-
|
|
775
|
-
const sentryTrace = maybeSentryTraceHeader
|
|
776
|
-
? Array.isArray(maybeSentryTraceHeader)
|
|
777
|
-
? maybeSentryTraceHeader[0]
|
|
778
|
-
: maybeSentryTraceHeader
|
|
779
|
-
: undefined;
|
|
780
|
-
|
|
781
|
-
// Add remote parent span context
|
|
782
|
-
// If there is no incoming trace, this will return the context as-is
|
|
783
|
-
return ensureScopesOnContext(getContextWithRemoteActiveSpan(context, { sentryTrace, baggage }));
|
|
784
|
-
}
|
|
785
|
-
|
|
786
|
-
/**
|
|
787
|
-
* @inheritDoc
|
|
788
|
-
*/
|
|
789
|
-
fields() {
|
|
790
|
-
return [SENTRY_TRACE_HEADER, SENTRY_BAGGAGE_HEADER, 'traceparent'];
|
|
791
|
-
}
|
|
792
|
-
}
|
|
793
|
-
|
|
794
|
-
/**
|
|
795
|
-
* Get propagation injection data for the given context.
|
|
796
|
-
* The additional options can be passed to override the scope and client that is otherwise derived from the context.
|
|
797
|
-
*/
|
|
798
|
-
function getInjectionData(
|
|
799
|
-
context,
|
|
800
|
-
options = {},
|
|
801
|
-
)
|
|
802
|
-
|
|
803
|
-
{
|
|
804
|
-
const span = api.trace.getSpan(context);
|
|
805
|
-
|
|
806
|
-
// If we have a remote span, the spanId should be considered as the parentSpanId, not spanId itself
|
|
807
|
-
// Instead, we use a virtual (generated) spanId for propagation
|
|
808
|
-
if (span?.spanContext().isRemote) {
|
|
809
|
-
const spanContext = span.spanContext();
|
|
810
|
-
const dynamicSamplingContext = core.getDynamicSamplingContextFromSpan(span);
|
|
811
|
-
|
|
812
|
-
return {
|
|
813
|
-
dynamicSamplingContext,
|
|
814
|
-
traceId: spanContext.traceId,
|
|
815
|
-
spanId: undefined,
|
|
816
|
-
sampled: getSamplingDecision(spanContext), // TODO: Do we need to change something here?
|
|
817
|
-
};
|
|
818
|
-
}
|
|
819
|
-
|
|
820
|
-
// If we have a local span, we just use this
|
|
821
|
-
if (span) {
|
|
822
|
-
const spanContext = span.spanContext();
|
|
823
|
-
const dynamicSamplingContext = core.getDynamicSamplingContextFromSpan(span);
|
|
824
|
-
|
|
825
|
-
return {
|
|
826
|
-
dynamicSamplingContext,
|
|
827
|
-
traceId: spanContext.traceId,
|
|
828
|
-
spanId: spanContext.spanId,
|
|
829
|
-
sampled: getSamplingDecision(spanContext), // TODO: Do we need to change something here?
|
|
830
|
-
};
|
|
831
|
-
}
|
|
832
|
-
|
|
833
|
-
// Else we try to use the propagation context from the scope
|
|
834
|
-
// The only scenario where this should happen is when we neither have a span, nor an incoming trace
|
|
835
|
-
const scope = options.scope || getScopesFromContext(context)?.scope || core.getCurrentScope();
|
|
836
|
-
const client = options.client || core.getClient();
|
|
837
|
-
|
|
838
|
-
const propagationContext = scope.getPropagationContext();
|
|
839
|
-
const dynamicSamplingContext = client ? core.getDynamicSamplingContextFromScope(client, scope) : undefined;
|
|
840
|
-
return {
|
|
841
|
-
dynamicSamplingContext,
|
|
842
|
-
traceId: propagationContext.traceId,
|
|
843
|
-
spanId: propagationContext.propagationSpanId,
|
|
844
|
-
sampled: propagationContext.sampled,
|
|
845
|
-
};
|
|
846
|
-
}
|
|
847
|
-
|
|
848
|
-
function getContextWithRemoteActiveSpan(
|
|
849
|
-
ctx,
|
|
850
|
-
{ sentryTrace, baggage },
|
|
851
|
-
) {
|
|
852
|
-
const propagationContext = core.propagationContextFromHeaders(sentryTrace, baggage);
|
|
853
|
-
|
|
854
|
-
const { traceId, parentSpanId, sampled, dsc } = propagationContext;
|
|
855
|
-
|
|
856
|
-
const client = core.getClient();
|
|
857
|
-
const incomingDsc = core.baggageHeaderToDynamicSamplingContext(baggage);
|
|
858
|
-
|
|
859
|
-
// We only want to set the virtual span if we are continuing a concrete trace
|
|
860
|
-
// Otherwise, we ignore the incoming trace here, e.g. if we have no trace headers
|
|
861
|
-
if (!parentSpanId || (client && !core.shouldContinueTrace(client, incomingDsc?.org_id))) {
|
|
862
|
-
return ctx;
|
|
863
|
-
}
|
|
864
|
-
|
|
865
|
-
const spanContext = generateRemoteSpanContext({
|
|
866
|
-
traceId,
|
|
867
|
-
spanId: parentSpanId,
|
|
868
|
-
sampled,
|
|
869
|
-
dsc,
|
|
870
|
-
});
|
|
871
|
-
|
|
872
|
-
return api.trace.setSpanContext(ctx, spanContext);
|
|
873
|
-
}
|
|
874
|
-
|
|
875
|
-
/**
|
|
876
|
-
* Takes trace strings and propagates them as a remote active span.
|
|
877
|
-
* This should be used in addition to `continueTrace` in OTEL-powered environments.
|
|
878
|
-
*/
|
|
879
|
-
function continueTraceAsRemoteSpan(
|
|
880
|
-
ctx,
|
|
881
|
-
options,
|
|
882
|
-
callback,
|
|
883
|
-
) {
|
|
884
|
-
const ctxWithSpanContext = ensureScopesOnContext(getContextWithRemoteActiveSpan(ctx, options));
|
|
885
|
-
|
|
886
|
-
return api.context.with(ctxWithSpanContext, callback);
|
|
887
|
-
}
|
|
888
|
-
|
|
889
|
-
function ensureScopesOnContext(ctx) {
|
|
890
|
-
// If there are no scopes yet on the context, ensure we have them
|
|
891
|
-
const scopes = getScopesFromContext(ctx);
|
|
892
|
-
const newScopes = {
|
|
893
|
-
// If we have no scope here, this is most likely either the root context or a context manually derived from it
|
|
894
|
-
// In this case, we want to fork the current scope, to ensure we do not pollute the root scope
|
|
895
|
-
scope: scopes ? scopes.scope : core.getCurrentScope().clone(),
|
|
896
|
-
isolationScope: scopes ? scopes.isolationScope : core.getIsolationScope(),
|
|
897
|
-
};
|
|
898
|
-
|
|
899
|
-
return setScopesOnContext(ctx, newScopes);
|
|
900
|
-
}
|
|
901
|
-
|
|
902
|
-
/** Try to get the existing baggage header so we can merge this in. */
|
|
903
|
-
function getExistingBaggage(carrier) {
|
|
904
|
-
try {
|
|
905
|
-
const baggage = (carrier )[SENTRY_BAGGAGE_HEADER];
|
|
906
|
-
return Array.isArray(baggage) ? baggage.join(',') : baggage;
|
|
907
|
-
} catch {
|
|
908
|
-
return undefined;
|
|
909
|
-
}
|
|
910
|
-
}
|
|
911
|
-
|
|
912
|
-
function getExistingSentryTrace(carrier) {
|
|
913
|
-
try {
|
|
914
|
-
return (carrier )[SENTRY_TRACE_HEADER];
|
|
915
|
-
} catch {
|
|
916
|
-
return undefined;
|
|
917
|
-
}
|
|
918
|
-
}
|
|
919
|
-
|
|
920
|
-
/**
|
|
921
|
-
* It is pretty tricky to get access to the outgoing request URL of a request in the propagator.
|
|
922
|
-
* As we only have access to the context of the span to be sent and the carrier (=headers),
|
|
923
|
-
* but the span may be unsampled and thus have no attributes.
|
|
924
|
-
*
|
|
925
|
-
* So we use the following logic:
|
|
926
|
-
* 1. If we have an active span, we check if it has a URL attribute.
|
|
927
|
-
* 2. Else, if the active span has no URL attribute (e.g. it is unsampled), we check a special trace state (which we set in our sampler).
|
|
928
|
-
*/
|
|
929
|
-
function getCurrentURL(span) {
|
|
930
|
-
const spanData = core.spanToJSON(span).data;
|
|
931
|
-
// `ATTR_URL_FULL` is the new attribute, but we still support the old one, `SEMATTRS_HTTP_URL`, for now.
|
|
932
|
-
// eslint-disable-next-line deprecation/deprecation
|
|
933
|
-
const urlAttribute = spanData[semanticConventions.SEMATTRS_HTTP_URL] || spanData[semanticConventions.ATTR_URL_FULL];
|
|
934
|
-
if (typeof urlAttribute === 'string') {
|
|
935
|
-
return urlAttribute;
|
|
936
|
-
}
|
|
937
|
-
|
|
938
|
-
// Also look at the traceState, which we may set in the sampler even for unsampled spans
|
|
939
|
-
const urlTraceState = span.spanContext().traceState?.get(SENTRY_TRACE_STATE_URL);
|
|
940
|
-
if (urlTraceState) {
|
|
941
|
-
return urlTraceState;
|
|
942
|
-
}
|
|
943
|
-
|
|
944
|
-
return undefined;
|
|
945
|
-
}
|
|
946
|
-
|
|
947
|
-
function generateRemoteSpanContext({
|
|
948
|
-
spanId,
|
|
949
|
-
traceId,
|
|
950
|
-
sampled,
|
|
951
|
-
dsc,
|
|
952
|
-
}
|
|
953
|
-
|
|
954
|
-
) {
|
|
955
|
-
// We store the DSC as OTEL trace state on the span context
|
|
956
|
-
const traceState = makeTraceState({
|
|
957
|
-
dsc,
|
|
958
|
-
sampled,
|
|
959
|
-
});
|
|
960
|
-
|
|
961
|
-
const spanContext = {
|
|
962
|
-
traceId,
|
|
963
|
-
spanId,
|
|
964
|
-
isRemote: true,
|
|
965
|
-
traceFlags: sampled ? api.TraceFlags.SAMPLED : api.TraceFlags.NONE,
|
|
966
|
-
traceState,
|
|
967
|
-
};
|
|
968
|
-
|
|
969
|
-
return spanContext;
|
|
970
|
-
}
|
|
971
|
-
|
|
972
|
-
/**
|
|
973
|
-
* Internal helper for starting spans and manual spans. See {@link startSpan} and {@link startSpanManual} for the public APIs.
|
|
974
|
-
* @param options - The span context options
|
|
975
|
-
* @param callback - The callback to execute with the span
|
|
976
|
-
* @param autoEnd - Whether to automatically end the span after the callback completes
|
|
977
|
-
*/
|
|
978
|
-
function _startSpan(options, callback, autoEnd) {
|
|
979
|
-
const tracer = getTracer();
|
|
980
|
-
|
|
981
|
-
const { name, parentSpan: customParentSpan } = options;
|
|
982
|
-
|
|
983
|
-
// If `options.parentSpan` is defined, we want to wrap the callback in `withActiveSpan`
|
|
984
|
-
const wrapper = getActiveSpanWrapper(customParentSpan);
|
|
985
|
-
|
|
986
|
-
return wrapper(() => {
|
|
987
|
-
const activeCtx = getContext(options.scope, options.forceTransaction);
|
|
988
|
-
const missingRequiredParent = options.onlyIfParent && !api.trace.getSpan(activeCtx);
|
|
989
|
-
const ctx = missingRequiredParent ? core$1.suppressTracing(activeCtx) : activeCtx;
|
|
990
|
-
|
|
991
|
-
if (missingRequiredParent) {
|
|
992
|
-
core.getClient()?.recordDroppedEvent('no_parent_span', 'span');
|
|
993
|
-
}
|
|
994
|
-
|
|
995
|
-
const spanOptions = getSpanOptions(options);
|
|
996
|
-
|
|
997
|
-
// If spans are not enabled, ensure we suppress tracing for the span creation
|
|
998
|
-
// but preserve the original context for the callback execution
|
|
999
|
-
// This ensures that we don't create spans when tracing is disabled which
|
|
1000
|
-
// would otherwise be a problem for users that don't enable tracing but use
|
|
1001
|
-
// custom OpenTelemetry setups.
|
|
1002
|
-
if (!core.hasSpansEnabled()) {
|
|
1003
|
-
const suppressedCtx = core$1.isTracingSuppressed(ctx) ? ctx : core$1.suppressTracing(ctx);
|
|
1004
|
-
|
|
1005
|
-
return api.context.with(suppressedCtx, () => {
|
|
1006
|
-
return tracer.startActiveSpan(name, spanOptions, suppressedCtx, span => {
|
|
1007
|
-
patchSpanEnd(span);
|
|
1008
|
-
// Restore the original unsuppressed context for the callback execution
|
|
1009
|
-
// so that custom OpenTelemetry spans maintain the correct context.
|
|
1010
|
-
// We use activeCtx (not ctx) because ctx may be suppressed when onlyIfParent is true
|
|
1011
|
-
// and no parent span exists. Using activeCtx ensures custom OTel spans are never
|
|
1012
|
-
// inadvertently suppressed.
|
|
1013
|
-
return api.context.with(activeCtx, () => {
|
|
1014
|
-
return core.handleCallbackErrors(
|
|
1015
|
-
() => callback(span),
|
|
1016
|
-
() => {
|
|
1017
|
-
// Only set the span status to ERROR when there wasn't any status set before, in order to avoid stomping useful span statuses
|
|
1018
|
-
if (core.spanToJSON(span).status === undefined) {
|
|
1019
|
-
span.setStatus({ code: api.SpanStatusCode.ERROR });
|
|
1020
|
-
}
|
|
1021
|
-
},
|
|
1022
|
-
autoEnd ? () => span.end() : undefined,
|
|
1023
|
-
);
|
|
1024
|
-
});
|
|
1025
|
-
});
|
|
1026
|
-
});
|
|
1027
|
-
}
|
|
1028
|
-
|
|
1029
|
-
return tracer.startActiveSpan(name, spanOptions, ctx, span => {
|
|
1030
|
-
patchSpanEnd(span);
|
|
1031
|
-
return core.handleCallbackErrors(
|
|
1032
|
-
() => callback(span),
|
|
1033
|
-
() => {
|
|
1034
|
-
// Only set the span status to ERROR when there wasn't any status set before, in order to avoid stomping useful span statuses
|
|
1035
|
-
if (core.spanToJSON(span).status === undefined) {
|
|
1036
|
-
span.setStatus({ code: api.SpanStatusCode.ERROR });
|
|
1037
|
-
}
|
|
1038
|
-
},
|
|
1039
|
-
autoEnd ? () => span.end() : undefined,
|
|
1040
|
-
);
|
|
1041
|
-
});
|
|
1042
|
-
});
|
|
1043
|
-
}
|
|
1044
|
-
|
|
1045
|
-
/**
|
|
1046
|
-
* Wraps a function with a transaction/span and finishes the span after the function is done.
|
|
1047
|
-
* The created span is the active span and will be used as parent by other spans created inside the function
|
|
1048
|
-
* and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.
|
|
1049
|
-
*
|
|
1050
|
-
* If you want to create a span that is not set as active, use {@link startInactiveSpan}.
|
|
1051
|
-
*
|
|
1052
|
-
* You'll always get a span passed to the callback,
|
|
1053
|
-
* it may just be a non-recording span if the span is not sampled or if tracing is disabled.
|
|
1054
|
-
*/
|
|
1055
|
-
function startSpan(options, callback) {
|
|
1056
|
-
return _startSpan(options, callback, true);
|
|
1057
|
-
}
|
|
1058
|
-
|
|
1059
|
-
/**
|
|
1060
|
-
* Similar to `Sentry.startSpan`. Wraps a function with a span, but does not finish the span
|
|
1061
|
-
* after the function is done automatically. You'll have to call `span.end()` or the `finish` function passed to the callback manually.
|
|
1062
|
-
*
|
|
1063
|
-
* The created span is the active span and will be used as parent by other spans created inside the function
|
|
1064
|
-
* and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.
|
|
1065
|
-
*
|
|
1066
|
-
* You'll always get a span passed to the callback,
|
|
1067
|
-
* it may just be a non-recording span if the span is not sampled or if tracing is disabled.
|
|
1068
|
-
*/
|
|
1069
|
-
function startSpanManual(
|
|
1070
|
-
options,
|
|
1071
|
-
callback,
|
|
1072
|
-
) {
|
|
1073
|
-
return _startSpan(options, span => callback(span, () => span.end()), false);
|
|
1074
|
-
}
|
|
1075
|
-
|
|
1076
|
-
/**
|
|
1077
|
-
* Creates a span. This span is not set as active, so will not get automatic instrumentation spans
|
|
1078
|
-
* as children or be able to be accessed via `Sentry.getActiveSpan()`.
|
|
1079
|
-
*
|
|
1080
|
-
* If you want to create a span that is set as active, use {@link startSpan}.
|
|
1081
|
-
*
|
|
1082
|
-
* This function will always return a span,
|
|
1083
|
-
* it may just be a non-recording span if the span is not sampled or if tracing is disabled.
|
|
1084
|
-
*/
|
|
1085
|
-
function startInactiveSpan(options) {
|
|
1086
|
-
const tracer = getTracer();
|
|
1087
|
-
|
|
1088
|
-
const { name, parentSpan: customParentSpan } = options;
|
|
1089
|
-
|
|
1090
|
-
// If `options.parentSpan` is defined, we want to wrap the callback in `withActiveSpan`
|
|
1091
|
-
const wrapper = getActiveSpanWrapper(customParentSpan);
|
|
1092
|
-
|
|
1093
|
-
return wrapper(() => {
|
|
1094
|
-
const activeCtx = getContext(options.scope, options.forceTransaction);
|
|
1095
|
-
const missingRequiredParent = options.onlyIfParent && !api.trace.getSpan(activeCtx);
|
|
1096
|
-
let ctx = missingRequiredParent ? core$1.suppressTracing(activeCtx) : activeCtx;
|
|
1097
|
-
|
|
1098
|
-
if (missingRequiredParent) {
|
|
1099
|
-
core.getClient()?.recordDroppedEvent('no_parent_span', 'span');
|
|
1100
|
-
}
|
|
1101
|
-
|
|
1102
|
-
const spanOptions = getSpanOptions(options);
|
|
1103
|
-
|
|
1104
|
-
if (!core.hasSpansEnabled()) {
|
|
1105
|
-
ctx = core$1.isTracingSuppressed(ctx) ? ctx : core$1.suppressTracing(ctx);
|
|
1106
|
-
}
|
|
1107
|
-
|
|
1108
|
-
const span = tracer.startSpan(name, spanOptions, ctx);
|
|
1109
|
-
patchSpanEnd(span);
|
|
1110
|
-
return span;
|
|
1111
|
-
});
|
|
1112
|
-
}
|
|
1113
|
-
|
|
1114
|
-
/**
|
|
1115
|
-
* Forks the current scope and sets the provided span as active span in the context of the provided callback. Can be
|
|
1116
|
-
* passed `null` to start an entirely new span tree.
|
|
1117
|
-
*
|
|
1118
|
-
* @param span Spans started in the context of the provided callback will be children of this span. If `null` is passed,
|
|
1119
|
-
* spans started within the callback will be root spans.
|
|
1120
|
-
* @param callback Execution context in which the provided span will be active. Is passed the newly forked scope.
|
|
1121
|
-
* @returns the value returned from the provided callback function.
|
|
1122
|
-
*/
|
|
1123
|
-
function withActiveSpan(span, callback) {
|
|
1124
|
-
const newContextWithActiveSpan = span ? api.trace.setSpan(api.context.active(), span) : api.trace.deleteSpan(api.context.active());
|
|
1125
|
-
return api.context.with(newContextWithActiveSpan, () => callback(core.getCurrentScope()));
|
|
1126
|
-
}
|
|
1127
|
-
|
|
1128
|
-
function getTracer() {
|
|
1129
|
-
const client = core.getClient();
|
|
1130
|
-
return client?.tracer || api.trace.getTracer('@sentry/opentelemetry', core.SDK_VERSION);
|
|
1131
|
-
}
|
|
1132
|
-
|
|
1133
|
-
function getSpanOptions(options) {
|
|
1134
|
-
const { startTime, attributes, kind, op, links } = options;
|
|
1135
|
-
|
|
1136
|
-
// OTEL expects timestamps in ms, not seconds
|
|
1137
|
-
const fixedStartTime = typeof startTime === 'number' ? ensureTimestampInMilliseconds(startTime) : startTime;
|
|
1138
|
-
|
|
1139
|
-
return {
|
|
1140
|
-
attributes: op
|
|
1141
|
-
? {
|
|
1142
|
-
[core.SEMANTIC_ATTRIBUTE_SENTRY_OP]: op,
|
|
1143
|
-
...attributes,
|
|
1144
|
-
}
|
|
1145
|
-
: attributes,
|
|
1146
|
-
kind,
|
|
1147
|
-
links,
|
|
1148
|
-
startTime: fixedStartTime,
|
|
1149
|
-
};
|
|
1150
|
-
}
|
|
1151
|
-
|
|
1152
|
-
function ensureTimestampInMilliseconds(timestamp) {
|
|
1153
|
-
const isMs = timestamp < 9999999999;
|
|
1154
|
-
return isMs ? timestamp * 1000 : timestamp;
|
|
1155
|
-
}
|
|
1156
|
-
|
|
1157
|
-
/**
|
|
1158
|
-
* Wraps the span's `end()` method so that numeric timestamps passed in seconds
|
|
1159
|
-
* are converted to milliseconds before reaching OTel's native `Span.end()`.
|
|
1160
|
-
*/
|
|
1161
|
-
function patchSpanEnd(span) {
|
|
1162
|
-
const originalEnd = span.end.bind(span);
|
|
1163
|
-
span.end = (endTime) => {
|
|
1164
|
-
return originalEnd(typeof endTime === 'number' ? ensureTimestampInMilliseconds(endTime) : endTime);
|
|
1165
|
-
};
|
|
1166
|
-
}
|
|
1167
|
-
|
|
1168
|
-
function getContext(scope, forceTransaction) {
|
|
1169
|
-
const ctx = getContextForScope(scope);
|
|
1170
|
-
const parentSpan = api.trace.getSpan(ctx);
|
|
1171
|
-
|
|
1172
|
-
// In the case that we have no parent span, we start a new trace
|
|
1173
|
-
// Note that if we continue a trace, we'll always have a remote parent span here anyhow
|
|
1174
|
-
if (!parentSpan) {
|
|
1175
|
-
return ctx;
|
|
1176
|
-
}
|
|
1177
|
-
|
|
1178
|
-
// If we don't want to force a transaction, and we have a parent span, all good, we just return as-is!
|
|
1179
|
-
if (!forceTransaction) {
|
|
1180
|
-
return ctx;
|
|
1181
|
-
}
|
|
1182
|
-
|
|
1183
|
-
// Else, if we do have a parent span but want to force a transaction, we have to simulate a "root" context
|
|
1184
|
-
|
|
1185
|
-
// Else, we need to do two things:
|
|
1186
|
-
// 1. Unset the parent span from the context, so we'll create a new root span
|
|
1187
|
-
// 2. Ensure the propagation context is correct, so we'll continue from the parent span
|
|
1188
|
-
const ctxWithoutSpan = api.trace.deleteSpan(ctx);
|
|
1189
|
-
|
|
1190
|
-
const { spanId, traceId } = parentSpan.spanContext();
|
|
1191
|
-
const sampled = getSamplingDecision(parentSpan.spanContext());
|
|
1192
|
-
|
|
1193
|
-
// In this case, when we are forcing a transaction, we want to treat this like continuing an incoming trace
|
|
1194
|
-
// so we set the traceState according to the root span
|
|
1195
|
-
const rootSpan = core.getRootSpan(parentSpan);
|
|
1196
|
-
const dsc = core.getDynamicSamplingContextFromSpan(rootSpan);
|
|
1197
|
-
|
|
1198
|
-
const traceState = makeTraceState({
|
|
1199
|
-
dsc,
|
|
1200
|
-
sampled,
|
|
1201
|
-
});
|
|
1202
|
-
|
|
1203
|
-
const spanOptions = {
|
|
1204
|
-
traceId,
|
|
1205
|
-
spanId,
|
|
1206
|
-
isRemote: true,
|
|
1207
|
-
traceFlags: sampled ? api.TraceFlags.SAMPLED : api.TraceFlags.NONE,
|
|
1208
|
-
traceState,
|
|
1209
|
-
};
|
|
1210
|
-
|
|
1211
|
-
const ctxWithSpanContext = api.trace.setSpanContext(ctxWithoutSpan, spanOptions);
|
|
1212
|
-
|
|
1213
|
-
return ctxWithSpanContext;
|
|
1214
|
-
}
|
|
1215
|
-
|
|
1216
|
-
function getContextForScope(scope) {
|
|
1217
|
-
if (scope) {
|
|
1218
|
-
const ctx = getContextFromScope(scope);
|
|
1219
|
-
if (ctx) {
|
|
1220
|
-
return ctx;
|
|
1221
|
-
}
|
|
1222
|
-
}
|
|
1223
|
-
|
|
1224
|
-
return api.context.active();
|
|
1225
|
-
}
|
|
1226
|
-
|
|
1227
|
-
/**
|
|
1228
|
-
* Continue a trace from `sentry-trace` and `baggage` values.
|
|
1229
|
-
* These values can be obtained from incoming request headers, or in the browser from `<meta name="sentry-trace">`
|
|
1230
|
-
* and `<meta name="baggage">` HTML tags.
|
|
1231
|
-
*
|
|
1232
|
-
* Spans started with `startSpan`, `startSpanManual` and `startInactiveSpan`, within the callback will automatically
|
|
1233
|
-
* be attached to the incoming trace.
|
|
1234
|
-
*
|
|
1235
|
-
* This is a custom version of `continueTrace` that is used in OTEL-powered environments.
|
|
1236
|
-
* It propagates the trace as a remote span, in addition to setting it on the propagation context.
|
|
1237
|
-
*/
|
|
1238
|
-
function continueTrace(options, callback) {
|
|
1239
|
-
return continueTraceAsRemoteSpan(api.context.active(), options, callback);
|
|
1240
|
-
}
|
|
1241
|
-
|
|
1242
|
-
/**
|
|
1243
|
-
* Start a new trace with a unique traceId, ensuring all spans created within the callback
|
|
1244
|
-
* share the same traceId.
|
|
1245
|
-
*
|
|
1246
|
-
* This is a custom version of `startNewTrace` for OTEL-powered environments.
|
|
1247
|
-
* It injects the new traceId as a remote span context into the OTEL context, so that
|
|
1248
|
-
* `startInactiveSpan` and `startSpan` pick it up correctly.
|
|
1249
|
-
*/
|
|
1250
|
-
function startNewTrace(callback) {
|
|
1251
|
-
const traceId = core.generateTraceId();
|
|
1252
|
-
const spanId = core.generateSpanId();
|
|
1253
|
-
|
|
1254
|
-
const spanContext = {
|
|
1255
|
-
traceId,
|
|
1256
|
-
spanId,
|
|
1257
|
-
isRemote: true,
|
|
1258
|
-
traceFlags: api.TraceFlags.NONE,
|
|
1259
|
-
};
|
|
1260
|
-
|
|
1261
|
-
const ctxWithTrace = api.trace.setSpanContext(api.context.active(), spanContext);
|
|
1262
|
-
|
|
1263
|
-
return api.context.with(ctxWithTrace, () => {
|
|
1264
|
-
core.getCurrentScope().setPropagationContext({
|
|
1265
|
-
traceId,
|
|
1266
|
-
sampleRand: core._INTERNAL_safeMathRandom(),
|
|
1267
|
-
});
|
|
1268
|
-
return callback();
|
|
1269
|
-
});
|
|
1270
|
-
}
|
|
1271
|
-
|
|
1272
|
-
/**
|
|
1273
|
-
* Get the trace context for a given scope.
|
|
1274
|
-
* We have a custom implementation here because we need an OTEL-specific way to get the span from a scope.
|
|
1275
|
-
*/
|
|
1276
|
-
function getTraceContextForScope(
|
|
1277
|
-
client,
|
|
1278
|
-
scope,
|
|
1279
|
-
) {
|
|
1280
|
-
const ctx = getContextFromScope(scope);
|
|
1281
|
-
const span = ctx && api.trace.getSpan(ctx);
|
|
1282
|
-
|
|
1283
|
-
const traceContext = span ? core.spanToTraceContext(span) : core.getTraceContextFromScope(scope);
|
|
1284
|
-
|
|
1285
|
-
const dynamicSamplingContext = span
|
|
1286
|
-
? core.getDynamicSamplingContextFromSpan(span)
|
|
1287
|
-
: core.getDynamicSamplingContextFromScope(client, scope);
|
|
1288
|
-
return [dynamicSamplingContext, traceContext];
|
|
1289
|
-
}
|
|
1290
|
-
|
|
1291
|
-
function getActiveSpanWrapper(parentSpan) {
|
|
1292
|
-
return parentSpan !== undefined
|
|
1293
|
-
? (callback) => {
|
|
1294
|
-
return withActiveSpan(parentSpan, callback);
|
|
1295
|
-
}
|
|
1296
|
-
: (callback) => callback();
|
|
1297
|
-
}
|
|
1298
|
-
|
|
1299
|
-
/** Suppress tracing in the given callback, ensuring no spans are generated inside of it. */
|
|
1300
|
-
function suppressTracing(callback) {
|
|
1301
|
-
const ctx = core$1.suppressTracing(api.context.active());
|
|
1302
|
-
return api.context.with(ctx, callback);
|
|
1303
|
-
}
|
|
1304
|
-
|
|
1305
|
-
/** Ensure the `trace` context is set on all events. */
|
|
1306
|
-
function setupEventContextTrace(client) {
|
|
1307
|
-
client.on('preprocessEvent', event => {
|
|
1308
|
-
const span = getActiveSpan();
|
|
1309
|
-
// For transaction events, this is handled separately
|
|
1310
|
-
// Because the active span may not be the span that is actually the transaction event
|
|
1311
|
-
if (!span || event.type === 'transaction') {
|
|
1312
|
-
return;
|
|
1313
|
-
}
|
|
1314
|
-
|
|
1315
|
-
// If event has already set `trace` context, use that one.
|
|
1316
|
-
event.contexts = {
|
|
1317
|
-
trace: core.spanToTraceContext(span),
|
|
1318
|
-
...event.contexts,
|
|
1319
|
-
};
|
|
1320
|
-
|
|
1321
|
-
const rootSpan = core.getRootSpan(span);
|
|
1322
|
-
|
|
1323
|
-
event.sdkProcessingMetadata = {
|
|
1324
|
-
dynamicSamplingContext: core.getDynamicSamplingContextFromSpan(rootSpan),
|
|
1325
|
-
...event.sdkProcessingMetadata,
|
|
1326
|
-
};
|
|
1327
|
-
|
|
1328
|
-
return event;
|
|
1329
|
-
});
|
|
1330
|
-
}
|
|
1331
|
-
|
|
1332
|
-
/**
|
|
1333
|
-
* Otel-specific implementation of `getTraceData`.
|
|
1334
|
-
* @see `@sentry/core` version of `getTraceData` for more information
|
|
1335
|
-
*/
|
|
1336
|
-
function getTraceData({
|
|
1337
|
-
span,
|
|
1338
|
-
scope,
|
|
1339
|
-
client,
|
|
1340
|
-
propagateTraceparent,
|
|
1341
|
-
} = {}) {
|
|
1342
|
-
let ctx = (scope && getContextFromScope(scope)) ?? api.context.active();
|
|
1343
|
-
|
|
1344
|
-
if (span) {
|
|
1345
|
-
const { scope } = core.getCapturedScopesOnSpan(span);
|
|
1346
|
-
// fall back to current context if for whatever reason we can't find the one of the span
|
|
1347
|
-
ctx = (scope && getContextFromScope(scope)) || api.trace.setSpan(api.context.active(), span);
|
|
1348
|
-
}
|
|
1349
|
-
|
|
1350
|
-
const { traceId, spanId, sampled, dynamicSamplingContext } = getInjectionData(ctx, { scope, client });
|
|
1351
|
-
|
|
1352
|
-
const traceData = {
|
|
1353
|
-
'sentry-trace': core.generateSentryTraceHeader(traceId, spanId, sampled),
|
|
1354
|
-
baggage: core.dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext),
|
|
1355
|
-
};
|
|
1356
|
-
|
|
1357
|
-
if (propagateTraceparent) {
|
|
1358
|
-
traceData.traceparent = core.generateTraceparentHeader(traceId, spanId, sampled);
|
|
1359
|
-
}
|
|
1360
|
-
|
|
1361
|
-
return traceData;
|
|
1362
|
-
}
|
|
1363
|
-
|
|
1364
|
-
/**
|
|
1365
|
-
* Sets the async context strategy to use follow the OTEL context under the hood.
|
|
1366
|
-
* We handle forking a hub inside of our custom OTEL Context Manager (./otelContextManager.ts)
|
|
1367
|
-
*/
|
|
1368
|
-
function setOpenTelemetryContextAsyncContextStrategy() {
|
|
1369
|
-
function getScopes() {
|
|
1370
|
-
const ctx = api.context.active();
|
|
1371
|
-
const scopes = getScopesFromContext(ctx);
|
|
1372
|
-
|
|
1373
|
-
if (scopes) {
|
|
1374
|
-
return scopes;
|
|
1375
|
-
}
|
|
1376
|
-
|
|
1377
|
-
// fallback behavior:
|
|
1378
|
-
// if, for whatever reason, we can't find scopes on the context here, we have to fix this somehow
|
|
1379
|
-
return {
|
|
1380
|
-
scope: core.getDefaultCurrentScope(),
|
|
1381
|
-
isolationScope: core.getDefaultIsolationScope(),
|
|
1382
|
-
};
|
|
1383
|
-
}
|
|
1384
|
-
|
|
1385
|
-
function withScope(callback) {
|
|
1386
|
-
const ctx = api.context.active();
|
|
1387
|
-
|
|
1388
|
-
// We depend on the otelContextManager to handle the context/hub
|
|
1389
|
-
// We set the `SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY` context value, which is picked up by
|
|
1390
|
-
// the OTEL context manager, which uses the presence of this key to determine if it should
|
|
1391
|
-
// fork the isolation scope, or not
|
|
1392
|
-
// as by default, we don't want to fork this, unless triggered explicitly by `withScope`
|
|
1393
|
-
return api.context.with(ctx, () => {
|
|
1394
|
-
return callback(getCurrentScope());
|
|
1395
|
-
});
|
|
1396
|
-
}
|
|
1397
|
-
|
|
1398
|
-
function withSetScope(scope, callback) {
|
|
1399
|
-
const ctx = getContextFromScope(scope) || api.context.active();
|
|
1400
|
-
|
|
1401
|
-
// We depend on the otelContextManager to handle the context/hub
|
|
1402
|
-
// We set the `SENTRY_FORK_SET_SCOPE_CONTEXT_KEY` context value, which is picked up by
|
|
1403
|
-
// the OTEL context manager, which picks up this scope as the current scope
|
|
1404
|
-
return api.context.with(ctx.setValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY, scope), () => {
|
|
1405
|
-
return callback(scope);
|
|
1406
|
-
});
|
|
1407
|
-
}
|
|
1408
|
-
|
|
1409
|
-
function withIsolationScope(callback) {
|
|
1410
|
-
const ctx = api.context.active();
|
|
1411
|
-
|
|
1412
|
-
// We depend on the otelContextManager to handle the context/hub
|
|
1413
|
-
// We set the `SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY` context value, which is picked up by
|
|
1414
|
-
// the OTEL context manager, which uses the presence of this key to determine if it should
|
|
1415
|
-
// fork the isolation scope, or not
|
|
1416
|
-
return api.context.with(ctx.setValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY, true), () => {
|
|
1417
|
-
return callback(getIsolationScope());
|
|
1418
|
-
});
|
|
1419
|
-
}
|
|
1420
|
-
|
|
1421
|
-
function withSetIsolationScope(isolationScope, callback) {
|
|
1422
|
-
const ctx = api.context.active();
|
|
1423
|
-
|
|
1424
|
-
// We depend on the otelContextManager to handle the context/hub
|
|
1425
|
-
// We set the `SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY` context value, which is picked up by
|
|
1426
|
-
// the OTEL context manager, which uses the presence of this key to determine if it should
|
|
1427
|
-
// fork the isolation scope, or not
|
|
1428
|
-
return api.context.with(ctx.setValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY, isolationScope), () => {
|
|
1429
|
-
return callback(getIsolationScope());
|
|
1430
|
-
});
|
|
1431
|
-
}
|
|
1432
|
-
|
|
1433
|
-
function getCurrentScope() {
|
|
1434
|
-
return getScopes().scope;
|
|
1435
|
-
}
|
|
1436
|
-
|
|
1437
|
-
function getIsolationScope() {
|
|
1438
|
-
return getScopes().isolationScope;
|
|
1439
|
-
}
|
|
1440
|
-
|
|
1441
|
-
core.setAsyncContextStrategy({
|
|
1442
|
-
withScope,
|
|
1443
|
-
withSetScope,
|
|
1444
|
-
withSetIsolationScope,
|
|
1445
|
-
withIsolationScope,
|
|
1446
|
-
getCurrentScope,
|
|
1447
|
-
getIsolationScope,
|
|
1448
|
-
startSpan,
|
|
1449
|
-
startSpanManual,
|
|
1450
|
-
startInactiveSpan,
|
|
1451
|
-
getActiveSpan,
|
|
1452
|
-
suppressTracing,
|
|
1453
|
-
getTraceData,
|
|
1454
|
-
continueTrace,
|
|
1455
|
-
startNewTrace,
|
|
1456
|
-
// The types here don't fully align, because our own `Span` type is narrower
|
|
1457
|
-
// than the OTEL one - but this is OK for here, as we now we'll only have OTEL spans passed around
|
|
1458
|
-
withActiveSpan: withActiveSpan ,
|
|
1459
|
-
});
|
|
1460
|
-
}
|
|
1461
|
-
|
|
1462
|
-
/**
|
|
1463
|
-
* Merge Sentry scopes into an OpenTelemetry {@link Context} and apply trace-context adjustments
|
|
1464
|
-
* used by Sentry OpenTelemetry context manager(s).
|
|
1465
|
-
*
|
|
1466
|
-
* @param context - Context passed into `ContextManager.with`.
|
|
1467
|
-
* @param activeContext - Context that was active before entering `with` (e.g. `this.active()`), used
|
|
1468
|
-
* to restore the parent span when the incoming span is marked ignored for children.
|
|
1469
|
-
* @returns A new context ready for `super.with` / `AsyncLocalStorage.run`.
|
|
1470
|
-
*/
|
|
1471
|
-
function buildContextWithSentryScopes(context, activeContext) {
|
|
1472
|
-
const span = api.trace.getSpan(context);
|
|
1473
|
-
let effectiveContext;
|
|
1474
|
-
if (span?.spanContext().traceState?.get(SENTRY_TRACE_STATE_CHILD_IGNORED) === '1') {
|
|
1475
|
-
const contextWithoutSpan = api.trace.deleteSpan(context);
|
|
1476
|
-
const parentSpan = api.trace.getSpan(activeContext);
|
|
1477
|
-
effectiveContext = parentSpan ? api.trace.setSpan(contextWithoutSpan, parentSpan) : contextWithoutSpan;
|
|
1478
|
-
} else {
|
|
1479
|
-
effectiveContext = context;
|
|
1480
|
-
}
|
|
1481
|
-
|
|
1482
|
-
const currentScopes = getScopesFromContext(effectiveContext);
|
|
1483
|
-
const currentScope = currentScopes?.scope || core.getCurrentScope();
|
|
1484
|
-
const currentIsolationScope = currentScopes?.isolationScope || core.getIsolationScope();
|
|
1485
|
-
|
|
1486
|
-
const shouldForkIsolationScope = effectiveContext.getValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY) === true;
|
|
1487
|
-
const scope = effectiveContext.getValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY) ;
|
|
1488
|
-
const isolationScope = effectiveContext.getValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY) ;
|
|
1489
|
-
|
|
1490
|
-
const newCurrentScope = scope || currentScope.clone();
|
|
1491
|
-
const newIsolationScope =
|
|
1492
|
-
isolationScope || (shouldForkIsolationScope ? currentIsolationScope.clone() : currentIsolationScope);
|
|
1493
|
-
const scopes = { scope: newCurrentScope, isolationScope: newIsolationScope };
|
|
1494
|
-
|
|
1495
|
-
const ctx1 = setScopesOnContext(effectiveContext, scopes);
|
|
1496
|
-
|
|
1497
|
-
const ctx2 = ctx1
|
|
1498
|
-
.deleteValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY)
|
|
1499
|
-
.deleteValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY)
|
|
1500
|
-
.deleteValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY);
|
|
1501
|
-
|
|
1502
|
-
setContextOnScope(newCurrentScope, ctx2);
|
|
1503
|
-
|
|
1504
|
-
return ctx2;
|
|
1505
|
-
}
|
|
1506
|
-
|
|
1507
|
-
/**
|
|
1508
|
-
* Wrap an OpenTelemetry ContextManager in a way that ensures the context is kept in sync with the Sentry Scope.
|
|
1509
|
-
*
|
|
1510
|
-
* Usage:
|
|
1511
|
-
* import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';
|
|
1512
|
-
* const SentryContextManager = wrapContextManagerClass(AsyncLocalStorageContextManager);
|
|
1513
|
-
* const contextManager = new SentryContextManager();
|
|
1514
|
-
*
|
|
1515
|
-
* @deprecated Use {@link SentryAsyncLocalStorageContextManager} instead.
|
|
1516
|
-
*/
|
|
1517
|
-
function wrapContextManagerClass(
|
|
1518
|
-
ContextManagerClass,
|
|
1519
|
-
) {
|
|
1520
|
-
/**
|
|
1521
|
-
* This is a custom ContextManager for OpenTelemetry, which extends the default AsyncLocalStorageContextManager.
|
|
1522
|
-
* It ensures that we create new scopes per context, so that the OTEL Context & the Sentry Scope are always in sync.
|
|
1523
|
-
*
|
|
1524
|
-
* Note that we currently only support AsyncHooks with this,
|
|
1525
|
-
* but since this should work for Node 14+ anyhow that should be good enough.
|
|
1526
|
-
*/
|
|
1527
|
-
|
|
1528
|
-
// @ts-expect-error TS does not like this, but we know this is fine
|
|
1529
|
-
class SentryContextManager extends ContextManagerClass {
|
|
1530
|
-
constructor(...args) {
|
|
1531
|
-
super(...args);
|
|
1532
|
-
setIsSetup('SentryContextManager');
|
|
1533
|
-
}
|
|
1534
|
-
/**
|
|
1535
|
-
* Overwrite with() of the original AsyncLocalStorageContextManager
|
|
1536
|
-
* to ensure we also create new scopes per context.
|
|
1537
|
-
*/
|
|
1538
|
-
with(
|
|
1539
|
-
context,
|
|
1540
|
-
fn,
|
|
1541
|
-
thisArg,
|
|
1542
|
-
...args
|
|
1543
|
-
) {
|
|
1544
|
-
const ctx2 = buildContextWithSentryScopes(context, this.active());
|
|
1545
|
-
return super.with(ctx2, fn, thisArg, ...args);
|
|
1546
|
-
}
|
|
1547
|
-
|
|
1548
|
-
/**
|
|
1549
|
-
* Gets underlying AsyncLocalStorage and symbol to allow lookup of scope.
|
|
1550
|
-
*/
|
|
1551
|
-
getAsyncLocalStorageLookup() {
|
|
1552
|
-
return {
|
|
1553
|
-
// @ts-expect-error This is on the base class, but not part of the interface
|
|
1554
|
-
asyncLocalStorage: this._asyncLocalStorage,
|
|
1555
|
-
contextSymbol: SENTRY_SCOPES_CONTEXT_KEY,
|
|
1556
|
-
};
|
|
1557
|
-
}
|
|
1558
|
-
}
|
|
1559
|
-
|
|
1560
|
-
return SentryContextManager ;
|
|
1561
|
-
}
|
|
1562
|
-
|
|
1563
|
-
const ADD_LISTENER_METHODS = ['addListener', 'on', 'once', 'prependListener', 'prependOnceListener'] ;
|
|
1564
|
-
|
|
1565
|
-
/**
|
|
1566
|
-
* OpenTelemetry-compatible context manager using Node.js `AsyncLocalStorage`.
|
|
1567
|
-
* Semantics match `@opentelemetry/context-async-hooks` (function `bind` + `EventEmitter` patching).
|
|
1568
|
-
*/
|
|
1569
|
-
class SentryAsyncLocalStorageContextManager {
|
|
1570
|
-
__init() {this._asyncLocalStorage = new node_async_hooks.AsyncLocalStorage();}
|
|
1571
|
-
|
|
1572
|
-
__init2() {this._kOtListeners = Symbol('OtListeners');}
|
|
1573
|
-
__init3() {this._wrapped = false;}
|
|
1574
|
-
|
|
1575
|
-
constructor() {SentryAsyncLocalStorageContextManager.prototype.__init.call(this);SentryAsyncLocalStorageContextManager.prototype.__init2.call(this);SentryAsyncLocalStorageContextManager.prototype.__init3.call(this);
|
|
1576
|
-
setIsSetup('SentryContextManager');
|
|
1577
|
-
}
|
|
1578
|
-
|
|
1579
|
-
active() {
|
|
1580
|
-
return this._asyncLocalStorage.getStore() ?? api.ROOT_CONTEXT;
|
|
1581
|
-
}
|
|
1582
|
-
|
|
1583
|
-
with(
|
|
1584
|
-
context,
|
|
1585
|
-
fn,
|
|
1586
|
-
thisArg,
|
|
1587
|
-
...args
|
|
1588
|
-
) {
|
|
1589
|
-
const ctx2 = buildContextWithSentryScopes(context, this.active());
|
|
1590
|
-
const cb = thisArg == null ? fn : fn.bind(thisArg);
|
|
1591
|
-
return this._asyncLocalStorage.run(ctx2, cb , ...args);
|
|
1592
|
-
}
|
|
1593
|
-
|
|
1594
|
-
enable() {
|
|
1595
|
-
return this;
|
|
1596
|
-
}
|
|
1597
|
-
|
|
1598
|
-
disable() {
|
|
1599
|
-
this._asyncLocalStorage.disable();
|
|
1600
|
-
return this;
|
|
1601
|
-
}
|
|
1602
|
-
|
|
1603
|
-
bind(context, target) {
|
|
1604
|
-
if (target instanceof node_events.EventEmitter) {
|
|
1605
|
-
return this._bindEventEmitter(context, target);
|
|
1606
|
-
}
|
|
1607
|
-
if (typeof target === 'function') {
|
|
1608
|
-
return this._bindFunction(context, target ) ;
|
|
1609
|
-
}
|
|
1610
|
-
return target;
|
|
1611
|
-
}
|
|
1612
|
-
|
|
1613
|
-
/**
|
|
1614
|
-
* Gets underlying AsyncLocalStorage and symbol to allow lookup of scope.
|
|
1615
|
-
* This is Sentry-specific.
|
|
1616
|
-
*/
|
|
1617
|
-
getAsyncLocalStorageLookup() {
|
|
1618
|
-
return {
|
|
1619
|
-
asyncLocalStorage: this._asyncLocalStorage,
|
|
1620
|
-
contextSymbol: SENTRY_SCOPES_CONTEXT_KEY,
|
|
1621
|
-
};
|
|
1622
|
-
}
|
|
1623
|
-
|
|
1624
|
-
_bindFunction(context, target) {
|
|
1625
|
-
const managerWith = this.with.bind(this);
|
|
1626
|
-
const contextWrapper = function ( ...args) {
|
|
1627
|
-
return managerWith(context, () => target.apply(this, args));
|
|
1628
|
-
};
|
|
1629
|
-
Object.defineProperty(contextWrapper, 'length', {
|
|
1630
|
-
enumerable: false,
|
|
1631
|
-
configurable: true,
|
|
1632
|
-
writable: false,
|
|
1633
|
-
value: target.length,
|
|
1634
|
-
});
|
|
1635
|
-
return contextWrapper;
|
|
1636
|
-
}
|
|
1637
|
-
|
|
1638
|
-
_bindEventEmitter(context, ee) {
|
|
1639
|
-
if (this._getPatchMap(ee) !== undefined) {
|
|
1640
|
-
return ee;
|
|
1641
|
-
}
|
|
1642
|
-
this._createPatchMap(ee);
|
|
1643
|
-
|
|
1644
|
-
for (const methodName of ADD_LISTENER_METHODS) {
|
|
1645
|
-
if (ee[methodName] === undefined) continue;
|
|
1646
|
-
ee[methodName] = this._patchAddListener(
|
|
1647
|
-
ee,
|
|
1648
|
-
ee[methodName] ,
|
|
1649
|
-
context,
|
|
1650
|
-
);
|
|
1651
|
-
}
|
|
1652
|
-
if (typeof ee.removeListener === 'function') {
|
|
1653
|
-
// oxlint-disable-next-line @typescript-eslint/unbound-method -- patched like upstream OTel context manager
|
|
1654
|
-
ee.removeListener = this._patchRemoveListener(ee, ee.removeListener );
|
|
1655
|
-
}
|
|
1656
|
-
if (typeof ee.off === 'function') {
|
|
1657
|
-
// oxlint-disable-next-line @typescript-eslint/unbound-method
|
|
1658
|
-
ee.off = this._patchRemoveListener(ee, ee.off );
|
|
1659
|
-
}
|
|
1660
|
-
if (typeof ee.removeAllListeners === 'function') {
|
|
1661
|
-
ee.removeAllListeners = this._patchRemoveAllListeners(
|
|
1662
|
-
ee,
|
|
1663
|
-
// oxlint-disable-next-line @typescript-eslint/unbound-method
|
|
1664
|
-
ee.removeAllListeners ,
|
|
1665
|
-
);
|
|
1666
|
-
}
|
|
1667
|
-
return ee;
|
|
1668
|
-
}
|
|
1669
|
-
|
|
1670
|
-
_patchRemoveListener(ee, original) {
|
|
1671
|
-
// oxlint-disable-next-line @typescript-eslint/no-this-alias
|
|
1672
|
-
const contextManager = this;
|
|
1673
|
-
return function ( event, listener) {
|
|
1674
|
-
const events = contextManager._getPatchMap(ee)?.[event];
|
|
1675
|
-
if (events === undefined) {
|
|
1676
|
-
return original.call(this, event, listener);
|
|
1677
|
-
}
|
|
1678
|
-
const patchedListener = events.get(listener);
|
|
1679
|
-
return original.call(this, event, patchedListener || listener);
|
|
1680
|
-
};
|
|
1681
|
-
}
|
|
1682
|
-
|
|
1683
|
-
_patchRemoveAllListeners(ee, original) {
|
|
1684
|
-
// oxlint-disable-next-line @typescript-eslint/no-this-alias
|
|
1685
|
-
const contextManager = this;
|
|
1686
|
-
return function ( event) {
|
|
1687
|
-
const map = contextManager._getPatchMap(ee);
|
|
1688
|
-
if (map !== undefined) {
|
|
1689
|
-
if (arguments.length === 0) {
|
|
1690
|
-
contextManager._createPatchMap(ee);
|
|
1691
|
-
} else if (event !== undefined && map[event] !== undefined) {
|
|
1692
|
-
// oxlint-disable-next-line @typescript-eslint/no-dynamic-delete -- event-keyed listener map
|
|
1693
|
-
delete map[event];
|
|
1694
|
-
}
|
|
1695
|
-
}
|
|
1696
|
-
return original.apply(this, arguments);
|
|
1697
|
-
};
|
|
1698
|
-
}
|
|
1699
|
-
|
|
1700
|
-
_patchAddListener(ee, original, context) {
|
|
1701
|
-
// oxlint-disable-next-line @typescript-eslint/no-this-alias
|
|
1702
|
-
const contextManager = this;
|
|
1703
|
-
return function ( event, listener) {
|
|
1704
|
-
if (contextManager._wrapped) {
|
|
1705
|
-
return original.call(this, event, listener);
|
|
1706
|
-
}
|
|
1707
|
-
let map = contextManager._getPatchMap(ee);
|
|
1708
|
-
if (map === undefined) {
|
|
1709
|
-
map = contextManager._createPatchMap(ee);
|
|
1710
|
-
}
|
|
1711
|
-
let listeners = map[event];
|
|
1712
|
-
if (listeners === undefined) {
|
|
1713
|
-
listeners = new WeakMap();
|
|
1714
|
-
map[event] = listeners;
|
|
1715
|
-
}
|
|
1716
|
-
const patchedListener = contextManager.bind(context, listener);
|
|
1717
|
-
listeners.set(listener, patchedListener);
|
|
1718
|
-
|
|
1719
|
-
contextManager._wrapped = true;
|
|
1720
|
-
try {
|
|
1721
|
-
return original.call(this, event, patchedListener);
|
|
1722
|
-
} finally {
|
|
1723
|
-
contextManager._wrapped = false;
|
|
1724
|
-
}
|
|
1725
|
-
};
|
|
1726
|
-
}
|
|
1727
|
-
|
|
1728
|
-
_createPatchMap(ee) {
|
|
1729
|
-
const map = Object.create(null) ;
|
|
1730
|
-
(ee )[this._kOtListeners] = map;
|
|
1731
|
-
return map;
|
|
1732
|
-
}
|
|
1733
|
-
|
|
1734
|
-
_getPatchMap(ee) {
|
|
1735
|
-
return (ee )[this._kOtListeners];
|
|
1736
|
-
}
|
|
1737
|
-
}
|
|
1738
|
-
|
|
1739
|
-
/**
|
|
1740
|
-
* This function runs through a list of OTEL Spans, and wraps them in an `SpanNode`
|
|
1741
|
-
* where each node holds a reference to their parent node.
|
|
1742
|
-
*/
|
|
1743
|
-
function groupSpansWithParents(spans) {
|
|
1744
|
-
const nodeMap = new Map();
|
|
1745
|
-
|
|
1746
|
-
for (const span of spans) {
|
|
1747
|
-
createOrUpdateSpanNodeAndRefs(nodeMap, span);
|
|
1748
|
-
}
|
|
1749
|
-
|
|
1750
|
-
return Array.from(nodeMap, function ([_id, spanNode]) {
|
|
1751
|
-
return spanNode;
|
|
1752
|
-
});
|
|
1753
|
-
}
|
|
1754
|
-
|
|
1755
|
-
/**
|
|
1756
|
-
* This returns the _local_ parent ID - `parentId` on the span may point to a remote span.
|
|
1757
|
-
*/
|
|
1758
|
-
function getLocalParentId(span) {
|
|
1759
|
-
const parentIsRemote = span.attributes[SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE] === true;
|
|
1760
|
-
// If the parentId is the trace parent ID, we pretend it's undefined
|
|
1761
|
-
// As this means the parent exists somewhere else
|
|
1762
|
-
return !parentIsRemote ? getParentSpanId(span) : undefined;
|
|
1763
|
-
}
|
|
1764
|
-
|
|
1765
|
-
function createOrUpdateSpanNodeAndRefs(nodeMap, span) {
|
|
1766
|
-
const id = span.spanContext().spanId;
|
|
1767
|
-
const parentId = getLocalParentId(span);
|
|
1768
|
-
|
|
1769
|
-
if (!parentId) {
|
|
1770
|
-
createOrUpdateNode(nodeMap, { id, span, children: [] });
|
|
1771
|
-
return;
|
|
1772
|
-
}
|
|
1773
|
-
|
|
1774
|
-
// Else make sure to create parent node as well
|
|
1775
|
-
// Note that the parent may not know it's parent _yet_, this may be updated in a later pass
|
|
1776
|
-
const parentNode = createOrGetParentNode(nodeMap, parentId);
|
|
1777
|
-
const node = createOrUpdateNode(nodeMap, { id, span, parentNode, children: [] });
|
|
1778
|
-
parentNode.children.push(node);
|
|
1779
|
-
}
|
|
1780
|
-
|
|
1781
|
-
function createOrGetParentNode(nodeMap, id) {
|
|
1782
|
-
const existing = nodeMap.get(id);
|
|
1783
|
-
|
|
1784
|
-
if (existing) {
|
|
1785
|
-
return existing;
|
|
1786
|
-
}
|
|
1787
|
-
|
|
1788
|
-
return createOrUpdateNode(nodeMap, { id, children: [] });
|
|
1789
|
-
}
|
|
1790
|
-
|
|
1791
|
-
function createOrUpdateNode(nodeMap, spanNode) {
|
|
1792
|
-
const existing = nodeMap.get(spanNode.id);
|
|
1793
|
-
|
|
1794
|
-
// If span is already set, nothing to do here
|
|
1795
|
-
if (existing?.span) {
|
|
1796
|
-
return existing;
|
|
1797
|
-
}
|
|
1798
|
-
|
|
1799
|
-
// If it exists but span is not set yet, we update it
|
|
1800
|
-
if (existing && !existing.span) {
|
|
1801
|
-
existing.span = spanNode.span;
|
|
1802
|
-
existing.parentNode = spanNode.parentNode;
|
|
1803
|
-
return existing;
|
|
1804
|
-
}
|
|
1805
|
-
|
|
1806
|
-
// Else, we create a new one...
|
|
1807
|
-
nodeMap.set(spanNode.id, spanNode);
|
|
1808
|
-
return spanNode;
|
|
1809
|
-
}
|
|
1810
|
-
|
|
1811
|
-
// canonicalCodesGrpcMap maps some GRPC codes to Sentry's span statuses. See description in grpc documentation.
|
|
1812
|
-
const canonicalGrpcErrorCodesMap = {
|
|
1813
|
-
'1': 'cancelled',
|
|
1814
|
-
'2': 'unknown_error',
|
|
1815
|
-
'3': 'invalid_argument',
|
|
1816
|
-
'4': 'deadline_exceeded',
|
|
1817
|
-
'5': 'not_found',
|
|
1818
|
-
'6': 'already_exists',
|
|
1819
|
-
'7': 'permission_denied',
|
|
1820
|
-
'8': 'resource_exhausted',
|
|
1821
|
-
'9': 'failed_precondition',
|
|
1822
|
-
'10': 'aborted',
|
|
1823
|
-
'11': 'out_of_range',
|
|
1824
|
-
'12': 'unimplemented',
|
|
1825
|
-
'13': 'internal_error',
|
|
1826
|
-
'14': 'unavailable',
|
|
1827
|
-
'15': 'data_loss',
|
|
1828
|
-
'16': 'unauthenticated',
|
|
1829
|
-
} ;
|
|
1830
|
-
|
|
1831
|
-
const isStatusErrorMessageValid = (message) => {
|
|
1832
|
-
return Object.values(canonicalGrpcErrorCodesMap).includes(message );
|
|
1833
|
-
};
|
|
1834
|
-
|
|
1835
|
-
/**
|
|
1836
|
-
* Get a Sentry span status from an otel span.
|
|
1837
|
-
*/
|
|
1838
|
-
function mapStatus(span) {
|
|
1839
|
-
const attributes = spanHasAttributes(span) ? span.attributes : {};
|
|
1840
|
-
const status = spanHasStatus(span) ? span.status : undefined;
|
|
1841
|
-
|
|
1842
|
-
if (status) {
|
|
1843
|
-
// Since span status OK is not set by default, we give it priority: https://opentelemetry.io/docs/concepts/signals/traces/#span-status
|
|
1844
|
-
if (status.code === api.SpanStatusCode.OK) {
|
|
1845
|
-
return { code: core.SPAN_STATUS_OK };
|
|
1846
|
-
// If the span is already marked as erroneous we return that exact status
|
|
1847
|
-
} else if (status.code === api.SpanStatusCode.ERROR) {
|
|
1848
|
-
if (typeof status.message === 'undefined') {
|
|
1849
|
-
const inferredStatus = inferStatusFromAttributes(attributes);
|
|
1850
|
-
if (inferredStatus) {
|
|
1851
|
-
return inferredStatus;
|
|
1852
|
-
}
|
|
1853
|
-
}
|
|
1854
|
-
|
|
1855
|
-
if (status.message && isStatusErrorMessageValid(status.message)) {
|
|
1856
|
-
return { code: core.SPAN_STATUS_ERROR, message: status.message };
|
|
1857
|
-
} else {
|
|
1858
|
-
return { code: core.SPAN_STATUS_ERROR, message: 'internal_error' };
|
|
1859
|
-
}
|
|
1860
|
-
}
|
|
1861
|
-
}
|
|
1862
|
-
|
|
1863
|
-
// If the span status is UNSET, we try to infer it from HTTP or GRPC status codes.
|
|
1864
|
-
const inferredStatus = inferStatusFromAttributes(attributes);
|
|
1865
|
-
|
|
1866
|
-
if (inferredStatus) {
|
|
1867
|
-
return inferredStatus;
|
|
1868
|
-
}
|
|
1869
|
-
|
|
1870
|
-
// We default to setting the spans status to ok.
|
|
1871
|
-
if (status?.code === api.SpanStatusCode.UNSET) {
|
|
1872
|
-
return { code: core.SPAN_STATUS_OK };
|
|
1873
|
-
} else {
|
|
1874
|
-
return { code: core.SPAN_STATUS_ERROR, message: 'unknown_error' };
|
|
1875
|
-
}
|
|
1876
|
-
}
|
|
1877
|
-
|
|
1878
|
-
function inferStatusFromAttributes(attributes) {
|
|
1879
|
-
// If the span status is UNSET, we try to infer it from HTTP or GRPC status codes.
|
|
1880
|
-
|
|
1881
|
-
// eslint-disable-next-line deprecation/deprecation
|
|
1882
|
-
const httpCodeAttribute = attributes[semanticConventions.ATTR_HTTP_RESPONSE_STATUS_CODE] || attributes[semanticConventions.SEMATTRS_HTTP_STATUS_CODE];
|
|
1883
|
-
// eslint-disable-next-line deprecation/deprecation
|
|
1884
|
-
const grpcCodeAttribute = attributes[semanticConventions.SEMATTRS_RPC_GRPC_STATUS_CODE];
|
|
1885
|
-
|
|
1886
|
-
const numberHttpCode =
|
|
1887
|
-
typeof httpCodeAttribute === 'number'
|
|
1888
|
-
? httpCodeAttribute
|
|
1889
|
-
: typeof httpCodeAttribute === 'string'
|
|
1890
|
-
? parseInt(httpCodeAttribute)
|
|
1891
|
-
: undefined;
|
|
1892
|
-
|
|
1893
|
-
if (typeof numberHttpCode === 'number') {
|
|
1894
|
-
return core.getSpanStatusFromHttpCode(numberHttpCode);
|
|
1895
|
-
}
|
|
1896
|
-
|
|
1897
|
-
if (typeof grpcCodeAttribute === 'string') {
|
|
1898
|
-
return { code: core.SPAN_STATUS_ERROR, message: canonicalGrpcErrorCodesMap[grpcCodeAttribute] || 'unknown_error' };
|
|
1899
|
-
}
|
|
1900
|
-
|
|
1901
|
-
return undefined;
|
|
1902
|
-
}
|
|
1903
|
-
|
|
1904
|
-
const MAX_SPAN_COUNT = 1000;
|
|
1905
|
-
const DEFAULT_TIMEOUT = 300; // 5 min
|
|
1906
|
-
|
|
1907
|
-
/**
|
|
1908
|
-
* A Sentry-specific exporter that converts OpenTelemetry Spans to Sentry Spans & Transactions.
|
|
1909
|
-
*/
|
|
1910
|
-
class SentrySpanExporter {
|
|
1911
|
-
/*
|
|
1912
|
-
* A quick explanation on the buckets: We do bucketing of finished spans for efficiency. This span exporter is
|
|
1913
|
-
* accumulating spans until a root span is encountered and then it flushes all the spans that are descendants of that
|
|
1914
|
-
* root span. Because it is totally in the realm of possibilities that root spans are never finished, and we don't
|
|
1915
|
-
* want to accumulate spans indefinitely in memory, we need to periodically evacuate spans. Naively we could simply
|
|
1916
|
-
* store the spans in an array and each time a new span comes in we could iterate through the entire array and
|
|
1917
|
-
* evacuate all spans that have an end-timestamp that is older than our limit. This could get quite expensive because
|
|
1918
|
-
* we would have to iterate a potentially large number of spans every time we evacuate. We want to avoid these large
|
|
1919
|
-
* bursts of computation.
|
|
1920
|
-
*
|
|
1921
|
-
* Instead we go for a bucketing approach and put spans into buckets, based on what second
|
|
1922
|
-
* (modulo the time limit) the span was put into the exporter. With buckets, when we decide to evacuate, we can
|
|
1923
|
-
* iterate through the bucket entries instead, which have an upper bound of items, making the evacuation much more
|
|
1924
|
-
* efficient. Cleaning up also becomes much more efficient since it simply involves de-referencing a bucket within the
|
|
1925
|
-
* bucket array, and letting garbage collection take care of the rest.
|
|
1926
|
-
*/
|
|
1927
|
-
|
|
1928
|
-
// Essentially a a set of span ids that are already sent. The values are expiration
|
|
1929
|
-
// times in this cache so we don't hold onto them indefinitely.
|
|
1930
|
-
|
|
1931
|
-
/* Internally, we use a debounced flush to give some wiggle room to the span processor to accumulate more spans. */
|
|
1932
|
-
|
|
1933
|
-
constructor(options
|
|
1934
|
-
|
|
1935
|
-
) {
|
|
1936
|
-
this._finishedSpanBucketSize = options?.timeout || DEFAULT_TIMEOUT;
|
|
1937
|
-
this._finishedSpanBuckets = new Array(this._finishedSpanBucketSize).fill(undefined);
|
|
1938
|
-
this._lastCleanupTimestampInS = Math.floor(core._INTERNAL_safeDateNow() / 1000);
|
|
1939
|
-
this._spansToBucketEntry = new WeakMap();
|
|
1940
|
-
this._sentSpans = new Map();
|
|
1941
|
-
this._debouncedFlush = core.debounce(this.flush.bind(this), 1, { maxWait: 100 });
|
|
1942
|
-
}
|
|
1943
|
-
|
|
1944
|
-
/**
|
|
1945
|
-
* Export a single span.
|
|
1946
|
-
* This is called by the span processor whenever a span is ended.
|
|
1947
|
-
*/
|
|
1948
|
-
export(span) {
|
|
1949
|
-
const currentTimestampInS = Math.floor(core._INTERNAL_safeDateNow() / 1000);
|
|
1950
|
-
|
|
1951
|
-
if (this._lastCleanupTimestampInS !== currentTimestampInS) {
|
|
1952
|
-
let droppedSpanCount = 0;
|
|
1953
|
-
this._finishedSpanBuckets.forEach((bucket, i) => {
|
|
1954
|
-
if (bucket && bucket.timestampInS <= currentTimestampInS - this._finishedSpanBucketSize) {
|
|
1955
|
-
droppedSpanCount += bucket.spans.size;
|
|
1956
|
-
this._finishedSpanBuckets[i] = undefined;
|
|
1957
|
-
}
|
|
1958
|
-
});
|
|
1959
|
-
if (droppedSpanCount > 0) {
|
|
1960
|
-
debugBuild.DEBUG_BUILD &&
|
|
1961
|
-
core.debug.log(
|
|
1962
|
-
`SpanExporter dropped ${droppedSpanCount} spans because they were pending for more than ${this._finishedSpanBucketSize} seconds.`,
|
|
1963
|
-
);
|
|
1964
|
-
}
|
|
1965
|
-
this._lastCleanupTimestampInS = currentTimestampInS;
|
|
1966
|
-
}
|
|
1967
|
-
|
|
1968
|
-
const currentBucketIndex = currentTimestampInS % this._finishedSpanBucketSize;
|
|
1969
|
-
const currentBucket = this._finishedSpanBuckets[currentBucketIndex] || {
|
|
1970
|
-
timestampInS: currentTimestampInS,
|
|
1971
|
-
spans: new Set(),
|
|
1972
|
-
};
|
|
1973
|
-
this._finishedSpanBuckets[currentBucketIndex] = currentBucket;
|
|
1974
|
-
currentBucket.spans.add(span);
|
|
1975
|
-
this._spansToBucketEntry.set(span, currentBucket);
|
|
1976
|
-
|
|
1977
|
-
// If the span doesn't have a local parent ID (it's a root span), we're gonna flush all the ended spans
|
|
1978
|
-
const localParentId = getLocalParentId(span);
|
|
1979
|
-
if (!localParentId || this._sentSpans.has(localParentId)) {
|
|
1980
|
-
this._debouncedFlush();
|
|
1981
|
-
}
|
|
1982
|
-
}
|
|
1983
|
-
|
|
1984
|
-
/**
|
|
1985
|
-
* Try to flush any pending spans immediately.
|
|
1986
|
-
* This is called internally by the exporter (via _debouncedFlush),
|
|
1987
|
-
* but can also be triggered externally if we force-flush.
|
|
1988
|
-
*/
|
|
1989
|
-
flush() {
|
|
1990
|
-
const finishedSpans = this._finishedSpanBuckets.flatMap(bucket => (bucket ? Array.from(bucket.spans) : []));
|
|
1991
|
-
|
|
1992
|
-
this._flushSentSpanCache();
|
|
1993
|
-
const sentSpans = this._maybeSend(finishedSpans);
|
|
1994
|
-
|
|
1995
|
-
const sentSpanCount = sentSpans.size;
|
|
1996
|
-
const remainingOpenSpanCount = finishedSpans.length - sentSpanCount;
|
|
1997
|
-
debugBuild.DEBUG_BUILD &&
|
|
1998
|
-
core.debug.log(
|
|
1999
|
-
`SpanExporter exported ${sentSpanCount} spans, ${remainingOpenSpanCount} spans are waiting for their parent spans to finish`,
|
|
2000
|
-
);
|
|
2001
|
-
|
|
2002
|
-
const expirationDate = core._INTERNAL_safeDateNow() + DEFAULT_TIMEOUT * 1000;
|
|
2003
|
-
|
|
2004
|
-
for (const span of sentSpans) {
|
|
2005
|
-
this._sentSpans.set(span.spanContext().spanId, expirationDate);
|
|
2006
|
-
const bucketEntry = this._spansToBucketEntry.get(span);
|
|
2007
|
-
if (bucketEntry) {
|
|
2008
|
-
bucketEntry.spans.delete(span);
|
|
2009
|
-
}
|
|
2010
|
-
}
|
|
2011
|
-
// Cancel a pending debounced flush, if there is one
|
|
2012
|
-
// This can be relevant if we directly flush, circumventing the debounce
|
|
2013
|
-
// in that case, we want to cancel any pending debounced flush
|
|
2014
|
-
this._debouncedFlush.cancel();
|
|
2015
|
-
}
|
|
2016
|
-
|
|
2017
|
-
/**
|
|
2018
|
-
* Clear the exporter.
|
|
2019
|
-
* This is called when the span processor is shut down.
|
|
2020
|
-
*/
|
|
2021
|
-
clear() {
|
|
2022
|
-
this._finishedSpanBuckets = this._finishedSpanBuckets.fill(undefined);
|
|
2023
|
-
this._sentSpans.clear();
|
|
2024
|
-
this._debouncedFlush.cancel();
|
|
2025
|
-
}
|
|
2026
|
-
|
|
2027
|
-
/**
|
|
2028
|
-
* Send the given spans, but only if they are part of a finished transaction.
|
|
2029
|
-
*
|
|
2030
|
-
* Returns the sent spans.
|
|
2031
|
-
* Spans remain unsent when their parent span is not yet finished.
|
|
2032
|
-
* This will happen regularly, as child spans are generally finished before their parents.
|
|
2033
|
-
* But it _could_ also happen because, for whatever reason, a parent span was lost.
|
|
2034
|
-
* In this case, we'll eventually need to clean this up.
|
|
2035
|
-
*/
|
|
2036
|
-
_maybeSend(spans) {
|
|
2037
|
-
const grouped = groupSpansWithParents(spans);
|
|
2038
|
-
const sentSpans = new Set();
|
|
2039
|
-
|
|
2040
|
-
const rootNodes = this._getCompletedRootNodes(grouped);
|
|
2041
|
-
|
|
2042
|
-
for (const root of rootNodes) {
|
|
2043
|
-
const span = root.span;
|
|
2044
|
-
sentSpans.add(span);
|
|
2045
|
-
const transactionEvent = createTransactionForOtelSpan(span);
|
|
2046
|
-
|
|
2047
|
-
// Add an attribute to the transaction event to indicate that this transaction is an orphaned transaction
|
|
2048
|
-
if (root.parentNode && this._sentSpans.has(root.parentNode.id)) {
|
|
2049
|
-
const traceData = transactionEvent.contexts?.trace?.data;
|
|
2050
|
-
if (traceData) {
|
|
2051
|
-
traceData['sentry.parent_span_already_sent'] = true;
|
|
2052
|
-
}
|
|
2053
|
-
}
|
|
2054
|
-
|
|
2055
|
-
// We'll recursively add all the child spans to this array
|
|
2056
|
-
const spans = transactionEvent.spans || [];
|
|
2057
|
-
|
|
2058
|
-
let hasGenAiSpans = false;
|
|
2059
|
-
for (const child of root.children) {
|
|
2060
|
-
if (createAndFinishSpanForOtelSpan(child, spans, sentSpans)) {
|
|
2061
|
-
hasGenAiSpans = true;
|
|
2062
|
-
}
|
|
2063
|
-
}
|
|
2064
|
-
|
|
2065
|
-
// spans.sort() mutates the array, but we do not use this anymore after this point
|
|
2066
|
-
// so we can safely mutate it here
|
|
2067
|
-
transactionEvent.spans =
|
|
2068
|
-
spans.length > MAX_SPAN_COUNT
|
|
2069
|
-
? spans.sort((a, b) => a.start_timestamp - b.start_timestamp).slice(0, MAX_SPAN_COUNT)
|
|
2070
|
-
: spans;
|
|
2071
|
-
|
|
2072
|
-
if (hasGenAiSpans) {
|
|
2073
|
-
transactionEvent.sdkProcessingMetadata = {
|
|
2074
|
-
...transactionEvent.sdkProcessingMetadata,
|
|
2075
|
-
hasGenAiSpans: true,
|
|
2076
|
-
};
|
|
2077
|
-
}
|
|
2078
|
-
|
|
2079
|
-
const measurements = core.timedEventsToMeasurements(span.events);
|
|
2080
|
-
if (measurements) {
|
|
2081
|
-
transactionEvent.measurements = measurements;
|
|
2082
|
-
}
|
|
2083
|
-
|
|
2084
|
-
core.captureEvent(transactionEvent);
|
|
2085
|
-
}
|
|
2086
|
-
|
|
2087
|
-
return sentSpans;
|
|
2088
|
-
}
|
|
2089
|
-
|
|
2090
|
-
/** Remove "expired" span id entries from the _sentSpans cache. */
|
|
2091
|
-
_flushSentSpanCache() {
|
|
2092
|
-
const currentTimestamp = core._INTERNAL_safeDateNow();
|
|
2093
|
-
// Note, it is safe to delete items from the map as we go: https://stackoverflow.com/a/35943995/90297
|
|
2094
|
-
for (const [spanId, expirationTime] of this._sentSpans.entries()) {
|
|
2095
|
-
if (expirationTime <= currentTimestamp) {
|
|
2096
|
-
this._sentSpans.delete(spanId);
|
|
2097
|
-
}
|
|
2098
|
-
}
|
|
2099
|
-
}
|
|
2100
|
-
|
|
2101
|
-
/** Check if a node is a completed root node or a node whose parent has already been sent */
|
|
2102
|
-
_nodeIsCompletedRootNodeOrHasSentParent(node) {
|
|
2103
|
-
return !!node.span && (!node.parentNode || this._sentSpans.has(node.parentNode.id));
|
|
2104
|
-
}
|
|
2105
|
-
|
|
2106
|
-
/** Get all completed root nodes from a list of nodes */
|
|
2107
|
-
_getCompletedRootNodes(nodes) {
|
|
2108
|
-
// TODO: We should be able to remove the explicit `node is SpanNodeCompleted` type guard
|
|
2109
|
-
// once we stop supporting TS < 5.5
|
|
2110
|
-
return nodes.filter((node) => this._nodeIsCompletedRootNodeOrHasSentParent(node));
|
|
2111
|
-
}
|
|
2112
|
-
}
|
|
2113
|
-
|
|
2114
|
-
function parseSpan(span) {
|
|
2115
|
-
const attributes = span.attributes;
|
|
2116
|
-
|
|
2117
|
-
const origin = attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] ;
|
|
2118
|
-
const op = attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_OP] ;
|
|
2119
|
-
const source = attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] ;
|
|
2120
|
-
|
|
2121
|
-
return { origin, op, source };
|
|
2122
|
-
}
|
|
2123
|
-
|
|
2124
|
-
/** Exported only for tests. */
|
|
2125
|
-
function createTransactionForOtelSpan(span) {
|
|
2126
|
-
const { op, description, data, origin = 'manual', source } = getSpanData(span);
|
|
2127
|
-
const capturedSpanScopes = core.getCapturedScopesOnSpan(span );
|
|
2128
|
-
|
|
2129
|
-
const sampleRate = span.attributes[core.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] ;
|
|
2130
|
-
|
|
2131
|
-
const attributes = {
|
|
2132
|
-
[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: source,
|
|
2133
|
-
[core.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: sampleRate,
|
|
2134
|
-
[core.SEMANTIC_ATTRIBUTE_SENTRY_OP]: op,
|
|
2135
|
-
[core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: origin,
|
|
2136
|
-
...data,
|
|
2137
|
-
...removeSentryAttributes(span.attributes),
|
|
2138
|
-
};
|
|
2139
|
-
|
|
2140
|
-
const { links } = span;
|
|
2141
|
-
const { traceId: trace_id, spanId: span_id } = span.spanContext();
|
|
2142
|
-
|
|
2143
|
-
// If parentSpanIdFromTraceState is defined at all, we want it to take precedence
|
|
2144
|
-
// In that case, an empty string should be interpreted as "no parent span id",
|
|
2145
|
-
// even if `span.parentSpanId` is set
|
|
2146
|
-
// this is the case when we are starting a new trace, where we have a virtual span based on the propagationContext
|
|
2147
|
-
// We only want to continue the traceId in this case, but ignore the parent span
|
|
2148
|
-
const parent_span_id = getParentSpanId(span);
|
|
2149
|
-
|
|
2150
|
-
const status = mapStatus(span);
|
|
2151
|
-
|
|
2152
|
-
const traceContext = {
|
|
2153
|
-
parent_span_id,
|
|
2154
|
-
span_id,
|
|
2155
|
-
trace_id,
|
|
2156
|
-
data: attributes,
|
|
2157
|
-
origin,
|
|
2158
|
-
op,
|
|
2159
|
-
status: core.getStatusMessage(status), // As per protocol, span status is allowed to be undefined
|
|
2160
|
-
links: core.convertSpanLinksForEnvelope(links),
|
|
2161
|
-
};
|
|
2162
|
-
|
|
2163
|
-
const statusCode = attributes[semanticConventions.ATTR_HTTP_RESPONSE_STATUS_CODE];
|
|
2164
|
-
const responseContext = typeof statusCode === 'number' ? { response: { status_code: statusCode } } : undefined;
|
|
2165
|
-
|
|
2166
|
-
const transactionEvent = {
|
|
2167
|
-
contexts: {
|
|
2168
|
-
trace: traceContext,
|
|
2169
|
-
otel: {
|
|
2170
|
-
resource: span.resource.attributes,
|
|
2171
|
-
},
|
|
2172
|
-
...responseContext,
|
|
2173
|
-
},
|
|
2174
|
-
spans: [],
|
|
2175
|
-
start_timestamp: core.spanTimeInputToSeconds(span.startTime),
|
|
2176
|
-
timestamp: core.spanTimeInputToSeconds(span.endTime),
|
|
2177
|
-
transaction: description,
|
|
2178
|
-
type: 'transaction',
|
|
2179
|
-
sdkProcessingMetadata: {
|
|
2180
|
-
capturedSpanScope: capturedSpanScopes.scope,
|
|
2181
|
-
capturedSpanIsolationScope: capturedSpanScopes.isolationScope,
|
|
2182
|
-
sampleRate,
|
|
2183
|
-
dynamicSamplingContext: core.getDynamicSamplingContextFromSpan(span ),
|
|
2184
|
-
},
|
|
2185
|
-
...(source && {
|
|
2186
|
-
transaction_info: {
|
|
2187
|
-
source,
|
|
2188
|
-
},
|
|
2189
|
-
}),
|
|
2190
|
-
};
|
|
2191
|
-
|
|
2192
|
-
return transactionEvent;
|
|
2193
|
-
}
|
|
2194
|
-
|
|
2195
|
-
/**
|
|
2196
|
-
* Returns `true` if this span or any descendant is a gen_ai span.
|
|
2197
|
-
*/
|
|
2198
|
-
function createAndFinishSpanForOtelSpan(node, spans, sentSpans) {
|
|
2199
|
-
const span = node.span;
|
|
2200
|
-
|
|
2201
|
-
if (span) {
|
|
2202
|
-
sentSpans.add(span);
|
|
2203
|
-
}
|
|
2204
|
-
|
|
2205
|
-
const shouldDrop = !span;
|
|
2206
|
-
|
|
2207
|
-
// If this span should be dropped, we still want to create spans for the children of this
|
|
2208
|
-
if (shouldDrop) {
|
|
2209
|
-
let hasGenAiSpans = false;
|
|
2210
|
-
node.children.forEach(child => {
|
|
2211
|
-
if (createAndFinishSpanForOtelSpan(child, spans, sentSpans)) {
|
|
2212
|
-
hasGenAiSpans = true;
|
|
2213
|
-
}
|
|
2214
|
-
});
|
|
2215
|
-
return hasGenAiSpans;
|
|
2216
|
-
}
|
|
2217
|
-
|
|
2218
|
-
const span_id = span.spanContext().spanId;
|
|
2219
|
-
const trace_id = span.spanContext().traceId;
|
|
2220
|
-
const parentSpanId = getParentSpanId(span);
|
|
2221
|
-
|
|
2222
|
-
const { attributes, startTime, endTime, links } = span;
|
|
2223
|
-
|
|
2224
|
-
const { op, description, data, origin = 'manual' } = getSpanData(span);
|
|
2225
|
-
const allData = {
|
|
2226
|
-
[core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: origin,
|
|
2227
|
-
[core.SEMANTIC_ATTRIBUTE_SENTRY_OP]: op,
|
|
2228
|
-
...removeSentryAttributes(attributes),
|
|
2229
|
-
...data,
|
|
2230
|
-
};
|
|
2231
|
-
|
|
2232
|
-
const status = mapStatus(span);
|
|
2233
|
-
|
|
2234
|
-
const spanJSON = {
|
|
2235
|
-
span_id,
|
|
2236
|
-
trace_id,
|
|
2237
|
-
data: allData,
|
|
2238
|
-
description,
|
|
2239
|
-
parent_span_id: parentSpanId,
|
|
2240
|
-
start_timestamp: core.spanTimeInputToSeconds(startTime),
|
|
2241
|
-
// This is [0,0] by default in OTEL, in which case we want to interpret this as no end time
|
|
2242
|
-
timestamp: core.spanTimeInputToSeconds(endTime) || undefined,
|
|
2243
|
-
status: core.getStatusMessage(status), // As per protocol, span status is allowed to be undefined
|
|
2244
|
-
op,
|
|
2245
|
-
origin,
|
|
2246
|
-
measurements: core.timedEventsToMeasurements(span.events),
|
|
2247
|
-
links: core.convertSpanLinksForEnvelope(links),
|
|
2248
|
-
};
|
|
2249
|
-
|
|
2250
|
-
spans.push(spanJSON);
|
|
2251
|
-
|
|
2252
|
-
let hasGenAiSpans = !!op?.startsWith('gen_ai.');
|
|
2253
|
-
node.children.forEach(child => {
|
|
2254
|
-
if (createAndFinishSpanForOtelSpan(child, spans, sentSpans)) {
|
|
2255
|
-
hasGenAiSpans = true;
|
|
2256
|
-
}
|
|
2257
|
-
});
|
|
2258
|
-
return hasGenAiSpans;
|
|
2259
|
-
}
|
|
2260
|
-
|
|
2261
|
-
function getSpanData(span)
|
|
2262
|
-
|
|
2263
|
-
{
|
|
2264
|
-
const { op: definedOp, source: definedSource, origin } = parseSpan(span);
|
|
2265
|
-
const { op: inferredOp, description, source: inferredSource, data: inferredData } = parseSpanDescription(span);
|
|
2266
|
-
|
|
2267
|
-
const op = definedOp || inferredOp;
|
|
2268
|
-
const source = definedSource || inferredSource;
|
|
2269
|
-
|
|
2270
|
-
const data = { ...inferredData, ...getData(span) };
|
|
2271
|
-
|
|
2272
|
-
return {
|
|
2273
|
-
op,
|
|
2274
|
-
description,
|
|
2275
|
-
source,
|
|
2276
|
-
origin,
|
|
2277
|
-
data,
|
|
2278
|
-
};
|
|
2279
|
-
}
|
|
13
|
+
const ADD_LISTENER_METHODS = ['addListener', 'on', 'once', 'prependListener', 'prependOnceListener'] ;
|
|
2280
14
|
|
|
2281
15
|
/**
|
|
2282
|
-
*
|
|
2283
|
-
*
|
|
16
|
+
* OpenTelemetry-compatible context manager using Node.js `AsyncLocalStorage`.
|
|
17
|
+
* Semantics match `@opentelemetry/context-async-hooks` (function `bind` + `EventEmitter` patching).
|
|
2284
18
|
*/
|
|
2285
|
-
|
|
2286
|
-
|
|
2287
|
-
|
|
2288
|
-
/* eslint-disable @typescript-eslint/no-dynamic-delete */
|
|
2289
|
-
delete cleanedData[core.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE];
|
|
2290
|
-
delete cleanedData[SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE];
|
|
2291
|
-
delete cleanedData[core.SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];
|
|
2292
|
-
/* eslint-enable @typescript-eslint/no-dynamic-delete */
|
|
2293
|
-
|
|
2294
|
-
return cleanedData;
|
|
2295
|
-
}
|
|
19
|
+
class SentryAsyncLocalStorageContextManager {
|
|
20
|
+
__init() {this._asyncLocalStorage = new node_async_hooks.AsyncLocalStorage();}
|
|
2296
21
|
|
|
2297
|
-
|
|
2298
|
-
|
|
2299
|
-
const data = {};
|
|
22
|
+
__init2() {this._kOtListeners = Symbol('OtListeners');}
|
|
23
|
+
__init3() {this._wrapped = false;}
|
|
2300
24
|
|
|
2301
|
-
|
|
2302
|
-
|
|
25
|
+
constructor() {SentryAsyncLocalStorageContextManager.prototype.__init.call(this);SentryAsyncLocalStorageContextManager.prototype.__init2.call(this);SentryAsyncLocalStorageContextManager.prototype.__init3.call(this);
|
|
26
|
+
resource.setIsSetup('SentryContextManager');
|
|
2303
27
|
}
|
|
2304
28
|
|
|
2305
|
-
|
|
2306
|
-
|
|
2307
|
-
if (maybeHttpStatusCodeAttribute) {
|
|
2308
|
-
data[semanticConventions.ATTR_HTTP_RESPONSE_STATUS_CODE] = maybeHttpStatusCodeAttribute ;
|
|
29
|
+
active() {
|
|
30
|
+
return this._asyncLocalStorage.getStore() ?? api.ROOT_CONTEXT;
|
|
2309
31
|
}
|
|
2310
32
|
|
|
2311
|
-
|
|
2312
|
-
|
|
2313
|
-
|
|
2314
|
-
|
|
33
|
+
with(
|
|
34
|
+
context,
|
|
35
|
+
fn,
|
|
36
|
+
thisArg,
|
|
37
|
+
...args
|
|
38
|
+
) {
|
|
39
|
+
const ctx2 = resource.buildContextWithSentryScopes(context, this.active());
|
|
40
|
+
const cb = thisArg == null ? fn : fn.bind(thisArg);
|
|
41
|
+
return this._asyncLocalStorage.run(ctx2, cb , ...args);
|
|
2315
42
|
}
|
|
2316
43
|
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
}
|
|
2320
|
-
if (requestData['http.fragment']) {
|
|
2321
|
-
data['http.fragment'] = requestData['http.fragment'].slice(1);
|
|
44
|
+
enable() {
|
|
45
|
+
return this;
|
|
2322
46
|
}
|
|
2323
47
|
|
|
2324
|
-
|
|
2325
|
-
|
|
2326
|
-
|
|
2327
|
-
/**
|
|
2328
|
-
* Converts OpenTelemetry Spans to Sentry Spans and sends them to Sentry via
|
|
2329
|
-
* the Sentry SDK.
|
|
2330
|
-
*/
|
|
2331
|
-
class SentrySpanProcessor {
|
|
2332
|
-
|
|
2333
|
-
constructor(options) {
|
|
2334
|
-
setIsSetup('SentrySpanProcessor');
|
|
2335
|
-
this._exporter = new SentrySpanExporter(options);
|
|
48
|
+
disable() {
|
|
49
|
+
this._asyncLocalStorage.disable();
|
|
50
|
+
return this;
|
|
2336
51
|
}
|
|
2337
52
|
|
|
2338
|
-
|
|
2339
|
-
|
|
2340
|
-
|
|
2341
|
-
|
|
2342
|
-
|
|
53
|
+
bind(context, target) {
|
|
54
|
+
if (target instanceof node_events.EventEmitter) {
|
|
55
|
+
return this._bindEventEmitter(context, target);
|
|
56
|
+
}
|
|
57
|
+
if (typeof target === 'function') {
|
|
58
|
+
return this._bindFunction(context, target ) ;
|
|
59
|
+
}
|
|
60
|
+
return target;
|
|
2343
61
|
}
|
|
2344
62
|
|
|
2345
63
|
/**
|
|
2346
|
-
*
|
|
64
|
+
* Gets underlying AsyncLocalStorage and symbol to allow lookup of scope.
|
|
65
|
+
* This is Sentry-specific.
|
|
2347
66
|
*/
|
|
2348
|
-
|
|
2349
|
-
|
|
67
|
+
getAsyncLocalStorageLookup() {
|
|
68
|
+
return {
|
|
69
|
+
asyncLocalStorage: this._asyncLocalStorage,
|
|
70
|
+
contextSymbol: resource.SENTRY_SCOPES_CONTEXT_KEY,
|
|
71
|
+
};
|
|
2350
72
|
}
|
|
2351
73
|
|
|
2352
|
-
|
|
2353
|
-
|
|
2354
|
-
|
|
2355
|
-
|
|
2356
|
-
|
|
2357
|
-
|
|
2358
|
-
|
|
2359
|
-
|
|
74
|
+
_bindFunction(context, target) {
|
|
75
|
+
const managerWith = this.with.bind(this);
|
|
76
|
+
const contextWrapper = function ( ...args) {
|
|
77
|
+
return managerWith(context, () => target.apply(this, args));
|
|
78
|
+
};
|
|
79
|
+
Object.defineProperty(contextWrapper, 'length', {
|
|
80
|
+
enumerable: false,
|
|
81
|
+
configurable: true,
|
|
82
|
+
writable: false,
|
|
83
|
+
value: target.length,
|
|
84
|
+
});
|
|
85
|
+
return contextWrapper;
|
|
86
|
+
}
|
|
2360
87
|
|
|
2361
|
-
|
|
2362
|
-
if (
|
|
2363
|
-
|
|
88
|
+
_bindEventEmitter(context, ee) {
|
|
89
|
+
if (this._getPatchMap(ee) !== undefined) {
|
|
90
|
+
return ee;
|
|
2364
91
|
}
|
|
92
|
+
this._createPatchMap(ee);
|
|
2365
93
|
|
|
2366
|
-
|
|
2367
|
-
|
|
2368
|
-
|
|
94
|
+
for (const methodName of ADD_LISTENER_METHODS) {
|
|
95
|
+
if (ee[methodName] === undefined) continue;
|
|
96
|
+
ee[methodName] = this._patchAddListener(
|
|
97
|
+
ee,
|
|
98
|
+
ee[methodName] ,
|
|
99
|
+
context,
|
|
100
|
+
);
|
|
2369
101
|
}
|
|
2370
|
-
|
|
2371
|
-
|
|
2372
|
-
|
|
2373
|
-
if (parentContext === api.ROOT_CONTEXT) {
|
|
2374
|
-
scopes = {
|
|
2375
|
-
scope: core.getDefaultCurrentScope(),
|
|
2376
|
-
isolationScope: core.getDefaultIsolationScope(),
|
|
2377
|
-
};
|
|
102
|
+
if (typeof ee.removeListener === 'function') {
|
|
103
|
+
// oxlint-disable-next-line @typescript-eslint/unbound-method -- patched like upstream OTel context manager
|
|
104
|
+
ee.removeListener = this._patchRemoveListener(ee, ee.removeListener );
|
|
2378
105
|
}
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
|
|
2382
|
-
core.setCapturedScopesOnSpan(span, scopes.scope, scopes.isolationScope);
|
|
106
|
+
if (typeof ee.off === 'function') {
|
|
107
|
+
// oxlint-disable-next-line @typescript-eslint/unbound-method
|
|
108
|
+
ee.off = this._patchRemoveListener(ee, ee.off );
|
|
2383
109
|
}
|
|
2384
|
-
|
|
2385
|
-
|
|
2386
|
-
|
|
2387
|
-
|
|
2388
|
-
|
|
2389
|
-
|
|
2390
|
-
|
|
2391
|
-
/** @inheritDoc */
|
|
2392
|
-
onEnd(span) {
|
|
2393
|
-
core.logSpanEnd(span);
|
|
2394
|
-
|
|
2395
|
-
const client = core.getClient();
|
|
2396
|
-
client?.emit('spanEnd', span);
|
|
2397
|
-
|
|
2398
|
-
if (client && core.hasSpanStreamingEnabled(client)) {
|
|
2399
|
-
client.emit('afterSpanEnd', span);
|
|
2400
|
-
} else {
|
|
2401
|
-
this._exporter.export(span);
|
|
110
|
+
if (typeof ee.removeAllListeners === 'function') {
|
|
111
|
+
ee.removeAllListeners = this._patchRemoveAllListeners(
|
|
112
|
+
ee,
|
|
113
|
+
// oxlint-disable-next-line @typescript-eslint/unbound-method
|
|
114
|
+
ee.removeAllListeners ,
|
|
115
|
+
);
|
|
2402
116
|
}
|
|
117
|
+
return ee;
|
|
2403
118
|
}
|
|
2404
|
-
}
|
|
2405
|
-
|
|
2406
|
-
/**
|
|
2407
|
-
* A custom OTEL sampler that uses Sentry sampling rates to make its decision
|
|
2408
|
-
*/
|
|
2409
|
-
class SentrySampler {
|
|
2410
119
|
|
|
2411
|
-
|
|
2412
|
-
|
|
2413
|
-
|
|
2414
|
-
|
|
120
|
+
_patchRemoveListener(ee, original) {
|
|
121
|
+
// oxlint-disable-next-line @typescript-eslint/no-this-alias
|
|
122
|
+
const contextManager = this;
|
|
123
|
+
return function ( event, listener) {
|
|
124
|
+
const events = contextManager._getPatchMap(ee)?.[event];
|
|
125
|
+
if (events === undefined) {
|
|
126
|
+
return original.call(this, event, listener);
|
|
127
|
+
}
|
|
128
|
+
const patchedListener = events.get(listener);
|
|
129
|
+
return original.call(this, event, patchedListener || listener);
|
|
130
|
+
};
|
|
2415
131
|
}
|
|
2416
132
|
|
|
2417
|
-
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
|
|
2427
|
-
|
|
2428
|
-
|
|
2429
|
-
const parentSpan = getValidSpan(context);
|
|
2430
|
-
const parentContext = parentSpan?.spanContext();
|
|
2431
|
-
|
|
2432
|
-
if (!core.hasSpansEnabled(options)) {
|
|
2433
|
-
return wrapSamplingDecision({ decision: undefined, context, spanAttributes });
|
|
2434
|
-
}
|
|
2435
|
-
|
|
2436
|
-
// `ATTR_HTTP_REQUEST_METHOD` is the new attribute, but we still support the old one, `SEMATTRS_HTTP_METHOD`, for now.
|
|
2437
|
-
// eslint-disable-next-line deprecation/deprecation
|
|
2438
|
-
const maybeSpanHttpMethod = spanAttributes[semanticConventions.SEMATTRS_HTTP_METHOD] || spanAttributes[semanticConventions.ATTR_HTTP_REQUEST_METHOD];
|
|
2439
|
-
|
|
2440
|
-
// If we have a http.client span that has no local parent, we never want to sample it
|
|
2441
|
-
// but we want to leave downstream sampling decisions up to the server
|
|
2442
|
-
if (spanKind === api.SpanKind.CLIENT && maybeSpanHttpMethod && (!parentSpan || parentContext?.isRemote)) {
|
|
2443
|
-
this._client.recordDroppedEvent('no_parent_span', 'span');
|
|
2444
|
-
return wrapSamplingDecision({ decision: undefined, context, spanAttributes });
|
|
2445
|
-
}
|
|
2446
|
-
|
|
2447
|
-
const parentSampled = parentSpan ? getParentSampled(parentSpan, traceId, spanName) : undefined;
|
|
2448
|
-
const isRootSpan = !parentSpan || parentContext?.isRemote;
|
|
2449
|
-
|
|
2450
|
-
// We only sample based on parameters (like tracesSampleRate or tracesSampler) for root spans (which is done in sampleSpan).
|
|
2451
|
-
// Non-root-spans simply inherit the sampling decision from their parent.
|
|
2452
|
-
if (!isRootSpan) {
|
|
2453
|
-
if (this._isSpanStreaming) {
|
|
2454
|
-
// `ignoreSpans` is only applied at span start for streamed spans.
|
|
2455
|
-
// Static spans/transactions get filtered at transaction end.
|
|
2456
|
-
// Likewise, we only record client outcomes for child spans when streaming
|
|
2457
|
-
if (parentSampled) {
|
|
2458
|
-
if (ignoreSpans?.length) {
|
|
2459
|
-
const { description: inferredChildName, op: childOp } = inferSpanData(spanName, spanAttributes, spanKind);
|
|
2460
|
-
if (
|
|
2461
|
-
core.shouldIgnoreSpan(
|
|
2462
|
-
{ description: inferredChildName, op: spanAttributes[core.SEMANTIC_ATTRIBUTE_SENTRY_OP] ?? childOp },
|
|
2463
|
-
ignoreSpans,
|
|
2464
|
-
)
|
|
2465
|
-
) {
|
|
2466
|
-
this._client.recordDroppedEvent('ignored', 'span');
|
|
2467
|
-
return wrapSamplingDecision({
|
|
2468
|
-
decision: sdkTraceBase.SamplingDecision.NOT_RECORD,
|
|
2469
|
-
context,
|
|
2470
|
-
spanAttributes,
|
|
2471
|
-
ignoredChildSpan: true,
|
|
2472
|
-
});
|
|
2473
|
-
}
|
|
2474
|
-
}
|
|
2475
|
-
}
|
|
2476
|
-
|
|
2477
|
-
if (!parentSampled) {
|
|
2478
|
-
const parentSegmentIgnored = parentContext?.traceState?.get(SENTRY_TRACE_STATE_SEGMENT_IGNORED) === '1';
|
|
2479
|
-
this._client.recordDroppedEvent(parentSegmentIgnored ? 'ignored' : 'sample_rate', 'span');
|
|
133
|
+
_patchRemoveAllListeners(ee, original) {
|
|
134
|
+
// oxlint-disable-next-line @typescript-eslint/no-this-alias
|
|
135
|
+
const contextManager = this;
|
|
136
|
+
return function ( event) {
|
|
137
|
+
const map = contextManager._getPatchMap(ee);
|
|
138
|
+
if (map !== undefined) {
|
|
139
|
+
if (arguments.length === 0) {
|
|
140
|
+
contextManager._createPatchMap(ee);
|
|
141
|
+
} else if (event !== undefined && map[event] !== undefined) {
|
|
142
|
+
// oxlint-disable-next-line @typescript-eslint/no-dynamic-delete -- event-keyed listener map
|
|
143
|
+
delete map[event];
|
|
2480
144
|
}
|
|
2481
145
|
}
|
|
2482
|
-
|
|
2483
|
-
return wrapSamplingDecision({
|
|
2484
|
-
decision: parentSampled ? sdkTraceBase.SamplingDecision.RECORD_AND_SAMPLED : sdkTraceBase.SamplingDecision.NOT_RECORD,
|
|
2485
|
-
context,
|
|
2486
|
-
spanAttributes,
|
|
2487
|
-
});
|
|
2488
|
-
}
|
|
2489
|
-
|
|
2490
|
-
// We want to pass the inferred name & attributes to the sampler method
|
|
2491
|
-
const {
|
|
2492
|
-
description: inferredSpanName,
|
|
2493
|
-
data: inferredAttributes,
|
|
2494
|
-
op,
|
|
2495
|
-
} = inferSpanData(spanName, spanAttributes, spanKind);
|
|
2496
|
-
|
|
2497
|
-
const mergedAttributes = {
|
|
2498
|
-
...inferredAttributes,
|
|
2499
|
-
...spanAttributes,
|
|
2500
|
-
};
|
|
2501
|
-
|
|
2502
|
-
if (op) {
|
|
2503
|
-
mergedAttributes[core.SEMANTIC_ATTRIBUTE_SENTRY_OP] = op;
|
|
2504
|
-
}
|
|
2505
|
-
|
|
2506
|
-
if (
|
|
2507
|
-
this._isSpanStreaming &&
|
|
2508
|
-
ignoreSpans?.length &&
|
|
2509
|
-
core.shouldIgnoreSpan(
|
|
2510
|
-
{ description: inferredSpanName, op: mergedAttributes[core.SEMANTIC_ATTRIBUTE_SENTRY_OP] ?? op },
|
|
2511
|
-
ignoreSpans,
|
|
2512
|
-
)
|
|
2513
|
-
) {
|
|
2514
|
-
this._client.recordDroppedEvent('ignored', 'span');
|
|
2515
|
-
return wrapSamplingDecision({
|
|
2516
|
-
decision: sdkTraceBase.SamplingDecision.NOT_RECORD,
|
|
2517
|
-
context,
|
|
2518
|
-
spanAttributes,
|
|
2519
|
-
ignoredSegmentSpan: true,
|
|
2520
|
-
});
|
|
2521
|
-
}
|
|
2522
|
-
|
|
2523
|
-
const mutableSamplingDecision = { decision: true };
|
|
2524
|
-
this._client.emit(
|
|
2525
|
-
'beforeSampling',
|
|
2526
|
-
{
|
|
2527
|
-
spanAttributes: mergedAttributes,
|
|
2528
|
-
spanName: inferredSpanName,
|
|
2529
|
-
parentSampled: parentSampled,
|
|
2530
|
-
parentContext: parentContext,
|
|
2531
|
-
},
|
|
2532
|
-
mutableSamplingDecision,
|
|
2533
|
-
);
|
|
2534
|
-
if (!mutableSamplingDecision.decision) {
|
|
2535
|
-
return wrapSamplingDecision({ decision: undefined, context, spanAttributes });
|
|
2536
|
-
}
|
|
2537
|
-
|
|
2538
|
-
const { isolationScope } = getScopesFromContext(context) ?? {};
|
|
2539
|
-
|
|
2540
|
-
const dscString = parentContext?.traceState ? parentContext.traceState.get(SENTRY_TRACE_STATE_DSC) : undefined;
|
|
2541
|
-
const dsc = dscString ? core.baggageHeaderToDynamicSamplingContext(dscString) : undefined;
|
|
2542
|
-
|
|
2543
|
-
const sampleRand = core.parseSampleRate(dsc?.sample_rand) ?? core._INTERNAL_safeMathRandom();
|
|
2544
|
-
|
|
2545
|
-
const [sampled, sampleRate, localSampleRateWasApplied] = core.sampleSpan(
|
|
2546
|
-
options,
|
|
2547
|
-
{
|
|
2548
|
-
name: inferredSpanName,
|
|
2549
|
-
attributes: mergedAttributes,
|
|
2550
|
-
normalizedRequest: isolationScope?.getScopeData().sdkProcessingMetadata.normalizedRequest,
|
|
2551
|
-
parentSampled,
|
|
2552
|
-
parentSampleRate: core.parseSampleRate(dsc?.sample_rate),
|
|
2553
|
-
},
|
|
2554
|
-
sampleRand,
|
|
2555
|
-
);
|
|
2556
|
-
|
|
2557
|
-
const method = `${maybeSpanHttpMethod}`.toUpperCase();
|
|
2558
|
-
if (method === 'OPTIONS' || method === 'HEAD') {
|
|
2559
|
-
debugBuild.DEBUG_BUILD && core.debug.log(`[Tracing] Not sampling span because HTTP method is '${method}' for ${spanName}`);
|
|
2560
|
-
|
|
2561
|
-
return wrapSamplingDecision({
|
|
2562
|
-
decision: sdkTraceBase.SamplingDecision.NOT_RECORD,
|
|
2563
|
-
context,
|
|
2564
|
-
spanAttributes,
|
|
2565
|
-
sampleRand,
|
|
2566
|
-
downstreamTraceSampleRate: 0, // we don't want to sample anything in the downstream trace either
|
|
2567
|
-
});
|
|
2568
|
-
}
|
|
2569
|
-
|
|
2570
|
-
if (
|
|
2571
|
-
!sampled &&
|
|
2572
|
-
// We check for `parentSampled === undefined` because we only want to record client reports for spans that are trace roots (ie. when there was incoming trace)
|
|
2573
|
-
parentSampled === undefined
|
|
2574
|
-
) {
|
|
2575
|
-
debugBuild.DEBUG_BUILD && core.debug.log('[Tracing] Discarding root span because its trace was not chosen to be sampled.');
|
|
2576
|
-
this._client.recordDroppedEvent('sample_rate', this._isSpanStreaming ? 'span' : 'transaction');
|
|
2577
|
-
}
|
|
2578
|
-
|
|
2579
|
-
return {
|
|
2580
|
-
...wrapSamplingDecision({
|
|
2581
|
-
decision: sampled ? sdkTraceBase.SamplingDecision.RECORD_AND_SAMPLED : sdkTraceBase.SamplingDecision.NOT_RECORD,
|
|
2582
|
-
context,
|
|
2583
|
-
spanAttributes,
|
|
2584
|
-
sampleRand,
|
|
2585
|
-
downstreamTraceSampleRate: localSampleRateWasApplied ? sampleRate : undefined,
|
|
2586
|
-
}),
|
|
2587
|
-
attributes: {
|
|
2588
|
-
// We set the sample rate on the span when a local sample rate was applied to better understand how traces were sampled in Sentry
|
|
2589
|
-
[core.SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: localSampleRateWasApplied ? sampleRate : undefined,
|
|
2590
|
-
},
|
|
146
|
+
return original.apply(this, arguments);
|
|
2591
147
|
};
|
|
2592
148
|
}
|
|
2593
149
|
|
|
2594
|
-
|
|
2595
|
-
|
|
2596
|
-
|
|
2597
|
-
|
|
2598
|
-
|
|
2599
|
-
|
|
2600
|
-
|
|
2601
|
-
|
|
2602
|
-
|
|
2603
|
-
|
|
2604
|
-
|
|
2605
|
-
|
|
2606
|
-
|
|
2607
|
-
|
|
2608
|
-
|
|
2609
|
-
|
|
2610
|
-
|
|
2611
|
-
|
|
2612
|
-
|
|
2613
|
-
const parentSampled = getSamplingDecision(parentContext);
|
|
2614
|
-
debugBuild.DEBUG_BUILD && core.debug.log(`[Tracing] Inheriting parent's sampled decision for ${spanName}: ${parentSampled}`);
|
|
2615
|
-
return parentSampled;
|
|
2616
|
-
}
|
|
2617
|
-
|
|
2618
|
-
return undefined;
|
|
2619
|
-
}
|
|
2620
|
-
|
|
2621
|
-
/**
|
|
2622
|
-
* Wrap a sampling decision with data that Sentry needs to work properly with it.
|
|
2623
|
-
* If you pass `decision: undefined`, it will be treated as `NOT_RECORDING`, but in contrast to passing `NOT_RECORDING`
|
|
2624
|
-
* it will not propagate this decision to downstream Sentry SDKs.
|
|
2625
|
-
*/
|
|
2626
|
-
function wrapSamplingDecision({
|
|
2627
|
-
decision,
|
|
2628
|
-
context,
|
|
2629
|
-
spanAttributes,
|
|
2630
|
-
sampleRand,
|
|
2631
|
-
downstreamTraceSampleRate,
|
|
2632
|
-
ignoredChildSpan,
|
|
2633
|
-
ignoredSegmentSpan,
|
|
2634
|
-
}
|
|
2635
|
-
|
|
2636
|
-
) {
|
|
2637
|
-
let traceState = getBaseTraceState(context, spanAttributes);
|
|
2638
|
-
|
|
2639
|
-
// We will override the propagated sample rate downstream when
|
|
2640
|
-
// - the tracesSampleRate is applied
|
|
2641
|
-
// - the tracesSampler is invoked
|
|
2642
|
-
// Since unsampled OTEL spans (NonRecordingSpans) cannot hold attributes we need to store this on the (trace)context.
|
|
2643
|
-
if (downstreamTraceSampleRate !== undefined) {
|
|
2644
|
-
traceState = traceState.set(SENTRY_TRACE_STATE_SAMPLE_RATE, `${downstreamTraceSampleRate}`);
|
|
2645
|
-
}
|
|
2646
|
-
|
|
2647
|
-
if (sampleRand !== undefined) {
|
|
2648
|
-
traceState = traceState.set(SENTRY_TRACE_STATE_SAMPLE_RAND, `${sampleRand}`);
|
|
2649
|
-
}
|
|
2650
|
-
|
|
2651
|
-
if (ignoredChildSpan) {
|
|
2652
|
-
traceState = traceState.set(SENTRY_TRACE_STATE_CHILD_IGNORED, '1');
|
|
2653
|
-
}
|
|
2654
|
-
|
|
2655
|
-
if (ignoredSegmentSpan) {
|
|
2656
|
-
traceState = traceState.set(SENTRY_TRACE_STATE_SEGMENT_IGNORED, '1');
|
|
2657
|
-
}
|
|
2658
|
-
|
|
2659
|
-
// If the decision is undefined, we treat it as NOT_RECORDING, but we don't propagate this decision to downstream SDKs
|
|
2660
|
-
// Which is done by not setting `SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING` traceState
|
|
2661
|
-
if (decision == undefined) {
|
|
2662
|
-
return { decision: sdkTraceBase.SamplingDecision.NOT_RECORD, traceState };
|
|
2663
|
-
}
|
|
2664
|
-
|
|
2665
|
-
if (decision === sdkTraceBase.SamplingDecision.NOT_RECORD) {
|
|
2666
|
-
return { decision, traceState: traceState.set(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING, '1') };
|
|
2667
|
-
}
|
|
2668
|
-
|
|
2669
|
-
return { decision, traceState };
|
|
2670
|
-
}
|
|
2671
|
-
|
|
2672
|
-
function getBaseTraceState(context, spanAttributes) {
|
|
2673
|
-
const parentSpan = api.trace.getSpan(context);
|
|
2674
|
-
const parentContext = parentSpan?.spanContext();
|
|
2675
|
-
|
|
2676
|
-
let traceState = parentContext?.traceState || new core$1.TraceState();
|
|
2677
|
-
|
|
2678
|
-
// We always keep the URL on the trace state, so we can access it in the propagator
|
|
2679
|
-
// `ATTR_URL_FULL` is the new attribute, but we still support the old one, `ATTR_HTTP_URL`, for now.
|
|
2680
|
-
// eslint-disable-next-line deprecation/deprecation
|
|
2681
|
-
const url = spanAttributes[semanticConventions.SEMATTRS_HTTP_URL] || spanAttributes[semanticConventions.ATTR_URL_FULL];
|
|
2682
|
-
if (url && typeof url === 'string') {
|
|
2683
|
-
traceState = traceState.set(SENTRY_TRACE_STATE_URL, url);
|
|
2684
|
-
}
|
|
2685
|
-
|
|
2686
|
-
return traceState;
|
|
2687
|
-
}
|
|
2688
|
-
|
|
2689
|
-
/**
|
|
2690
|
-
* If the active span is invalid, we want to ignore it as parent.
|
|
2691
|
-
* This aligns with how otel tracers and default samplers handle these cases.
|
|
2692
|
-
*/
|
|
2693
|
-
function getValidSpan(context) {
|
|
2694
|
-
const span = api.trace.getSpan(context);
|
|
2695
|
-
return span && api.isSpanContextValid(span.spanContext()) ? span : undefined;
|
|
2696
|
-
}
|
|
2697
|
-
|
|
2698
|
-
/**
|
|
2699
|
-
* Minimal Resource implementation that satisfies the OpenTelemetry Resource interface
|
|
2700
|
-
* used by BasicTracerProvider, without depending on `@opentelemetry/resources`.
|
|
2701
|
-
*/
|
|
2702
|
-
class SentryResource {
|
|
2703
|
-
|
|
2704
|
-
constructor(attributes) {
|
|
2705
|
-
this._attributes = attributes;
|
|
2706
|
-
}
|
|
150
|
+
_patchAddListener(ee, original, context) {
|
|
151
|
+
// oxlint-disable-next-line @typescript-eslint/no-this-alias
|
|
152
|
+
const contextManager = this;
|
|
153
|
+
return function ( event, listener) {
|
|
154
|
+
if (contextManager._wrapped) {
|
|
155
|
+
return original.call(this, event, listener);
|
|
156
|
+
}
|
|
157
|
+
let map = contextManager._getPatchMap(ee);
|
|
158
|
+
if (map === undefined) {
|
|
159
|
+
map = contextManager._createPatchMap(ee);
|
|
160
|
+
}
|
|
161
|
+
let listeners = map[event];
|
|
162
|
+
if (listeners === undefined) {
|
|
163
|
+
listeners = new WeakMap();
|
|
164
|
+
map[event] = listeners;
|
|
165
|
+
}
|
|
166
|
+
const patchedListener = contextManager.bind(context, listener);
|
|
167
|
+
listeners.set(listener, patchedListener);
|
|
2707
168
|
|
|
2708
|
-
|
|
2709
|
-
|
|
169
|
+
contextManager._wrapped = true;
|
|
170
|
+
try {
|
|
171
|
+
return original.call(this, event, patchedListener);
|
|
172
|
+
} finally {
|
|
173
|
+
contextManager._wrapped = false;
|
|
174
|
+
}
|
|
175
|
+
};
|
|
2710
176
|
}
|
|
2711
177
|
|
|
2712
|
-
|
|
2713
|
-
|
|
2714
|
-
|
|
2715
|
-
|
|
2716
|
-
return new SentryResource({ ...this._attributes, ...other.attributes });
|
|
178
|
+
_createPatchMap(ee) {
|
|
179
|
+
const map = Object.create(null) ;
|
|
180
|
+
(ee )[this._kOtListeners] = map;
|
|
181
|
+
return map;
|
|
2717
182
|
}
|
|
2718
183
|
|
|
2719
|
-
|
|
2720
|
-
return
|
|
184
|
+
_getPatchMap(ee) {
|
|
185
|
+
return (ee )[this._kOtListeners];
|
|
2721
186
|
}
|
|
2722
187
|
}
|
|
2723
188
|
|
|
2724
|
-
|
|
2725
|
-
|
|
2726
|
-
|
|
2727
|
-
|
|
2728
|
-
|
|
2729
|
-
|
|
2730
|
-
|
|
2731
|
-
|
|
2732
|
-
|
|
2733
|
-
|
|
2734
|
-
|
|
2735
|
-
|
|
2736
|
-
|
|
2737
|
-
|
|
2738
|
-
|
|
2739
|
-
|
|
2740
|
-
|
|
2741
|
-
|
|
2742
|
-
|
|
189
|
+
exports.SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION = resource.SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION;
|
|
190
|
+
exports.SentryPropagator = resource.SentryPropagator;
|
|
191
|
+
exports.SentrySampler = resource.SentrySampler;
|
|
192
|
+
exports.SentrySpanProcessor = resource.SentrySpanProcessor;
|
|
193
|
+
exports.continueTrace = resource.continueTrace;
|
|
194
|
+
exports.enhanceDscWithOpenTelemetryRootSpanName = resource.enhanceDscWithOpenTelemetryRootSpanName;
|
|
195
|
+
exports.getActiveSpan = resource.getActiveSpan;
|
|
196
|
+
exports.getRequestSpanData = resource.getRequestSpanData;
|
|
197
|
+
exports.getScopesFromContext = resource.getScopesFromContext;
|
|
198
|
+
exports.getSentryResource = resource.getSentryResource;
|
|
199
|
+
exports.getSpanKind = resource.getSpanKind;
|
|
200
|
+
exports.getTraceContextForScope = resource.getTraceContextForScope;
|
|
201
|
+
exports.isSentryRequestSpan = resource.isSentryRequestSpan;
|
|
202
|
+
exports.openTelemetrySetupCheck = resource.openTelemetrySetupCheck;
|
|
203
|
+
exports.setOpenTelemetryContextAsyncContextStrategy = resource.setOpenTelemetryContextAsyncContextStrategy;
|
|
204
|
+
exports.setupEventContextTrace = resource.setupEventContextTrace;
|
|
205
|
+
exports.spanHasAttributes = resource.spanHasAttributes;
|
|
206
|
+
exports.spanHasEvents = resource.spanHasEvents;
|
|
207
|
+
exports.spanHasKind = resource.spanHasKind;
|
|
208
|
+
exports.spanHasName = resource.spanHasName;
|
|
209
|
+
exports.spanHasParentId = resource.spanHasParentId;
|
|
210
|
+
exports.spanHasStatus = resource.spanHasStatus;
|
|
211
|
+
exports.startInactiveSpan = resource.startInactiveSpan;
|
|
212
|
+
exports.startSpan = resource.startSpan;
|
|
213
|
+
exports.startSpanManual = resource.startSpanManual;
|
|
214
|
+
exports.suppressTracing = resource.suppressTracing;
|
|
215
|
+
exports.withActiveSpan = resource.withActiveSpan;
|
|
216
|
+
exports.wrapClientClass = resource.wrapClientClass;
|
|
217
|
+
exports.wrapContextManagerClass = resource.wrapContextManagerClass;
|
|
218
|
+
exports.wrapSamplingDecision = resource.wrapSamplingDecision;
|
|
2743
219
|
exports.getClient = core.getClient;
|
|
2744
220
|
exports.getDynamicSamplingContextFromSpan = core.getDynamicSamplingContextFromSpan;
|
|
2745
221
|
exports.shouldPropagateTraceForUrl = core.shouldPropagateTraceForUrl;
|
|
2746
222
|
exports.withStreamedSpan = core.withStreamedSpan;
|
|
2747
|
-
exports.SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION = SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION;
|
|
2748
223
|
exports.SentryAsyncLocalStorageContextManager = SentryAsyncLocalStorageContextManager;
|
|
2749
|
-
exports.SentryPropagator = SentryPropagator;
|
|
2750
|
-
exports.SentrySampler = SentrySampler;
|
|
2751
|
-
exports.SentrySpanProcessor = SentrySpanProcessor;
|
|
2752
|
-
exports.continueTrace = continueTrace;
|
|
2753
|
-
exports.enhanceDscWithOpenTelemetryRootSpanName = enhanceDscWithOpenTelemetryRootSpanName;
|
|
2754
|
-
exports.getActiveSpan = getActiveSpan;
|
|
2755
|
-
exports.getRequestSpanData = getRequestSpanData;
|
|
2756
|
-
exports.getScopesFromContext = getScopesFromContext;
|
|
2757
|
-
exports.getSentryResource = getSentryResource;
|
|
2758
|
-
exports.getSpanKind = getSpanKind;
|
|
2759
|
-
exports.getTraceContextForScope = getTraceContextForScope;
|
|
2760
|
-
exports.isSentryRequestSpan = isSentryRequestSpan;
|
|
2761
|
-
exports.openTelemetrySetupCheck = openTelemetrySetupCheck;
|
|
2762
|
-
exports.setOpenTelemetryContextAsyncContextStrategy = setOpenTelemetryContextAsyncContextStrategy;
|
|
2763
|
-
exports.setupEventContextTrace = setupEventContextTrace;
|
|
2764
|
-
exports.spanHasAttributes = spanHasAttributes;
|
|
2765
|
-
exports.spanHasEvents = spanHasEvents;
|
|
2766
|
-
exports.spanHasKind = spanHasKind;
|
|
2767
|
-
exports.spanHasName = spanHasName;
|
|
2768
|
-
exports.spanHasParentId = spanHasParentId;
|
|
2769
|
-
exports.spanHasStatus = spanHasStatus;
|
|
2770
|
-
exports.startInactiveSpan = startInactiveSpan;
|
|
2771
|
-
exports.startSpan = startSpan;
|
|
2772
|
-
exports.startSpanManual = startSpanManual;
|
|
2773
|
-
exports.suppressTracing = suppressTracing;
|
|
2774
|
-
exports.withActiveSpan = withActiveSpan;
|
|
2775
|
-
exports.wrapClientClass = wrapClientClass;
|
|
2776
|
-
exports.wrapContextManagerClass = wrapContextManagerClass;
|
|
2777
|
-
exports.wrapSamplingDecision = wrapSamplingDecision;
|
|
2778
224
|
//# sourceMappingURL=index.js.map
|