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