@sentry/opentelemetry 10.48.0 → 10.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -43,7 +43,7 @@ This is how you can use this in your app:
43
43
  2. Call `setupEventContextTrace(client)`
44
44
  3. Add `SentrySampler` as sampler
45
45
  4. Add `SentrySpanProcessor` as span processor
46
- 5. Add a context manager wrapped via `wrapContextManagerClass`
46
+ 5. Register the Sentry context manager (`SentryAsyncLocalStorageContextManager`, or `wrapContextManagerClass` for a custom base)
47
47
  6. Add `SentryPropagator` as propagator
48
48
  7. Setup OTEL-powered async context strategy for Sentry via `setOpenTelemetryContextAsyncContextStrategy()`
49
49
 
@@ -52,14 +52,13 @@ For example, you could set this up as follows:
52
52
  ```js
53
53
  import * as Sentry from '@sentry/node';
54
54
  import {
55
+ SentryAsyncLocalStorageContextManager,
55
56
  SentryPropagator,
56
57
  SentrySampler,
57
58
  SentrySpanProcessor,
58
59
  setupEventContextTrace,
59
- wrapContextManagerClass,
60
60
  setOpenTelemetryContextAsyncContextStrategy,
61
61
  } from '@sentry/opentelemetry';
62
- import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';
63
62
  import { context, propagation, trace } from '@opentelemetry/api';
64
63
 
65
64
  function setupSentry() {
@@ -75,12 +74,10 @@ function setupSentry() {
75
74
  });
76
75
  provider.addSpanProcessor(new SentrySpanProcessor());
77
76
 
78
- const SentryContextManager = wrapContextManagerClass(AsyncLocalStorageContextManager);
79
-
80
77
  // Initialize the provider
81
78
  trace.setGlobalTracerProvider(provider);
82
79
  propagation.setGlobalPropagator(new SentryPropagator());
83
- context.setGlobalContextManager(new SentryContextManager());
80
+ context.setGlobalContextManager(new SentryAsyncLocalStorageContextManager());
84
81
 
85
82
  setOpenTelemetryContextAsyncContextStrategy();
86
83
  }
@@ -4,6 +4,8 @@ const semanticConventions = require('@opentelemetry/semantic-conventions');
4
4
  const core = require('@sentry/core');
5
5
  const api = require('@opentelemetry/api');
6
6
  const core$1 = require('@opentelemetry/core');
7
+ const node_async_hooks = require('node:async_hooks');
8
+ const node_events = require('node:events');
7
9
  const sdkTraceBase = require('@opentelemetry/sdk-trace-base');
8
10
 
9
11
  /** If this attribute is true, it means that the parent is a remote span. */
@@ -258,16 +260,23 @@ function setScopesOnContext(context, scopes) {
258
260
  /**
259
261
  * Set the context on the scope so we can later look it up.
260
262
  * We need this to get the context from the scope in the `trace` functions.
263
+ *
264
+ * We use WeakRef to avoid a circular reference between the scope and the context.
265
+ * The context holds scopes (via SENTRY_SCOPES_CONTEXT_KEY), and if the scope held
266
+ * a strong reference back to the context, neither could be garbage collected even
267
+ * when the context is no longer reachable from application code (e.g., after a
268
+ * request completes but pooled connections retain patched callbacks).
261
269
  */
262
270
  function setContextOnScope(scope, context) {
263
- core.addNonEnumerableProperty(scope, SCOPE_CONTEXT_FIELD, context);
271
+ core.addNonEnumerableProperty(scope, SCOPE_CONTEXT_FIELD, core.makeWeakRef(context));
264
272
  }
265
273
 
266
274
  /**
267
275
  * Get the context related to a scope.
276
+ * Returns undefined if the context has been garbage collected (when WeakRef is used).
268
277
  */
269
278
  function getContextFromScope(scope) {
270
- return (scope )[SCOPE_CONTEXT_FIELD];
279
+ return core.derefWeakRef((scope )[SCOPE_CONTEXT_FIELD]);
271
280
  }
272
281
 
273
282
  /**
@@ -1448,6 +1457,51 @@ function setOpenTelemetryContextAsyncContextStrategy() {
1448
1457
  });
1449
1458
  }
1450
1459
 
1460
+ /**
1461
+ * Merge Sentry scopes into an OpenTelemetry {@link Context} and apply trace-context adjustments
1462
+ * used by Sentry OpenTelemetry context manager(s).
1463
+ *
1464
+ * @param context - Context passed into `ContextManager.with`.
1465
+ * @param activeContext - Context that was active before entering `with` (e.g. `this.active()`), used
1466
+ * to restore the parent span when the incoming span is marked ignored for children.
1467
+ * @returns A new context ready for `super.with` / `AsyncLocalStorage.run`.
1468
+ */
1469
+ function buildContextWithSentryScopes(context, activeContext) {
1470
+ const span = api.trace.getSpan(context);
1471
+ let effectiveContext;
1472
+ if (span?.spanContext().traceState?.get(SENTRY_TRACE_STATE_CHILD_IGNORED) === '1') {
1473
+ const contextWithoutSpan = api.trace.deleteSpan(context);
1474
+ const parentSpan = api.trace.getSpan(activeContext);
1475
+ effectiveContext = parentSpan ? api.trace.setSpan(contextWithoutSpan, parentSpan) : contextWithoutSpan;
1476
+ } else {
1477
+ effectiveContext = context;
1478
+ }
1479
+
1480
+ const currentScopes = getScopesFromContext(effectiveContext);
1481
+ const currentScope = currentScopes?.scope || core.getCurrentScope();
1482
+ const currentIsolationScope = currentScopes?.isolationScope || core.getIsolationScope();
1483
+
1484
+ const shouldForkIsolationScope = effectiveContext.getValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY) === true;
1485
+ const scope = effectiveContext.getValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY) ;
1486
+ const isolationScope = effectiveContext.getValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY) ;
1487
+
1488
+ const newCurrentScope = scope || currentScope.clone();
1489
+ const newIsolationScope =
1490
+ isolationScope || (shouldForkIsolationScope ? currentIsolationScope.clone() : currentIsolationScope);
1491
+ const scopes = { scope: newCurrentScope, isolationScope: newIsolationScope };
1492
+
1493
+ const ctx1 = setScopesOnContext(effectiveContext, scopes);
1494
+
1495
+ const ctx2 = ctx1
1496
+ .deleteValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY)
1497
+ .deleteValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY)
1498
+ .deleteValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY);
1499
+
1500
+ setContextOnScope(newCurrentScope, ctx2);
1501
+
1502
+ return ctx2;
1503
+ }
1504
+
1451
1505
  /**
1452
1506
  * Wrap an OpenTelemetry ContextManager in a way that ensures the context is kept in sync with the Sentry Scope.
1453
1507
  *
@@ -1455,6 +1509,8 @@ function setOpenTelemetryContextAsyncContextStrategy() {
1455
1509
  * import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';
1456
1510
  * const SentryContextManager = wrapContextManagerClass(AsyncLocalStorageContextManager);
1457
1511
  * const contextManager = new SentryContextManager();
1512
+ *
1513
+ * @deprecated Use {@link SentryAsyncLocalStorageContextManager} instead.
1458
1514
  */
1459
1515
  function wrapContextManagerClass(
1460
1516
  ContextManagerClass,
@@ -1483,45 +1539,7 @@ function wrapContextManagerClass(
1483
1539
  thisArg,
1484
1540
  ...args
1485
1541
  ) {
1486
- // Remove ignored spans from context and restore the parent span so children
1487
- // naturally parent to the grandparent instead of starting a new trace.
1488
- // At this point, this.active() still holds the outer context (before super.with()
1489
- // updates AsyncLocalStorage), which has the grandparent span we want to restore.
1490
- const span = api.trace.getSpan(context);
1491
- let effectiveContext;
1492
- if (span?.spanContext().traceState?.get(SENTRY_TRACE_STATE_CHILD_IGNORED) === '1') {
1493
- const contextWithoutSpan = api.trace.deleteSpan(context);
1494
- const parentSpan = api.trace.getSpan(this.active());
1495
- effectiveContext = parentSpan ? api.trace.setSpan(contextWithoutSpan, parentSpan) : contextWithoutSpan;
1496
- } else {
1497
- effectiveContext = context;
1498
- }
1499
-
1500
- const currentScopes = getScopesFromContext(effectiveContext);
1501
- const currentScope = currentScopes?.scope || core.getCurrentScope();
1502
- const currentIsolationScope = currentScopes?.isolationScope || core.getIsolationScope();
1503
-
1504
- const shouldForkIsolationScope = effectiveContext.getValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY) === true;
1505
- const scope = effectiveContext.getValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY) ;
1506
- const isolationScope = effectiveContext.getValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY)
1507
-
1508
- ;
1509
-
1510
- const newCurrentScope = scope || currentScope.clone();
1511
- const newIsolationScope =
1512
- isolationScope || (shouldForkIsolationScope ? currentIsolationScope.clone() : currentIsolationScope);
1513
- const scopes = { scope: newCurrentScope, isolationScope: newIsolationScope };
1514
-
1515
- const ctx1 = setScopesOnContext(effectiveContext, scopes);
1516
-
1517
- // Remove the unneeded values again
1518
- const ctx2 = ctx1
1519
- .deleteValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY)
1520
- .deleteValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY)
1521
- .deleteValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY);
1522
-
1523
- setContextOnScope(newCurrentScope, ctx2);
1524
-
1542
+ const ctx2 = buildContextWithSentryScopes(context, this.active());
1525
1543
  return super.with(ctx2, fn, thisArg, ...args);
1526
1544
  }
1527
1545
 
@@ -1540,6 +1558,182 @@ function wrapContextManagerClass(
1540
1558
  return SentryContextManager ;
1541
1559
  }
1542
1560
 
1561
+ const ADD_LISTENER_METHODS = ['addListener', 'on', 'once', 'prependListener', 'prependOnceListener'] ;
1562
+
1563
+ /**
1564
+ * OpenTelemetry-compatible context manager using Node.js `AsyncLocalStorage`.
1565
+ * Semantics match `@opentelemetry/context-async-hooks` (function `bind` + `EventEmitter` patching).
1566
+ */
1567
+ class SentryAsyncLocalStorageContextManager {
1568
+ __init() {this._asyncLocalStorage = new node_async_hooks.AsyncLocalStorage();}
1569
+
1570
+ __init2() {this._kOtListeners = Symbol('OtListeners');}
1571
+ __init3() {this._wrapped = false;}
1572
+
1573
+ constructor() {SentryAsyncLocalStorageContextManager.prototype.__init.call(this);SentryAsyncLocalStorageContextManager.prototype.__init2.call(this);SentryAsyncLocalStorageContextManager.prototype.__init3.call(this);
1574
+ setIsSetup('SentryContextManager');
1575
+ }
1576
+
1577
+ active() {
1578
+ return this._asyncLocalStorage.getStore() ?? api.ROOT_CONTEXT;
1579
+ }
1580
+
1581
+ with(
1582
+ context,
1583
+ fn,
1584
+ thisArg,
1585
+ ...args
1586
+ ) {
1587
+ const ctx2 = buildContextWithSentryScopes(context, this.active());
1588
+ const cb = thisArg == null ? fn : fn.bind(thisArg);
1589
+ return this._asyncLocalStorage.run(ctx2, cb , ...args);
1590
+ }
1591
+
1592
+ enable() {
1593
+ return this;
1594
+ }
1595
+
1596
+ disable() {
1597
+ this._asyncLocalStorage.disable();
1598
+ return this;
1599
+ }
1600
+
1601
+ bind(context, target) {
1602
+ if (target instanceof node_events.EventEmitter) {
1603
+ return this._bindEventEmitter(context, target);
1604
+ }
1605
+ if (typeof target === 'function') {
1606
+ return this._bindFunction(context, target ) ;
1607
+ }
1608
+ return target;
1609
+ }
1610
+
1611
+ /**
1612
+ * Gets underlying AsyncLocalStorage and symbol to allow lookup of scope.
1613
+ * This is Sentry-specific.
1614
+ */
1615
+ getAsyncLocalStorageLookup() {
1616
+ return {
1617
+ asyncLocalStorage: this._asyncLocalStorage,
1618
+ contextSymbol: SENTRY_SCOPES_CONTEXT_KEY,
1619
+ };
1620
+ }
1621
+
1622
+ _bindFunction(context, target) {
1623
+ const managerWith = this.with.bind(this);
1624
+ const contextWrapper = function ( ...args) {
1625
+ return managerWith(context, () => target.apply(this, args));
1626
+ };
1627
+ Object.defineProperty(contextWrapper, 'length', {
1628
+ enumerable: false,
1629
+ configurable: true,
1630
+ writable: false,
1631
+ value: target.length,
1632
+ });
1633
+ return contextWrapper;
1634
+ }
1635
+
1636
+ _bindEventEmitter(context, ee) {
1637
+ if (this._getPatchMap(ee) !== undefined) {
1638
+ return ee;
1639
+ }
1640
+ this._createPatchMap(ee);
1641
+
1642
+ for (const methodName of ADD_LISTENER_METHODS) {
1643
+ if (ee[methodName] === undefined) continue;
1644
+ ee[methodName] = this._patchAddListener(
1645
+ ee,
1646
+ ee[methodName] ,
1647
+ context,
1648
+ );
1649
+ }
1650
+ if (typeof ee.removeListener === 'function') {
1651
+ // oxlint-disable-next-line @typescript-eslint/unbound-method -- patched like upstream OTel context manager
1652
+ ee.removeListener = this._patchRemoveListener(ee, ee.removeListener );
1653
+ }
1654
+ if (typeof ee.off === 'function') {
1655
+ // oxlint-disable-next-line @typescript-eslint/unbound-method
1656
+ ee.off = this._patchRemoveListener(ee, ee.off );
1657
+ }
1658
+ if (typeof ee.removeAllListeners === 'function') {
1659
+ ee.removeAllListeners = this._patchRemoveAllListeners(
1660
+ ee,
1661
+ // oxlint-disable-next-line @typescript-eslint/unbound-method
1662
+ ee.removeAllListeners ,
1663
+ );
1664
+ }
1665
+ return ee;
1666
+ }
1667
+
1668
+ _patchRemoveListener(ee, original) {
1669
+ // oxlint-disable-next-line @typescript-eslint/no-this-alias
1670
+ const contextManager = this;
1671
+ return function ( event, listener) {
1672
+ const events = contextManager._getPatchMap(ee)?.[event];
1673
+ if (events === undefined) {
1674
+ return original.call(this, event, listener);
1675
+ }
1676
+ const patchedListener = events.get(listener);
1677
+ return original.call(this, event, patchedListener || listener);
1678
+ };
1679
+ }
1680
+
1681
+ _patchRemoveAllListeners(ee, original) {
1682
+ // oxlint-disable-next-line @typescript-eslint/no-this-alias
1683
+ const contextManager = this;
1684
+ return function ( event) {
1685
+ const map = contextManager._getPatchMap(ee);
1686
+ if (map !== undefined) {
1687
+ if (arguments.length === 0) {
1688
+ contextManager._createPatchMap(ee);
1689
+ } else if (event !== undefined && map[event] !== undefined) {
1690
+ // oxlint-disable-next-line @typescript-eslint/no-dynamic-delete -- event-keyed listener map
1691
+ delete map[event];
1692
+ }
1693
+ }
1694
+ return original.apply(this, arguments);
1695
+ };
1696
+ }
1697
+
1698
+ _patchAddListener(ee, original, context) {
1699
+ // oxlint-disable-next-line @typescript-eslint/no-this-alias
1700
+ const contextManager = this;
1701
+ return function ( event, listener) {
1702
+ if (contextManager._wrapped) {
1703
+ return original.call(this, event, listener);
1704
+ }
1705
+ let map = contextManager._getPatchMap(ee);
1706
+ if (map === undefined) {
1707
+ map = contextManager._createPatchMap(ee);
1708
+ }
1709
+ let listeners = map[event];
1710
+ if (listeners === undefined) {
1711
+ listeners = new WeakMap();
1712
+ map[event] = listeners;
1713
+ }
1714
+ const patchedListener = contextManager.bind(context, listener);
1715
+ listeners.set(listener, patchedListener);
1716
+
1717
+ contextManager._wrapped = true;
1718
+ try {
1719
+ return original.call(this, event, patchedListener);
1720
+ } finally {
1721
+ contextManager._wrapped = false;
1722
+ }
1723
+ };
1724
+ }
1725
+
1726
+ _createPatchMap(ee) {
1727
+ const map = Object.create(null) ;
1728
+ (ee )[this._kOtListeners] = map;
1729
+ return map;
1730
+ }
1731
+
1732
+ _getPatchMap(ee) {
1733
+ return (ee )[this._kOtListeners];
1734
+ }
1735
+ }
1736
+
1543
1737
  /**
1544
1738
  * This function runs through a list of OTEL Spans, and wraps them in an `SpanNode`
1545
1739
  * where each node holds a reference to their parent node.
@@ -2478,11 +2672,57 @@ function getValidSpan(context) {
2478
2672
  return span && api.isSpanContextValid(span.spanContext()) ? span : undefined;
2479
2673
  }
2480
2674
 
2675
+ /**
2676
+ * Minimal Resource implementation that satisfies the OpenTelemetry Resource interface
2677
+ * used by BasicTracerProvider, without depending on `@opentelemetry/resources`.
2678
+ */
2679
+ class SentryResource {
2680
+
2681
+ constructor(attributes) {
2682
+ this._attributes = attributes;
2683
+ }
2684
+
2685
+ get attributes() {
2686
+ return this._attributes;
2687
+ }
2688
+
2689
+ merge(other) {
2690
+ if (!other) {
2691
+ return this;
2692
+ }
2693
+ return new SentryResource({ ...this._attributes, ...other.attributes });
2694
+ }
2695
+
2696
+ getRawAttributes() {
2697
+ return Object.entries(this._attributes);
2698
+ }
2699
+ }
2700
+
2701
+ /**
2702
+ * Returns a Resource for use in Sentry's OpenTelemetry TracerProvider setup.
2703
+ *
2704
+ * Combines the default OTel SDK telemetry attributes with Sentry-specific
2705
+ * service attributes, equivalent to what was previously done via:
2706
+ * `defaultResource().merge(resourceFromAttributes({ ... }))`
2707
+ */
2708
+ function getSentryResource(serviceName) {
2709
+ return new SentryResource({
2710
+ [semanticConventions.ATTR_SERVICE_NAME]: serviceName,
2711
+ // eslint-disable-next-line deprecation/deprecation
2712
+ [semanticConventions.SEMRESATTRS_SERVICE_NAMESPACE]: 'sentry',
2713
+ [semanticConventions.ATTR_SERVICE_VERSION]: core.SDK_VERSION,
2714
+ [semanticConventions.ATTR_TELEMETRY_SDK_LANGUAGE]: core$1.SDK_INFO[semanticConventions.ATTR_TELEMETRY_SDK_LANGUAGE],
2715
+ [semanticConventions.ATTR_TELEMETRY_SDK_NAME]: core$1.SDK_INFO[semanticConventions.ATTR_TELEMETRY_SDK_NAME],
2716
+ [semanticConventions.ATTR_TELEMETRY_SDK_VERSION]: core$1.SDK_INFO[semanticConventions.ATTR_TELEMETRY_SDK_VERSION],
2717
+ });
2718
+ }
2719
+
2481
2720
  exports.getClient = core.getClient;
2482
2721
  exports.getDynamicSamplingContextFromSpan = core.getDynamicSamplingContextFromSpan;
2483
2722
  exports.shouldPropagateTraceForUrl = core.shouldPropagateTraceForUrl;
2484
2723
  exports.withStreamedSpan = core.withStreamedSpan;
2485
2724
  exports.SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION = SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION;
2725
+ exports.SentryAsyncLocalStorageContextManager = SentryAsyncLocalStorageContextManager;
2486
2726
  exports.SentryPropagator = SentryPropagator;
2487
2727
  exports.SentrySampler = SentrySampler;
2488
2728
  exports.SentrySpanProcessor = SentrySpanProcessor;
@@ -2491,6 +2731,7 @@ exports.enhanceDscWithOpenTelemetryRootSpanName = enhanceDscWithOpenTelemetryRoo
2491
2731
  exports.getActiveSpan = getActiveSpan;
2492
2732
  exports.getRequestSpanData = getRequestSpanData;
2493
2733
  exports.getScopesFromContext = getScopesFromContext;
2734
+ exports.getSentryResource = getSentryResource;
2494
2735
  exports.getSpanKind = getSpanKind;
2495
2736
  exports.getTraceContextForScope = getTraceContextForScope;
2496
2737
  exports.isSentryRequestSpan = isSentryRequestSpan;