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