@sentry/opentelemetry 11.0.0-alpha.1 → 11.0.0-beta.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,6 +1,6 @@
1
- import { derefWeakRef, makeWeakRef, dynamicSamplingContextToSentryBaggageHeader, consoleSandbox, isTracingSuppressed as isTracingSuppressed$1, getClient, getTraceData, propagationContextFromHeaders, baggageHeaderToDynamicSamplingContext, shouldContinueTrace, getCurrentScope, _INTERNAL_safeMathRandom, generateTraceId, getIsolationScope, markSpanAsTracerProviderSpan, getCapturedScopesOnSpan, spanIsIgnored, _INTERNAL_setSpanForScope, spanKindToName, startNewTrace, _INTERNAL_startInactiveSpan, getDynamicSamplingContextFromSpan, withScope, SentryNonRecordingSpan, addChildSpanToSpan, setCapturedScopesOnSpan, hasSpansEnabled, SDK_VERSION, getRootSpan, SEMANTIC_ATTRIBUTE_SENTRY_OP, handleCallbackErrors, spanToStaticSpanJSON, 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, context, trace, TraceFlags, isSpanContextValid, SpanStatusCode, ROOT_CONTEXT } from '@opentelemetry/api';
3
+ import { createContextKey, context, trace, TraceFlags, isSpanContextValid, ROOT_CONTEXT } from '@opentelemetry/api';
4
4
  import { SENTRY_KIND } from '@sentry/conventions/attributes';
5
5
  import { AsyncLocalStorage } from 'node:async_hooks';
6
6
 
@@ -169,33 +169,10 @@ function generateRemoteSpanContext({
169
169
  }
170
170
 
171
171
  const SUPPRESS_TRACING_KEY = createContextKey("OpenTelemetry SDK Context Key SUPPRESS_TRACING");
172
- function suppressTracing(context) {
173
- return context.setValue(SUPPRESS_TRACING_KEY, true);
174
- }
175
172
  function isTracingSuppressed(context) {
176
173
  return context.getValue(SUPPRESS_TRACING_KEY) === true;
177
174
  }
178
175
 
179
- function getSamplingDecision(spanContext) {
180
- const { traceFlags, traceState } = spanContext;
181
- const sampledNotRecording = traceState ? traceState.get(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING) === "1" : false;
182
- if (traceFlags === TraceFlags.SAMPLED) {
183
- return true;
184
- }
185
- if (sampledNotRecording) {
186
- return false;
187
- }
188
- const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : void 0;
189
- const dsc = dscString ? baggageHeaderToDynamicSamplingContext(dscString) : void 0;
190
- if (dsc?.sampled === "true") {
191
- return true;
192
- }
193
- if (dsc?.sampled === "false") {
194
- return false;
195
- }
196
- return void 0;
197
- }
198
-
199
176
  class SentryTracer {
200
177
  /** @inheritdoc */
201
178
  startSpan(name, options = {}, ctx) {
@@ -211,19 +188,38 @@ class SentryTracer {
211
188
  }
212
189
  startActiveSpan(name, optionsOrFn, contextOrFn, fn) {
213
190
  const options = typeof optionsOrFn === "function" ? {} : optionsOrFn;
214
- 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();
215
193
  const callback = typeof optionsOrFn === "function" ? optionsOrFn : typeof contextOrFn === "function" ? contextOrFn : fn;
216
- const span = this.startSpan(name, options, ctx);
194
+ const span = this.startSpan(name, options, explicitCtx);
217
195
  const capturedIsolationScope = getCapturedScopesOnSpan(span).isolationScope;
218
196
  const withCapturedIsolationScope = (contextToFork) => capturedIsolationScope ? contextToFork.setValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY, capturedIsolationScope) : contextToFork;
219
- if (spanIsIgnored(span) && trace.getSpan(ctx)) {
197
+ if (spanIsIgnored(span) && this._hasParentSpan(options, explicitCtx)) {
220
198
  return context.with(withCapturedIsolationScope(ctx), () => callback(span));
221
199
  }
222
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
+ }
223
207
  _INTERNAL_setSpanForScope(getCurrentScope(), span);
224
208
  return callback(span);
225
209
  });
226
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
+ }
227
223
  _startSentrySpan(name, options, parentSpan, hasExplicitContext) {
228
224
  const sentryOptions = {
229
225
  name,
@@ -235,36 +231,16 @@ class SentryTracer {
235
231
  sentryOptions.attributes[SENTRY_KIND] = spanKindToName(options.kind);
236
232
  }
237
233
  if (options.root) {
238
- return startNewTrace(() => _INTERNAL_startInactiveSpan({ ...sentryOptions, parentSpan: null }));
239
- }
240
- if (parentSpan?.spanContext().isRemote) {
241
- return this._startRootSpanWithRemoteParent(sentryOptions, parentSpan);
234
+ return startNewTrace(() => startInactiveSpan({ ...sentryOptions, parentSpan: null }));
242
235
  }
243
236
  if (parentSpan) {
244
- return _INTERNAL_startInactiveSpan({ ...sentryOptions, parentSpan });
237
+ return startInactiveSpan({ ...sentryOptions, parentSpan });
245
238
  }
246
- return _INTERNAL_startInactiveSpan({
239
+ return startInactiveSpan({
247
240
  ...sentryOptions,
248
241
  parentSpan: hasExplicitContext ? null : void 0
249
242
  });
250
243
  }
251
- _startRootSpanWithRemoteParent(options, parentSpan) {
252
- const { spanId, traceId, traceState } = parentSpan.spanContext();
253
- const dsc = getDynamicSamplingContextFromSpan(parentSpan);
254
- const sampleRand = typeof dsc.sample_rand === "string" ? Number(dsc.sample_rand) : void 0;
255
- const hasIncomingDsc = !!traceState?.get(SENTRY_TRACE_STATE_DSC);
256
- return withScope((scope) => {
257
- scope.setPropagationContext({
258
- traceId,
259
- parentSpanId: spanId,
260
- sampled: getSamplingDecision(parentSpan.spanContext()),
261
- dsc: hasIncomingDsc ? dsc : void 0,
262
- sampleRand: typeof sampleRand === "number" && !Number.isNaN(sampleRand) ? sampleRand : _INTERNAL_safeMathRandom()
263
- });
264
- _INTERNAL_setSpanForScope(scope, void 0);
265
- return _INTERNAL_startInactiveSpan({ ...options, parentSpan: null });
266
- });
267
- }
268
244
  _createNonRecordingSpan(parentSpan) {
269
245
  const traceId = parentSpan?.spanContext().traceId ?? getCurrentScope().getPropagationContext().traceId;
270
246
  const span = new SentryNonRecordingSpan({ traceId });
@@ -301,174 +277,22 @@ class SentryTracerProvider {
301
277
  }
302
278
  }
303
279
 
304
- function reconcileDscSampled(dsc, sampled) {
305
- const reconciled = { ...dsc };
306
- if (sampled === void 0) {
307
- delete reconciled.sampled;
308
- } else {
309
- reconciled.sampled = String(sampled);
310
- if (sampled === false) {
311
- delete reconciled.transaction;
312
- }
313
- }
314
- return reconciled;
315
- }
316
-
317
- function _startSpan(options, callback, autoEnd) {
318
- const tracer = getTracer();
319
- const { name, parentSpan: customParentSpan } = options;
320
- const wrapper = getActiveSpanWrapper(customParentSpan);
321
- return wrapper(() => {
322
- const activeCtx = getContext(options.scope, options.forceTransaction);
323
- const missingRequiredParent = options.onlyIfParent && !trace.getSpan(activeCtx);
324
- const ctx = missingRequiredParent ? suppressTracing(activeCtx) : activeCtx;
325
- if (missingRequiredParent) {
326
- getClient()?.recordDroppedEvent("no_parent_span", "span");
327
- }
328
- const spanOptions = getSpanOptions(options);
329
- if (!hasSpansEnabled()) {
330
- const suppressedCtx = isTracingSuppressed(ctx) ? ctx : suppressTracing(ctx);
331
- return context.with(suppressedCtx, () => {
332
- return tracer.startActiveSpan(name, spanOptions, suppressedCtx, (span) => {
333
- patchSpanEnd(span);
334
- return context.with(trace.setSpan(activeCtx, span), () => {
335
- return handleCallbackErrors(
336
- () => callback(span),
337
- () => {
338
- if (spanToStaticSpanJSON(span).status === "ok") {
339
- span.setStatus({ code: SpanStatusCode.ERROR });
340
- }
341
- },
342
- autoEnd ? () => span.end() : void 0
343
- );
344
- });
345
- });
346
- });
347
- }
348
- return tracer.startActiveSpan(name, spanOptions, ctx, (span) => {
349
- patchSpanEnd(span);
350
- return handleCallbackErrors(
351
- () => callback(span),
352
- () => {
353
- if (spanToStaticSpanJSON(span).status === "ok") {
354
- span.setStatus({ code: SpanStatusCode.ERROR });
355
- }
356
- },
357
- autoEnd ? () => span.end() : void 0
358
- );
359
- });
360
- });
361
- }
362
- function startSpan(options, callback) {
363
- return _startSpan(options, callback, true);
364
- }
365
- function startSpanManual(options, callback) {
366
- return _startSpan(options, (span) => callback(span, () => span.end()), false);
367
- }
368
- function startInactiveSpan(options) {
369
- const tracer = getTracer();
370
- const { name, parentSpan: customParentSpan } = options;
371
- const wrapper = getActiveSpanWrapper(customParentSpan);
372
- return wrapper(() => {
373
- const activeCtx = getContext(options.scope, options.forceTransaction);
374
- const missingRequiredParent = options.onlyIfParent && !trace.getSpan(activeCtx);
375
- let ctx = missingRequiredParent ? suppressTracing(activeCtx) : activeCtx;
376
- if (missingRequiredParent) {
377
- getClient()?.recordDroppedEvent("no_parent_span", "span");
378
- }
379
- const spanOptions = getSpanOptions(options);
380
- if (!hasSpansEnabled()) {
381
- ctx = isTracingSuppressed(ctx) ? ctx : suppressTracing(ctx);
382
- }
383
- const span = tracer.startSpan(name, spanOptions, ctx);
384
- patchSpanEnd(span);
385
- return span;
386
- });
387
- }
388
280
  function withActiveSpan(span, callback) {
389
281
  const newContextWithActiveSpan = span ? trace.setSpan(context.active(), span) : trace.deleteSpan(context.active());
390
- return context.with(newContextWithActiveSpan, () => callback(getCurrentScope()));
391
- }
392
- function getTracer() {
393
- const client = getClient();
394
- return client?.tracer || trace.getTracer("@sentry/opentelemetry", SDK_VERSION);
395
- }
396
- function getSpanOptions(options) {
397
- const { startTime, attributes, op, links } = options;
398
- const fixedStartTime = typeof startTime === "number" ? ensureTimestampInMilliseconds(startTime) : startTime;
399
- return {
400
- attributes: op ? {
401
- [SEMANTIC_ATTRIBUTE_SENTRY_OP]: op,
402
- ...attributes
403
- } : attributes,
404
- links,
405
- startTime: fixedStartTime
406
- };
407
- }
408
- function ensureTimestampInMilliseconds(timestamp) {
409
- const isMs = timestamp < 9999999999;
410
- return isMs ? timestamp * 1e3 : timestamp;
411
- }
412
- function patchSpanEnd(span) {
413
- const originalEnd = span.end.bind(span);
414
- span.end = (endTime) => {
415
- return originalEnd(typeof endTime === "number" ? ensureTimestampInMilliseconds(endTime) : endTime);
416
- };
417
- }
418
- function getContext(scope, forceTransaction) {
419
- const ctx = getContextForScope(scope);
420
- const parentSpan = trace.getSpan(ctx);
421
- if (!parentSpan) {
422
- return ctx;
423
- }
424
- if (!forceTransaction) {
425
- return ctx;
426
- }
427
- const ctxWithoutSpan = trace.deleteSpan(ctx);
428
- const { spanId, traceId } = parentSpan.spanContext();
429
- const sampled = getSamplingDecision(parentSpan.spanContext());
430
- const rootSpan = getRootSpan(parentSpan);
431
- const rawDsc = getDynamicSamplingContextFromSpan(rootSpan);
432
- const hasIncomingFrozenDsc = !!rootSpan.spanContext().traceState?.get(SENTRY_TRACE_STATE_DSC);
433
- const dsc = hasIncomingFrozenDsc ? rawDsc : reconcileDscSampled(rawDsc, sampled);
434
- const traceState = makeTraceState({
435
- dsc,
436
- sampled
282
+ return context.with(newContextWithActiveSpan, () => {
283
+ const scope = getCurrentScope();
284
+ _INTERNAL_setSpanForScope(scope, span ?? void 0);
285
+ return callback(scope);
437
286
  });
438
- const spanOptions = {
439
- traceId,
440
- spanId,
441
- isRemote: true,
442
- traceFlags: sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,
443
- traceState
444
- };
445
- const ctxWithSpanContext = trace.setSpanContext(ctxWithoutSpan, spanOptions);
446
- return ctxWithSpanContext;
447
- }
448
- function getContextForScope(scope) {
449
- if (scope) {
450
- const ctx = getContextFromScope(scope);
451
- if (ctx) {
452
- return ctx;
453
- }
454
- }
455
- return context.active();
456
- }
457
- function getActiveSpanWrapper(parentSpan) {
458
- return parentSpan !== void 0 ? (callback) => {
459
- return withActiveSpan(parentSpan, callback);
460
- } : (callback) => callback();
461
287
  }
462
288
 
463
289
  function getActiveSpan(scope) {
464
- if (!scope) {
465
- return trace.getActiveSpan();
466
- }
290
+ const span = scope ? getSpanFromScope(scope) : trace.getActiveSpan();
291
+ return span && isSpanContextValid(span.spanContext()) ? span : void 0;
292
+ }
293
+ function getSpanFromScope(scope) {
467
294
  const ctx = getContextFromScope(scope);
468
- if (ctx) {
469
- return trace.getSpan(ctx);
470
- }
471
- return void 0;
295
+ return ctx ? trace.getSpan(ctx) : void 0;
472
296
  }
473
297
 
474
298
  function buildContextWithSentryScopes(context) {
@@ -716,9 +540,6 @@ function setOpenTelemetryContextAsyncContextStrategy() {
716
540
  withIsolationScope,
717
541
  getCurrentScope,
718
542
  getIsolationScope,
719
- startSpan,
720
- startSpanManual,
721
- startInactiveSpan,
722
543
  getActiveSpan,
723
544
  // The types here don't fully align, because our own `Span` type is narrower
724
545
  // than the OTEL one - but this is OK for here, as we now we'll only have OTEL spans passed around
@@ -730,5 +551,49 @@ function setOpenTelemetryContextAsyncContextStrategy() {
730
551
  return ctxManager.getAsyncLocalStorageLookup();
731
552
  }
732
553
 
733
- export { SentryPropagator, SentryTracerProvider, getScopesFromContext, setOpenTelemetryContextAsyncContextStrategy };
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
+ });
596
+ }
597
+
598
+ export { SentryPropagator, SentryTracerProvider, getScopesFromContext, registerPrepareSpanScope, setOpenTelemetryContextAsyncContextStrategy };
734
599
  //# sourceMappingURL=index.js.map