@sentry/opentelemetry 11.0.0-alpha.0 → 11.0.0-alpha.2

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.
Files changed (40) hide show
  1. package/build/cjs/index.js +91 -461
  2. package/build/cjs/index.js.map +1 -1
  3. package/build/esm/index.js +94 -462
  4. package/build/esm/index.js.map +1 -1
  5. package/build/esm/package.json +1 -1
  6. package/build/types/asyncContextStrategy.d.ts.map +1 -1
  7. package/build/types/constants.d.ts +0 -5
  8. package/build/types/constants.d.ts.map +1 -1
  9. package/build/types/index.d.ts +1 -3
  10. package/build/types/index.d.ts.map +1 -1
  11. package/build/types/prepareSpanScope.d.ts +11 -0
  12. package/build/types/prepareSpanScope.d.ts.map +1 -0
  13. package/build/types/propagator.d.ts +0 -6
  14. package/build/types/propagator.d.ts.map +1 -1
  15. package/build/types/trace.d.ts +0 -33
  16. package/build/types/trace.d.ts.map +1 -1
  17. package/build/types/tracer.d.ts +6 -1
  18. package/build/types/tracer.d.ts.map +1 -1
  19. package/build/types/types.d.ts +1 -5
  20. package/build/types/types.d.ts.map +1 -1
  21. package/build/types/utils/buildContextWithSentryScopes.d.ts +1 -1
  22. package/build/types/utils/buildContextWithSentryScopes.d.ts.map +1 -1
  23. package/build/types/utils/contextData.d.ts.map +1 -1
  24. package/build/types/utils/getActiveSpan.d.ts +7 -2
  25. package/build/types/utils/getActiveSpan.d.ts.map +1 -1
  26. package/build/types/utils/getSamplingDecision.d.ts +0 -17
  27. package/build/types/utils/getSamplingDecision.d.ts.map +1 -1
  28. package/package.json +4 -3
  29. package/build/types/applyOtelSpanData.d.ts +0 -15
  30. package/build/types/applyOtelSpanData.d.ts.map +0 -1
  31. package/build/types/setupEventContextTrace.d.ts +0 -4
  32. package/build/types/setupEventContextTrace.d.ts.map +0 -1
  33. package/build/types/utils/backfillStreamedSpanData.d.ts +0 -14
  34. package/build/types/utils/backfillStreamedSpanData.d.ts.map +0 -1
  35. package/build/types/utils/mapStatus.d.ts +0 -3
  36. package/build/types/utils/mapStatus.d.ts.map +0 -1
  37. package/build/types/utils/parseSpanDescription.d.ts +0 -32
  38. package/build/types/utils/parseSpanDescription.d.ts.map +0 -1
  39. package/build/types/utils/reconcileDscSampled.d.ts +0 -14
  40. package/build/types/utils/reconcileDscSampled.d.ts.map +0 -1
@@ -1,19 +1,17 @@
1
- import { derefWeakRef, addNonEnumerableProperty, makeWeakRef, spanToTraceContext, getRootSpan, getDynamicSamplingContextFromSpan, dynamicSamplingContextToSentryBaggageHeader, consoleSandbox, isTracingSuppressed as isTracingSuppressed$1, getClient, getTraceData, propagationContextFromHeaders, baggageHeaderToDynamicSamplingContext, shouldContinueTrace, getCurrentScope, _INTERNAL_safeMathRandom, generateTraceId, getIsolationScope, getSpanStatusFromHttpCode, SPAN_STATUS_ERROR, SEMANTIC_ATTRIBUTE_SENTRY_OP, filterCollectedUrl, filterCollectedUrlQuery, getUrlQuery, getUrlFragment, SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, parseUrl, getSanitizedUrlString, stripUrlQueryAndFragment, spanToJSON, spanShouldInferOtelSource, spanSourceWasExplicitlySet, hasSpanStreamingEnabled, SPAN_STATUS_OK, isStatusErrorMessageValid, safeSetSpanJSONAttributes, markSpanAsTracerProviderSpan, markSpanForOtelSourceInference, getCapturedScopesOnSpan, spanIsIgnored, _INTERNAL_setSpanForScope, spanKindToName, startNewTrace, _INTERNAL_startInactiveSpan, withScope, SentryNonRecordingSpan, addChildSpanToSpan, setCapturedScopesOnSpan, hasSpansEnabled, SDK_VERSION, handleCallbackErrors, getAsyncContextStrategy, getMainCarrier, setAsyncContextStrategy, isContinuingTrace, getDefaultIsolationScope, getDefaultCurrentScope } from '@sentry/core';
1
+ import { derefWeakRef, makeWeakRef, dynamicSamplingContextToSentryBaggageHeader, consoleSandbox, isTracingSuppressed as isTracingSuppressed$1, getClient, getTraceData, propagationContextFromHeaders, baggageHeaderToDynamicSamplingContext, shouldContinueTrace, getCurrentScope, _INTERNAL_safeMathRandom, generateTraceId, getIsolationScope, markSpanAsTracerProviderSpan, getCapturedScopesOnSpan, spanIsIgnored, withScope, _INTERNAL_setSpanForScope, getActiveSpan as getActiveSpan$1, spanKindToName, startNewTrace, startInactiveSpan, SentryNonRecordingSpan, addChildSpanToSpan, setCapturedScopesOnSpan, getAsyncContextStrategy, getMainCarrier, setAsyncContextStrategy, isContinuingTrace, getDefaultIsolationScope, getDefaultCurrentScope, getDynamicSamplingContextFromSpan } from '@sentry/core';
2
2
  import * as api from '@opentelemetry/api';
3
- import { createContextKey, trace, context, TraceFlags, isSpanContextValid, SpanStatusCode, ROOT_CONTEXT } from '@opentelemetry/api';
4
- import { HTTP_RESPONSE_STATUS_CODE, HTTP_STATUS_CODE, RPC_GRPC_STATUS_CODE, HTTP_REQUEST_METHOD, HTTP_METHOD, DB_SYSTEM_NAME, DB_SYSTEM, RPC_SERVICE, MESSAGING_SYSTEM, MESSAGING_OPERATION_TYPE, FAAS_TRIGGER, SENTRY_KIND, URL_FULL, URL_QUERY, URL_FRAGMENT, HTTP_TARGET, HTTP_ROUTE, SENTRY_ORIGIN } from '@sentry/conventions/attributes';
5
- import { WEB_SERVER_HTTP_CLIENT_SPAN_OP, WEB_SERVER_HTTP_SERVER_SPAN_OP, WEB_SERVER_HTTP_SPAN_OP, MESSAGING_QUEUE_SPAN_OP, MESSAGING_QUEUE_PROCESS_SPAN_OP, MESSAGING_QUEUE_RECEIVE_SPAN_OP, MESSAGING_QUEUE_PUBLISH_SPAN_OP, GENERAL_FUNCTION_SPAN_OP } from '@sentry/conventions/op';
3
+ import { createContextKey, context, trace, TraceFlags, isSpanContextValid, ROOT_CONTEXT } from '@opentelemetry/api';
4
+ import { SENTRY_KIND } from '@sentry/conventions/attributes';
6
5
  import { AsyncLocalStorage } from 'node:async_hooks';
7
6
 
8
7
  const SENTRY_TRACE_STATE_DSC = "sentry.dsc";
9
8
  const SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING = "sentry.sampled_not_recording";
10
- const SENTRY_TRACE_STATE_CHILD_IGNORED = "sentry.ignored";
11
9
  const SENTRY_SCOPES_CONTEXT_KEY = createContextKey("sentry_scopes");
12
10
  const SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY = createContextKey("sentry_fork_isolation_scope");
13
11
  const SENTRY_FORK_SET_SCOPE_CONTEXT_KEY = createContextKey("sentry_fork_set_scope");
14
12
  const SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY = createContextKey("sentry_fork_set_isolation_scope");
15
13
 
16
- const SCOPE_CONTEXT_FIELD = "_scopeContext";
14
+ const SCOPE_CONTEXT_FIELD = "context";
17
15
  function getScopesFromContext(context) {
18
16
  return context.getValue(SENTRY_SCOPES_CONTEXT_KEY);
19
17
  }
@@ -21,33 +19,10 @@ function setScopesOnContext(context, scopes) {
21
19
  return context.setValue(SENTRY_SCOPES_CONTEXT_KEY, scopes);
22
20
  }
23
21
  function setContextOnScope(scope, context) {
24
- addNonEnumerableProperty(scope, SCOPE_CONTEXT_FIELD, makeWeakRef(context));
22
+ scope.refs[SCOPE_CONTEXT_FIELD] = makeWeakRef(context);
25
23
  }
26
24
  function getContextFromScope(scope) {
27
- return derefWeakRef(scope[SCOPE_CONTEXT_FIELD]);
28
- }
29
-
30
- function getActiveSpan() {
31
- return trace.getActiveSpan();
32
- }
33
-
34
- function setupEventContextTrace(client) {
35
- client.on("preprocessEvent", (event) => {
36
- const span = getActiveSpan();
37
- if (!span || event.type === "transaction") {
38
- return;
39
- }
40
- event.contexts = {
41
- trace: spanToTraceContext(span),
42
- ...event.contexts
43
- };
44
- const rootSpan = getRootSpan(span);
45
- event.sdkProcessingMetadata = {
46
- dynamicSamplingContext: getDynamicSamplingContextFromSpan(rootSpan),
47
- ...event.sdkProcessingMetadata
48
- };
49
- return event;
50
- });
25
+ return derefWeakRef(scope.refs[SCOPE_CONTEXT_FIELD]);
51
26
  }
52
27
 
53
28
  class TraceState {
@@ -193,233 +168,11 @@ function generateRemoteSpanContext({
193
168
  return spanContext;
194
169
  }
195
170
 
196
- const canonicalGrpcErrorCodesMap = {
197
- "1": "cancelled",
198
- "2": "unknown_error",
199
- "3": "invalid_argument",
200
- "4": "deadline_exceeded",
201
- "5": "not_found",
202
- "6": "already_exists",
203
- "7": "permission_denied",
204
- "8": "resource_exhausted",
205
- "9": "failed_precondition",
206
- "10": "aborted",
207
- "11": "out_of_range",
208
- "12": "unimplemented",
209
- "13": "internal_error",
210
- "14": "unavailable",
211
- "15": "data_loss",
212
- "16": "unauthenticated"
213
- };
214
- function inferStatusFromAttributes(attributes) {
215
- const httpCodeAttribute = attributes[HTTP_RESPONSE_STATUS_CODE] || attributes[HTTP_STATUS_CODE];
216
- const grpcCodeAttribute = attributes[RPC_GRPC_STATUS_CODE];
217
- const numberHttpCode = typeof httpCodeAttribute === "number" ? httpCodeAttribute : typeof httpCodeAttribute === "string" ? parseInt(httpCodeAttribute) : void 0;
218
- if (typeof numberHttpCode === "number") {
219
- return getSpanStatusFromHttpCode(numberHttpCode);
220
- }
221
- if (typeof grpcCodeAttribute === "string") {
222
- return { code: SPAN_STATUS_ERROR, message: canonicalGrpcErrorCodesMap[grpcCodeAttribute] || "unknown_error" };
223
- }
224
- return void 0;
225
- }
226
-
227
- function inferSpanData(attributes) {
228
- const httpMethod = attributes[HTTP_REQUEST_METHOD] || attributes[HTTP_METHOD];
229
- if (httpMethod) {
230
- return descriptionForHttpMethod(attributes);
231
- }
232
- const dbSystem = attributes[DB_SYSTEM_NAME] || attributes[DB_SYSTEM];
233
- const opIsCache = typeof attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] === "string" && attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP].startsWith("cache.");
234
- if (dbSystem && !opIsCache) {
235
- return descriptionForDbSystem(attributes);
236
- }
237
- const rpcService = attributes[RPC_SERVICE];
238
- if (rpcService) {
239
- return {
240
- op: "rpc"
241
- };
242
- }
243
- const messagingSystem = attributes[MESSAGING_SYSTEM];
244
- if (messagingSystem) {
245
- return {
246
- op: getMessagingOp(attributes[MESSAGING_OPERATION_TYPE])
247
- };
248
- }
249
- const faasTrigger = attributes[FAAS_TRIGGER];
250
- if (faasTrigger) {
251
- return {
252
- op: getFaasOp(faasTrigger)
253
- };
254
- }
255
- return { op: void 0 };
256
- }
257
- function getFaasOp(trigger) {
258
- switch (trigger) {
259
- case "http":
260
- return WEB_SERVER_HTTP_SERVER_SPAN_OP;
261
- case "pubsub":
262
- return MESSAGING_QUEUE_PROCESS_SPAN_OP;
263
- default:
264
- return GENERAL_FUNCTION_SPAN_OP;
265
- }
266
- }
267
- function getMessagingOp(operationType) {
268
- switch (operationType) {
269
- case "publish":
270
- case "send":
271
- return MESSAGING_QUEUE_PUBLISH_SPAN_OP;
272
- case "receive":
273
- return MESSAGING_QUEUE_RECEIVE_SPAN_OP;
274
- case "process":
275
- return MESSAGING_QUEUE_PROCESS_SPAN_OP;
276
- default:
277
- return MESSAGING_QUEUE_SPAN_OP;
278
- }
279
- }
280
- function descriptionForDbSystem(attributes) {
281
- const userDefinedName = attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];
282
- if (typeof userDefinedName === "string") {
283
- return {
284
- op: "db"
285
- };
286
- }
287
- if (attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] === "custom") {
288
- return { op: "db" };
289
- }
290
- return { op: "db" };
291
- }
292
- function descriptionForHttpMethod(attributes) {
293
- const kind = attributes[SENTRY_KIND];
294
- const op = kind === "client" ? WEB_SERVER_HTTP_CLIENT_SPAN_OP : kind === "server" ? WEB_SERVER_HTTP_SERVER_SPAN_OP : WEB_SERVER_HTTP_SPAN_OP;
295
- const { urlPath, url, query, fragment } = getSanitizedUrl(attributes);
296
- if (!urlPath) {
297
- return { op };
298
- }
299
- const data = {};
300
- if (url) {
301
- data[URL_FULL] = filterCollectedUrl(url);
302
- }
303
- const urlQuery = filterCollectedUrlQuery(getUrlQuery(query));
304
- if (urlQuery) {
305
- data[URL_QUERY] = urlQuery;
306
- }
307
- const urlFragment = getUrlFragment(fragment);
308
- if (urlFragment) {
309
- data[URL_FRAGMENT] = urlFragment;
310
- }
311
- return {
312
- op,
313
- data
314
- };
315
- }
316
- function getSanitizedUrl(attributes) {
317
- const kind = attributes[SENTRY_KIND];
318
- const httpTarget = attributes[HTTP_TARGET];
319
- const httpUrl = attributes[URL_FULL];
320
- const httpRoute = attributes[HTTP_ROUTE];
321
- const parsedUrl = typeof httpUrl === "string" ? parseUrl(httpUrl) : void 0;
322
- const url = parsedUrl ? getSanitizedUrlString(parsedUrl) : void 0;
323
- const query = parsedUrl?.search || void 0;
324
- const fragment = parsedUrl?.hash || void 0;
325
- if (typeof httpRoute === "string") {
326
- return { urlPath: httpRoute, url, query, fragment, hasRoute: true };
327
- }
328
- if (kind === "server" && typeof httpTarget === "string") {
329
- return { urlPath: stripUrlQueryAndFragment(httpTarget), url, query, fragment, hasRoute: false };
330
- }
331
- if (parsedUrl) {
332
- return { urlPath: url, url, query, fragment, hasRoute: false };
333
- }
334
- if (typeof httpTarget === "string") {
335
- return { urlPath: stripUrlQueryAndFragment(httpTarget), url, query, fragment, hasRoute: false };
336
- }
337
- return { urlPath: void 0, url, query, fragment, hasRoute: false };
338
- }
339
-
340
- function applyOtelSpanData(span, options = {}) {
341
- const spanJSON = spanToJSON(span);
342
- const attributes = spanJSON.data;
343
- const mayInferSource = spanShouldInferOtelSource(span);
344
- const hasCustomSpanName = attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME] !== void 0;
345
- const canInferSource = mayInferSource && !hasCustomSpanName && !spanSourceWasExplicitlySet(span);
346
- const attributesForInference = canInferSource && attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] === "custom" ? { ...attributes, [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: void 0 } : attributes;
347
- const inferred = inferSpanData(attributesForInference);
348
- if (inferred.op && attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] === void 0) {
349
- span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, inferred.op);
350
- }
351
- if (inferred.data) {
352
- Object.entries(inferred.data).forEach(([key, value]) => {
353
- if (value !== void 0 && attributes[key] === void 0) {
354
- span.setAttribute(key, value);
355
- }
356
- });
357
- }
358
- if (options.finalizeStatus) {
359
- applyOtelCompatibilityAttributes(span, attributes);
360
- const client = getClient();
361
- applyOtelSpanStatus(span, attributes, spanJSON.status, !!client && hasSpanStreamingEnabled(client));
362
- }
363
- }
364
- function applyOtelSpanStatus(span, attributes, status, spanStreamingEnabled) {
365
- if (status === "ok") {
366
- span.setStatus(inferStatusFromAttributes(attributes) || { code: SPAN_STATUS_OK });
367
- return;
368
- }
369
- if (!spanStreamingEnabled && status !== "ok" && !isStatusErrorMessageValid(status)) {
370
- span.setStatus({ code: SPAN_STATUS_ERROR, message: "internal_error" });
371
- }
372
- }
373
- function applyOtelCompatibilityAttributes(span, attributes) {
374
- const legacyHttpStatusCode = attributes[HTTP_STATUS_CODE];
375
- if (attributes[HTTP_RESPONSE_STATUS_CODE] === void 0 && legacyHttpStatusCode !== void 0) {
376
- span.setAttribute(HTTP_RESPONSE_STATUS_CODE, legacyHttpStatusCode);
377
- attributes[HTTP_RESPONSE_STATUS_CODE] = legacyHttpStatusCode;
378
- }
379
- }
380
-
381
- function backfillStreamedSpanDataFromOtel(spanJSON) {
382
- const attributes = spanJSON.attributes ?? {};
383
- const { op, data } = inferSpanData(attributes);
384
- safeSetSpanJSONAttributes(spanJSON, {
385
- [SEMANTIC_ATTRIBUTE_SENTRY_OP]: op,
386
- // If nothing in the chain previously set an origin, we now default it to 'manual'
387
- // For transactions, this is done in the SpanExporter.
388
- // TODO (v11): Remove this again once we fully moved away from OTel's TracerProvider.
389
- // at this point, we use `SentrySpan` everywhere, which defaults its origin to 'manual'.
390
- [SENTRY_ORIGIN]: "manual",
391
- ...data
392
- });
393
- }
394
-
395
171
  const SUPPRESS_TRACING_KEY = createContextKey("OpenTelemetry SDK Context Key SUPPRESS_TRACING");
396
- function suppressTracing(context) {
397
- return context.setValue(SUPPRESS_TRACING_KEY, true);
398
- }
399
172
  function isTracingSuppressed(context) {
400
173
  return context.getValue(SUPPRESS_TRACING_KEY) === true;
401
174
  }
402
175
 
403
- function getSamplingDecision(spanContext) {
404
- const { traceFlags, traceState } = spanContext;
405
- const sampledNotRecording = traceState ? traceState.get(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING) === "1" : false;
406
- if (traceFlags === TraceFlags.SAMPLED) {
407
- return true;
408
- }
409
- if (sampledNotRecording) {
410
- return false;
411
- }
412
- const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : void 0;
413
- const dsc = dscString ? baggageHeaderToDynamicSamplingContext(dscString) : void 0;
414
- if (dsc?.sampled === "true") {
415
- return true;
416
- }
417
- if (dsc?.sampled === "false") {
418
- return false;
419
- }
420
- return void 0;
421
- }
422
-
423
176
  class SentryTracer {
424
177
  /** @inheritdoc */
425
178
  startSpan(name, options = {}, ctx) {
@@ -431,27 +184,42 @@ class SentryTracer {
431
184
  }
432
185
  const span = this._startSentrySpan(name, options, parentSpan, ctx !== void 0);
433
186
  markSpanAsTracerProviderSpan(span);
434
- if (options.attributes?.[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] === void 0) {
435
- markSpanForOtelSourceInference(span);
436
- }
437
- applyOtelSpanData(span);
438
187
  return span;
439
188
  }
440
189
  startActiveSpan(name, optionsOrFn, contextOrFn, fn) {
441
190
  const options = typeof optionsOrFn === "function" ? {} : optionsOrFn;
442
- const ctx = typeof contextOrFn === "function" || contextOrFn === void 0 ? context.active() : contextOrFn;
191
+ const explicitCtx = typeof contextOrFn === "function" || contextOrFn === void 0 ? void 0 : contextOrFn;
192
+ const ctx = explicitCtx ?? context.active();
443
193
  const callback = typeof optionsOrFn === "function" ? optionsOrFn : typeof contextOrFn === "function" ? contextOrFn : fn;
444
- const span = this.startSpan(name, options, ctx);
194
+ const span = this.startSpan(name, options, explicitCtx);
445
195
  const capturedIsolationScope = getCapturedScopesOnSpan(span).isolationScope;
446
196
  const withCapturedIsolationScope = (contextToFork) => capturedIsolationScope ? contextToFork.setValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY, capturedIsolationScope) : contextToFork;
447
- if (spanIsIgnored(span) && trace.getSpan(ctx)) {
197
+ if (spanIsIgnored(span) && this._hasParentSpan(options, explicitCtx)) {
448
198
  return context.with(withCapturedIsolationScope(ctx), () => callback(span));
449
199
  }
450
200
  return context.with(withCapturedIsolationScope(trace.setSpan(ctx, span)), () => {
201
+ if (trace.getSpan(context.active()) !== span) {
202
+ return withScope((scope) => {
203
+ _INTERNAL_setSpanForScope(scope, span);
204
+ return callback(span);
205
+ });
206
+ }
451
207
  _INTERNAL_setSpanForScope(getCurrentScope(), span);
452
208
  return callback(span);
453
209
  });
454
210
  }
211
+ /**
212
+ * Whether a span started with these arguments gets a parent. Mirrors the parent lookup in `startSpan`
213
+ * plus core's fallback to the scope's active span, which is what parents the span on runtimes without an
214
+ * OTel context manager.
215
+ */
216
+ _hasParentSpan(options, explicitCtx) {
217
+ if (options.root) {
218
+ return false;
219
+ }
220
+ const parentSpan = explicitCtx ? trace.getSpan(explicitCtx) : getActiveSpan$1();
221
+ return !!parentSpan && isSpanContextValid(parentSpan.spanContext());
222
+ }
455
223
  _startSentrySpan(name, options, parentSpan, hasExplicitContext) {
456
224
  const sentryOptions = {
457
225
  name,
@@ -463,36 +231,16 @@ class SentryTracer {
463
231
  sentryOptions.attributes[SENTRY_KIND] = spanKindToName(options.kind);
464
232
  }
465
233
  if (options.root) {
466
- return startNewTrace(() => _INTERNAL_startInactiveSpan({ ...sentryOptions, parentSpan: null }));
467
- }
468
- if (parentSpan?.spanContext().isRemote) {
469
- return this._startRootSpanWithRemoteParent(sentryOptions, parentSpan);
234
+ return startNewTrace(() => startInactiveSpan({ ...sentryOptions, parentSpan: null }));
470
235
  }
471
236
  if (parentSpan) {
472
- return _INTERNAL_startInactiveSpan({ ...sentryOptions, parentSpan });
237
+ return startInactiveSpan({ ...sentryOptions, parentSpan });
473
238
  }
474
- return _INTERNAL_startInactiveSpan({
239
+ return startInactiveSpan({
475
240
  ...sentryOptions,
476
241
  parentSpan: hasExplicitContext ? null : void 0
477
242
  });
478
243
  }
479
- _startRootSpanWithRemoteParent(options, parentSpan) {
480
- const { spanId, traceId, traceState } = parentSpan.spanContext();
481
- const dsc = getDynamicSamplingContextFromSpan(parentSpan);
482
- const sampleRand = typeof dsc.sample_rand === "string" ? Number(dsc.sample_rand) : void 0;
483
- const hasIncomingDsc = !!traceState?.get(SENTRY_TRACE_STATE_DSC);
484
- return withScope((scope) => {
485
- scope.setPropagationContext({
486
- traceId,
487
- parentSpanId: spanId,
488
- sampled: getSamplingDecision(parentSpan.spanContext()),
489
- dsc: hasIncomingDsc ? dsc : void 0,
490
- sampleRand: typeof sampleRand === "number" && !Number.isNaN(sampleRand) ? sampleRand : _INTERNAL_safeMathRandom()
491
- });
492
- _INTERNAL_setSpanForScope(scope, void 0);
493
- return _INTERNAL_startInactiveSpan({ ...options, parentSpan: null });
494
- });
495
- }
496
244
  _createNonRecordingSpan(parentSpan) {
497
245
  const traceId = parentSpan?.spanContext().traceId ?? getCurrentScope().getPropagationContext().traceId;
498
246
  const span = new SentryNonRecordingSpan({ traceId });
@@ -529,186 +277,35 @@ class SentryTracerProvider {
529
277
  }
530
278
  }
531
279
 
532
- function reconcileDscSampled(dsc, sampled) {
533
- const reconciled = { ...dsc };
534
- if (sampled === void 0) {
535
- delete reconciled.sampled;
536
- } else {
537
- reconciled.sampled = String(sampled);
538
- if (sampled === false) {
539
- delete reconciled.transaction;
540
- }
541
- }
542
- return reconciled;
543
- }
544
-
545
- function _startSpan(options, callback, autoEnd) {
546
- const tracer = getTracer();
547
- const { name, parentSpan: customParentSpan } = options;
548
- const wrapper = getActiveSpanWrapper(customParentSpan);
549
- return wrapper(() => {
550
- const activeCtx = getContext(options.scope, options.forceTransaction);
551
- const missingRequiredParent = options.onlyIfParent && !trace.getSpan(activeCtx);
552
- const ctx = missingRequiredParent ? suppressTracing(activeCtx) : activeCtx;
553
- if (missingRequiredParent) {
554
- getClient()?.recordDroppedEvent("no_parent_span", "span");
555
- }
556
- const spanOptions = getSpanOptions(options);
557
- if (!hasSpansEnabled()) {
558
- const suppressedCtx = isTracingSuppressed(ctx) ? ctx : suppressTracing(ctx);
559
- return context.with(suppressedCtx, () => {
560
- return tracer.startActiveSpan(name, spanOptions, suppressedCtx, (span) => {
561
- patchSpanEnd(span);
562
- return context.with(trace.setSpan(activeCtx, span), () => {
563
- return handleCallbackErrors(
564
- () => callback(span),
565
- () => {
566
- if (spanToJSON(span).status === "ok") {
567
- span.setStatus({ code: SpanStatusCode.ERROR });
568
- }
569
- },
570
- autoEnd ? () => span.end() : void 0
571
- );
572
- });
573
- });
574
- });
575
- }
576
- return tracer.startActiveSpan(name, spanOptions, ctx, (span) => {
577
- patchSpanEnd(span);
578
- return handleCallbackErrors(
579
- () => callback(span),
580
- () => {
581
- if (spanToJSON(span).status === "ok") {
582
- span.setStatus({ code: SpanStatusCode.ERROR });
583
- }
584
- },
585
- autoEnd ? () => span.end() : void 0
586
- );
587
- });
588
- });
589
- }
590
- function startSpan(options, callback) {
591
- return _startSpan(options, callback, true);
592
- }
593
- function startSpanManual(options, callback) {
594
- return _startSpan(options, (span) => callback(span, () => span.end()), false);
595
- }
596
- function startInactiveSpan(options) {
597
- const tracer = getTracer();
598
- const { name, parentSpan: customParentSpan } = options;
599
- const wrapper = getActiveSpanWrapper(customParentSpan);
600
- return wrapper(() => {
601
- const activeCtx = getContext(options.scope, options.forceTransaction);
602
- const missingRequiredParent = options.onlyIfParent && !trace.getSpan(activeCtx);
603
- let ctx = missingRequiredParent ? suppressTracing(activeCtx) : activeCtx;
604
- if (missingRequiredParent) {
605
- getClient()?.recordDroppedEvent("no_parent_span", "span");
606
- }
607
- const spanOptions = getSpanOptions(options);
608
- if (!hasSpansEnabled()) {
609
- ctx = isTracingSuppressed(ctx) ? ctx : suppressTracing(ctx);
610
- }
611
- const span = tracer.startSpan(name, spanOptions, ctx);
612
- patchSpanEnd(span);
613
- return span;
614
- });
615
- }
616
280
  function withActiveSpan(span, callback) {
617
281
  const newContextWithActiveSpan = span ? trace.setSpan(context.active(), span) : trace.deleteSpan(context.active());
618
- return context.with(newContextWithActiveSpan, () => callback(getCurrentScope()));
619
- }
620
- function getTracer() {
621
- const client = getClient();
622
- return client?.tracer || trace.getTracer("@sentry/opentelemetry", SDK_VERSION);
623
- }
624
- function getSpanOptions(options) {
625
- const { startTime, attributes, kind, op, links } = options;
626
- const fixedStartTime = typeof startTime === "number" ? ensureTimestampInMilliseconds(startTime) : startTime;
627
- return {
628
- attributes: op ? {
629
- [SEMANTIC_ATTRIBUTE_SENTRY_OP]: op,
630
- ...attributes
631
- } : attributes,
632
- kind,
633
- links,
634
- startTime: fixedStartTime
635
- };
636
- }
637
- function ensureTimestampInMilliseconds(timestamp) {
638
- const isMs = timestamp < 9999999999;
639
- return isMs ? timestamp * 1e3 : timestamp;
640
- }
641
- function patchSpanEnd(span) {
642
- const originalEnd = span.end.bind(span);
643
- span.end = (endTime) => {
644
- return originalEnd(typeof endTime === "number" ? ensureTimestampInMilliseconds(endTime) : endTime);
645
- };
646
- }
647
- function getContext(scope, forceTransaction) {
648
- const ctx = getContextForScope(scope);
649
- const parentSpan = trace.getSpan(ctx);
650
- if (!parentSpan) {
651
- return ctx;
652
- }
653
- if (!forceTransaction) {
654
- return ctx;
655
- }
656
- const ctxWithoutSpan = trace.deleteSpan(ctx);
657
- const { spanId, traceId } = parentSpan.spanContext();
658
- const sampled = getSamplingDecision(parentSpan.spanContext());
659
- const rootSpan = getRootSpan(parentSpan);
660
- const rawDsc = getDynamicSamplingContextFromSpan(rootSpan);
661
- const hasIncomingFrozenDsc = !!rootSpan.spanContext().traceState?.get(SENTRY_TRACE_STATE_DSC);
662
- const dsc = hasIncomingFrozenDsc ? rawDsc : reconcileDscSampled(rawDsc, sampled);
663
- const traceState = makeTraceState({
664
- dsc,
665
- sampled
282
+ return context.with(newContextWithActiveSpan, () => {
283
+ const scope = getCurrentScope();
284
+ _INTERNAL_setSpanForScope(scope, span ?? void 0);
285
+ return callback(scope);
666
286
  });
667
- const spanOptions = {
668
- traceId,
669
- spanId,
670
- isRemote: true,
671
- traceFlags: sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,
672
- traceState
673
- };
674
- const ctxWithSpanContext = trace.setSpanContext(ctxWithoutSpan, spanOptions);
675
- return ctxWithSpanContext;
676
287
  }
677
- function getContextForScope(scope) {
678
- if (scope) {
679
- const ctx = getContextFromScope(scope);
680
- if (ctx) {
681
- return ctx;
682
- }
683
- }
684
- return context.active();
288
+
289
+ function getActiveSpan(scope) {
290
+ const span = scope ? getSpanFromScope(scope) : trace.getActiveSpan();
291
+ return span && isSpanContextValid(span.spanContext()) ? span : void 0;
685
292
  }
686
- function getActiveSpanWrapper(parentSpan) {
687
- return parentSpan !== void 0 ? (callback) => {
688
- return withActiveSpan(parentSpan, callback);
689
- } : (callback) => callback();
293
+ function getSpanFromScope(scope) {
294
+ const ctx = getContextFromScope(scope);
295
+ return ctx ? trace.getSpan(ctx) : void 0;
690
296
  }
691
297
 
692
- function buildContextWithSentryScopes(context, activeContext) {
693
- const span = trace.getSpan(context);
694
- let effectiveContext;
695
- if (span?.spanContext().traceState?.get(SENTRY_TRACE_STATE_CHILD_IGNORED) === "1") {
696
- const contextWithoutSpan = trace.deleteSpan(context);
697
- const parentSpan = trace.getSpan(activeContext);
698
- effectiveContext = parentSpan ? trace.setSpan(contextWithoutSpan, parentSpan) : contextWithoutSpan;
699
- } else {
700
- effectiveContext = context;
701
- }
702
- const currentScopes = getScopesFromContext(effectiveContext);
298
+ function buildContextWithSentryScopes(context) {
299
+ const currentScopes = getScopesFromContext(context);
703
300
  const currentScope = currentScopes?.scope || getCurrentScope();
704
301
  const currentIsolationScope = currentScopes?.isolationScope || getIsolationScope();
705
- const shouldForkIsolationScope = effectiveContext.getValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY) === true;
706
- const scope = effectiveContext.getValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY);
707
- const isolationScope = effectiveContext.getValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY);
302
+ const shouldForkIsolationScope = context.getValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY) === true;
303
+ const scope = context.getValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY);
304
+ const isolationScope = context.getValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY);
708
305
  const newCurrentScope = scope || currentScope.clone();
709
306
  const newIsolationScope = isolationScope || (shouldForkIsolationScope ? currentIsolationScope.clone() : currentIsolationScope);
710
307
  const scopes = { scope: newCurrentScope, isolationScope: newIsolationScope };
711
- const ctx1 = setScopesOnContext(effectiveContext, scopes);
308
+ const ctx1 = setScopesOnContext(context, scopes);
712
309
  const ctx2 = ctx1.deleteValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY).deleteValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY).deleteValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY);
713
310
  setContextOnScope(newCurrentScope, ctx2);
714
311
  return ctx2;
@@ -725,7 +322,7 @@ class SentryAsyncLocalStorageContextManager {
725
322
  return this._asyncLocalStorage.getStore() ?? ROOT_CONTEXT;
726
323
  }
727
324
  with(context, fn, thisArg, ...args) {
728
- const ctx2 = buildContextWithSentryScopes(context, this.active());
325
+ const ctx2 = buildContextWithSentryScopes(context);
729
326
  const cb = thisArg == null ? fn : fn.bind(thisArg);
730
327
  return this._asyncLocalStorage.run(ctx2, cb, ...args);
731
328
  }
@@ -933,8 +530,7 @@ function setOpenTelemetryContextAsyncContextStrategy() {
933
530
  }
934
531
  function getTracingChannelBinding() {
935
532
  return {
936
- asyncLocalStorage,
937
- getStoreWithActiveSpan
533
+ asyncLocalStorage
938
534
  };
939
535
  }
940
536
  setAsyncContextStrategy({
@@ -944,9 +540,6 @@ function setOpenTelemetryContextAsyncContextStrategy() {
944
540
  withIsolationScope,
945
541
  getCurrentScope,
946
542
  getIsolationScope,
947
- startSpan,
948
- startSpanManual,
949
- startInactiveSpan,
950
543
  getActiveSpan,
951
544
  // The types here don't fully align, because our own `Span` type is narrower
952
545
  // than the OTEL one - but this is OK for here, as we now we'll only have OTEL spans passed around
@@ -957,11 +550,50 @@ function setOpenTelemetryContextAsyncContextStrategy() {
957
550
  api.context.setGlobalContextManager(ctxManager);
958
551
  return ctxManager.getAsyncLocalStorageLookup();
959
552
  }
960
- function getStoreWithActiveSpan(span) {
961
- const activeContext = api.context.active();
962
- const isIgnoredChild = spanIsIgnored(span) && getRootSpan(span) !== span || span.spanContext().traceState?.get(SENTRY_TRACE_STATE_CHILD_IGNORED) === "1";
963
- return isIgnoredChild ? activeContext : api.trace.setSpan(activeContext, span);
553
+
554
+ function getSamplingDecision(spanContext) {
555
+ const { traceFlags, traceState } = spanContext;
556
+ const sampledNotRecording = traceState ? traceState.get(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING) === "1" : false;
557
+ if (traceFlags === TraceFlags.SAMPLED) {
558
+ return true;
559
+ }
560
+ if (sampledNotRecording) {
561
+ return false;
562
+ }
563
+ const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : void 0;
564
+ const dsc = dscString ? baggageHeaderToDynamicSamplingContext(dscString) : void 0;
565
+ if (dsc?.sampled === "true") {
566
+ return true;
567
+ }
568
+ if (dsc?.sampled === "false") {
569
+ return false;
570
+ }
571
+ return void 0;
572
+ }
573
+
574
+ function registerPrepareSpanScope(client) {
575
+ client.on("prepareSpanScope", (spanScope) => {
576
+ const { scope, parentSpan } = spanScope;
577
+ if (!parentSpan?.spanContext().isRemote) {
578
+ return;
579
+ }
580
+ const { spanId, traceId, traceState } = parentSpan.spanContext();
581
+ const dsc = getDynamicSamplingContextFromSpan(parentSpan);
582
+ const sampleRand = typeof dsc.sample_rand === "string" ? Number(dsc.sample_rand) : void 0;
583
+ const hasIncomingDsc = !!traceState?.get(SENTRY_TRACE_STATE_DSC);
584
+ const forkedScope = scope.clone();
585
+ forkedScope.setPropagationContext({
586
+ traceId,
587
+ parentSpanId: spanId,
588
+ sampled: getSamplingDecision(parentSpan.spanContext()),
589
+ dsc: hasIncomingDsc ? dsc : void 0,
590
+ sampleRand: typeof sampleRand === "number" && !Number.isNaN(sampleRand) ? sampleRand : _INTERNAL_safeMathRandom()
591
+ });
592
+ _INTERNAL_setSpanForScope(forkedScope, void 0);
593
+ spanScope.scope = forkedScope;
594
+ spanScope.parentSpan = void 0;
595
+ });
964
596
  }
965
597
 
966
- export { SentryPropagator, SentryTracerProvider, applyOtelSpanData, backfillStreamedSpanDataFromOtel, getScopesFromContext, setOpenTelemetryContextAsyncContextStrategy, setupEventContextTrace };
598
+ export { SentryPropagator, SentryTracerProvider, getScopesFromContext, registerPrepareSpanScope, setOpenTelemetryContextAsyncContextStrategy };
967
599
  //# sourceMappingURL=index.js.map