@sentry/opentelemetry 10.47.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.
Files changed (32) hide show
  1. package/README.md +3 -6
  2. package/build/cjs/index.js +399 -72
  3. package/build/cjs/index.js.map +1 -1
  4. package/build/esm/index.js +401 -77
  5. package/build/esm/index.js.map +1 -1
  6. package/build/esm/package.json +1 -1
  7. package/build/types/asyncLocalStorageContextManager.d.ts +31 -0
  8. package/build/types/asyncLocalStorageContextManager.d.ts.map +1 -0
  9. package/build/types/constants.d.ts +12 -0
  10. package/build/types/constants.d.ts.map +1 -1
  11. package/build/types/contextManager.d.ts +2 -0
  12. package/build/types/contextManager.d.ts.map +1 -1
  13. package/build/types/index.d.ts +3 -0
  14. package/build/types/index.d.ts.map +1 -1
  15. package/build/types/resource.d.ts +23 -0
  16. package/build/types/resource.d.ts.map +1 -0
  17. package/build/types/sampler.d.ts +4 -1
  18. package/build/types/sampler.d.ts.map +1 -1
  19. package/build/types/spanProcessor.d.ts.map +1 -1
  20. package/build/types/utils/buildContextWithSentryScopes.d.ts +12 -0
  21. package/build/types/utils/buildContextWithSentryScopes.d.ts.map +1 -0
  22. package/build/types/utils/contextData.d.ts +7 -0
  23. package/build/types/utils/contextData.d.ts.map +1 -1
  24. package/build/types-ts3.8/asyncLocalStorageContextManager.d.ts +31 -0
  25. package/build/types-ts3.8/constants.d.ts +12 -0
  26. package/build/types-ts3.8/contextManager.d.ts +2 -0
  27. package/build/types-ts3.8/index.d.ts +3 -0
  28. package/build/types-ts3.8/resource.d.ts +26 -0
  29. package/build/types-ts3.8/sampler.d.ts +4 -1
  30. package/build/types-ts3.8/utils/buildContextWithSentryScopes.d.ts +12 -0
  31. package/build/types-ts3.8/utils/contextData.d.ts +7 -0
  32. package/package.json +2 -4
@@ -1,9 +1,11 @@
1
- import { ATTR_URL_FULL, SEMATTRS_HTTP_URL, ATTR_HTTP_REQUEST_METHOD, SEMATTRS_HTTP_METHOD, ATTR_DB_SYSTEM_NAME, SEMATTRS_DB_SYSTEM, SEMATTRS_RPC_SERVICE, SEMATTRS_MESSAGING_SYSTEM, SEMATTRS_FAAS_TRIGGER, SEMATTRS_DB_STATEMENT, SEMATTRS_HTTP_TARGET, ATTR_HTTP_ROUTE, ATTR_HTTP_RESPONSE_STATUS_CODE, SEMATTRS_HTTP_STATUS_CODE, SEMATTRS_RPC_GRPC_STATUS_CODE } from '@opentelemetry/semantic-conventions';
2
- import { parseUrl, getSanitizedUrlString, SDK_VERSION, addNonEnumerableProperty, isSentryRequestUrl, getClient, baggageHeaderToDynamicSamplingContext, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME, stripUrlQueryAndFragment, spanToJSON, hasSpansEnabled, dynamicSamplingContextToSentryBaggageHeader, LRUMap, debug, shouldPropagateTraceForUrl, parseBaggageHeader, SENTRY_BAGGAGE_KEY_PREFIX, generateSentryTraceHeader, generateTraceparentHeader, getDynamicSamplingContextFromSpan, getCurrentScope, getDynamicSamplingContextFromScope, getIsolationScope, propagationContextFromHeaders, shouldContinueTrace, spanToTraceContext, getTraceContextFromScope, generateTraceId, generateSpanId, _INTERNAL_safeMathRandom, getRootSpan, handleCallbackErrors, getCapturedScopesOnSpan, setAsyncContextStrategy, getDefaultIsolationScope, getDefaultCurrentScope, SPAN_STATUS_OK, SPAN_STATUS_ERROR, getSpanStatusFromHttpCode, _INTERNAL_safeDateNow, debounce, timedEventsToMeasurements, captureEvent, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, convertSpanLinksForEnvelope, getStatusMessage, spanTimeInputToSeconds, addChildSpanToSpan, setCapturedScopesOnSpan, logSpanStart, logSpanEnd, parseSampleRate, sampleSpan } from '@sentry/core';
3
- export { getClient, getDynamicSamplingContextFromSpan, shouldPropagateTraceForUrl } from '@sentry/core';
1
+ import { ATTR_URL_FULL, SEMATTRS_HTTP_URL, ATTR_HTTP_REQUEST_METHOD, SEMATTRS_HTTP_METHOD, ATTR_DB_SYSTEM_NAME, SEMATTRS_DB_SYSTEM, SEMATTRS_RPC_SERVICE, SEMATTRS_MESSAGING_SYSTEM, SEMATTRS_FAAS_TRIGGER, SEMATTRS_DB_STATEMENT, SEMATTRS_HTTP_TARGET, ATTR_HTTP_ROUTE, ATTR_HTTP_RESPONSE_STATUS_CODE, SEMATTRS_HTTP_STATUS_CODE, SEMATTRS_RPC_GRPC_STATUS_CODE, ATTR_TELEMETRY_SDK_VERSION, ATTR_TELEMETRY_SDK_NAME, ATTR_TELEMETRY_SDK_LANGUAGE, ATTR_SERVICE_VERSION, SEMRESATTRS_SERVICE_NAMESPACE, ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions';
2
+ import { parseUrl, getSanitizedUrlString, SDK_VERSION, derefWeakRef, addNonEnumerableProperty, makeWeakRef, isSentryRequestUrl, getClient, baggageHeaderToDynamicSamplingContext, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME, stripUrlQueryAndFragment, spanToJSON, hasSpansEnabled, dynamicSamplingContextToSentryBaggageHeader, LRUMap, debug, shouldPropagateTraceForUrl, parseBaggageHeader, SENTRY_BAGGAGE_KEY_PREFIX, generateSentryTraceHeader, generateTraceparentHeader, getDynamicSamplingContextFromSpan, getCurrentScope, getDynamicSamplingContextFromScope, getIsolationScope, propagationContextFromHeaders, shouldContinueTrace, spanToTraceContext, getTraceContextFromScope, generateTraceId, generateSpanId, _INTERNAL_safeMathRandom, getRootSpan, handleCallbackErrors, getCapturedScopesOnSpan, setAsyncContextStrategy, getDefaultIsolationScope, getDefaultCurrentScope, SPAN_STATUS_OK, SPAN_STATUS_ERROR, getSpanStatusFromHttpCode, _INTERNAL_safeDateNow, debounce, timedEventsToMeasurements, captureEvent, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, convertSpanLinksForEnvelope, getStatusMessage, spanTimeInputToSeconds, addChildSpanToSpan, setCapturedScopesOnSpan, logSpanStart, logSpanEnd, hasSpanStreamingEnabled, shouldIgnoreSpan, parseSampleRate, sampleSpan } from '@sentry/core';
3
+ export { getClient, getDynamicSamplingContextFromSpan, shouldPropagateTraceForUrl, withStreamedSpan } from '@sentry/core';
4
4
  import * as api from '@opentelemetry/api';
5
5
  import { trace, SpanKind, createContextKey, TraceFlags, propagation, INVALID_TRACEID, context, SpanStatusCode, ROOT_CONTEXT, isSpanContextValid } from '@opentelemetry/api';
6
- import { TraceState, W3CBaggagePropagator, isTracingSuppressed, suppressTracing as suppressTracing$1 } from '@opentelemetry/core';
6
+ import { TraceState, W3CBaggagePropagator, isTracingSuppressed, suppressTracing as suppressTracing$1, SDK_INFO } from '@opentelemetry/core';
7
+ import { AsyncLocalStorage } from 'node:async_hooks';
8
+ import { EventEmitter } from 'node:events';
7
9
  import { SamplingDecision } from '@opentelemetry/sdk-trace-base';
8
10
 
9
11
  /** If this attribute is true, it means that the parent is a remote span. */
@@ -215,6 +217,20 @@ const SENTRY_TRACE_STATE_URL = 'sentry.url';
215
217
  const SENTRY_TRACE_STATE_SAMPLE_RAND = 'sentry.sample_rand';
216
218
  const SENTRY_TRACE_STATE_SAMPLE_RATE = 'sentry.sample_rate';
217
219
 
220
+ /**
221
+ * A flag marking a context as ignored because the span associated with the context
222
+ * is ignored (`ignoreSpans` filter).
223
+ */
224
+ const SENTRY_TRACE_STATE_CHILD_IGNORED = 'sentry.ignored';
225
+
226
+ /**
227
+ * A flag marking a segment span as ignored because it matched the `ignoreSpans` filter.
228
+ * Unlike `SENTRY_TRACE_STATE_CHILD_IGNORED` (used for child spans), this flag is NOT consumed
229
+ * by the context manager for re-parenting. Instead, it propagates to child spans so they
230
+ * can record the correct client report outcome (`ignored` instead of `sample_rate`).
231
+ */
232
+ const SENTRY_TRACE_STATE_SEGMENT_IGNORED = 'sentry.segment_ignored';
233
+
218
234
  const SENTRY_SCOPES_CONTEXT_KEY = createContextKey('sentry_scopes');
219
235
 
220
236
  const SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY = createContextKey('sentry_fork_isolation_scope');
@@ -244,16 +260,23 @@ function setScopesOnContext(context, scopes) {
244
260
  /**
245
261
  * Set the context on the scope so we can later look it up.
246
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).
247
269
  */
248
270
  function setContextOnScope(scope, context) {
249
- addNonEnumerableProperty(scope, SCOPE_CONTEXT_FIELD, context);
271
+ addNonEnumerableProperty(scope, SCOPE_CONTEXT_FIELD, makeWeakRef(context));
250
272
  }
251
273
 
252
274
  /**
253
275
  * Get the context related to a scope.
276
+ * Returns undefined if the context has been garbage collected (when WeakRef is used).
254
277
  */
255
278
  function getContextFromScope(scope) {
256
- return (scope )[SCOPE_CONTEXT_FIELD];
279
+ return derefWeakRef((scope )[SCOPE_CONTEXT_FIELD]);
257
280
  }
258
281
 
259
282
  /**
@@ -1434,6 +1457,51 @@ function setOpenTelemetryContextAsyncContextStrategy() {
1434
1457
  });
1435
1458
  }
1436
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 = trace.getSpan(context);
1471
+ let effectiveContext;
1472
+ if (span?.spanContext().traceState?.get(SENTRY_TRACE_STATE_CHILD_IGNORED) === '1') {
1473
+ const contextWithoutSpan = trace.deleteSpan(context);
1474
+ const parentSpan = trace.getSpan(activeContext);
1475
+ effectiveContext = parentSpan ? trace.setSpan(contextWithoutSpan, parentSpan) : contextWithoutSpan;
1476
+ } else {
1477
+ effectiveContext = context;
1478
+ }
1479
+
1480
+ const currentScopes = getScopesFromContext(effectiveContext);
1481
+ const currentScope = currentScopes?.scope || getCurrentScope();
1482
+ const currentIsolationScope = currentScopes?.isolationScope || 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
+
1437
1505
  /**
1438
1506
  * Wrap an OpenTelemetry ContextManager in a way that ensures the context is kept in sync with the Sentry Scope.
1439
1507
  *
@@ -1441,6 +1509,8 @@ function setOpenTelemetryContextAsyncContextStrategy() {
1441
1509
  * import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';
1442
1510
  * const SentryContextManager = wrapContextManagerClass(AsyncLocalStorageContextManager);
1443
1511
  * const contextManager = new SentryContextManager();
1512
+ *
1513
+ * @deprecated Use {@link SentryAsyncLocalStorageContextManager} instead.
1444
1514
  */
1445
1515
  function wrapContextManagerClass(
1446
1516
  ContextManagerClass,
@@ -1469,29 +1539,7 @@ function wrapContextManagerClass(
1469
1539
  thisArg,
1470
1540
  ...args
1471
1541
  ) {
1472
- const currentScopes = getScopesFromContext(context);
1473
- const currentScope = currentScopes?.scope || getCurrentScope();
1474
- const currentIsolationScope = currentScopes?.isolationScope || getIsolationScope();
1475
-
1476
- const shouldForkIsolationScope = context.getValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY) === true;
1477
- const scope = context.getValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY) ;
1478
- const isolationScope = context.getValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY) ;
1479
-
1480
- const newCurrentScope = scope || currentScope.clone();
1481
- const newIsolationScope =
1482
- isolationScope || (shouldForkIsolationScope ? currentIsolationScope.clone() : currentIsolationScope);
1483
- const scopes = { scope: newCurrentScope, isolationScope: newIsolationScope };
1484
-
1485
- const ctx1 = setScopesOnContext(context, scopes);
1486
-
1487
- // Remove the unneeded values again
1488
- const ctx2 = ctx1
1489
- .deleteValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY)
1490
- .deleteValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY)
1491
- .deleteValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY);
1492
-
1493
- setContextOnScope(newCurrentScope, ctx2);
1494
-
1542
+ const ctx2 = buildContextWithSentryScopes(context, this.active());
1495
1543
  return super.with(ctx2, fn, thisArg, ...args);
1496
1544
  }
1497
1545
 
@@ -1510,6 +1558,182 @@ function wrapContextManagerClass(
1510
1558
  return SentryContextManager ;
1511
1559
  }
1512
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 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() ?? 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 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
+
1513
1737
  /**
1514
1738
  * This function runs through a list of OTEL Spans, and wraps them in an `SpanNode`
1515
1739
  * where each node holds a reference to their parent node.
@@ -2078,49 +2302,6 @@ function getData(span) {
2078
2302
  return data;
2079
2303
  }
2080
2304
 
2081
- function onSpanStart(span, parentContext) {
2082
- // This is a reliable way to get the parent span - because this is exactly how the parent is identified in the OTEL SDK
2083
- const parentSpan = trace.getSpan(parentContext);
2084
-
2085
- let scopes = getScopesFromContext(parentContext);
2086
-
2087
- // We need access to the parent span in order to be able to move up the span tree for breadcrumbs
2088
- if (parentSpan && !parentSpan.spanContext().isRemote) {
2089
- addChildSpanToSpan(parentSpan, span);
2090
- }
2091
-
2092
- // We need this in the span exporter
2093
- if (parentSpan?.spanContext().isRemote) {
2094
- span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE, true);
2095
- }
2096
-
2097
- // The root context does not have scopes stored, so we check for this specifically
2098
- // As fallback we attach the global scopes
2099
- if (parentContext === ROOT_CONTEXT) {
2100
- scopes = {
2101
- scope: getDefaultCurrentScope(),
2102
- isolationScope: getDefaultIsolationScope(),
2103
- };
2104
- }
2105
-
2106
- // We need the scope at time of span creation in order to apply it to the event when the span is finished
2107
- if (scopes) {
2108
- setCapturedScopesOnSpan(span, scopes.scope, scopes.isolationScope);
2109
- }
2110
-
2111
- logSpanStart(span);
2112
-
2113
- const client = getClient();
2114
- client?.emit('spanStart', span);
2115
- }
2116
-
2117
- function onSpanEnd(span) {
2118
- logSpanEnd(span);
2119
-
2120
- const client = getClient();
2121
- client?.emit('spanEnd', span);
2122
- }
2123
-
2124
2305
  /**
2125
2306
  * Converts OpenTelemetry Spans to Sentry Spans and sends them to Sentry via
2126
2307
  * the Sentry SDK.
@@ -2150,14 +2331,53 @@ class SentrySpanProcessor {
2150
2331
  * @inheritDoc
2151
2332
  */
2152
2333
  onStart(span, parentContext) {
2153
- onSpanStart(span, parentContext);
2334
+ // This is a reliable way to get the parent span - because this is exactly how the parent is identified in the OTEL SDK
2335
+ const parentSpan = trace.getSpan(parentContext);
2336
+
2337
+ let scopes = getScopesFromContext(parentContext);
2338
+
2339
+ // We need access to the parent span in order to be able to move up the span tree for breadcrumbs
2340
+ if (parentSpan && !parentSpan.spanContext().isRemote) {
2341
+ addChildSpanToSpan(parentSpan, span);
2342
+ }
2343
+
2344
+ // We need this in the span exporter
2345
+ if (parentSpan?.spanContext().isRemote) {
2346
+ span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE, true);
2347
+ }
2348
+
2349
+ // The root context does not have scopes stored, so we check for this specifically
2350
+ // As fallback we attach the global scopes
2351
+ if (parentContext === ROOT_CONTEXT) {
2352
+ scopes = {
2353
+ scope: getDefaultCurrentScope(),
2354
+ isolationScope: getDefaultIsolationScope(),
2355
+ };
2356
+ }
2357
+
2358
+ // We need the scope at time of span creation in order to apply it to the event when the span is finished
2359
+ if (scopes) {
2360
+ setCapturedScopesOnSpan(span, scopes.scope, scopes.isolationScope);
2361
+ }
2362
+
2363
+ logSpanStart(span);
2364
+
2365
+ const client = getClient();
2366
+ client?.emit('spanStart', span);
2154
2367
  }
2155
2368
 
2156
2369
  /** @inheritDoc */
2157
2370
  onEnd(span) {
2158
- onSpanEnd(span);
2371
+ logSpanEnd(span);
2159
2372
 
2160
- this._exporter.export(span);
2373
+ const client = getClient();
2374
+ client?.emit('spanEnd', span);
2375
+
2376
+ if (client && hasSpanStreamingEnabled(client)) {
2377
+ client.emit('afterSpanEnd', span);
2378
+ } else {
2379
+ this._exporter.export(span);
2380
+ }
2161
2381
  }
2162
2382
  }
2163
2383
 
@@ -2168,6 +2388,7 @@ class SentrySampler {
2168
2388
 
2169
2389
  constructor(client) {
2170
2390
  this._client = client;
2391
+ this._isSpanStreaming = hasSpanStreamingEnabled(client);
2171
2392
  setIsSetup('SentrySampler');
2172
2393
  }
2173
2394
 
@@ -2181,6 +2402,7 @@ class SentrySampler {
2181
2402
  _links,
2182
2403
  ) {
2183
2404
  const options = this._client.getOptions();
2405
+ const { ignoreSpans } = options;
2184
2406
 
2185
2407
  const parentSpan = getValidSpan(context);
2186
2408
  const parentContext = parentSpan?.spanContext();
@@ -2205,6 +2427,36 @@ class SentrySampler {
2205
2427
  // We only sample based on parameters (like tracesSampleRate or tracesSampler) for root spans (which is done in sampleSpan).
2206
2428
  // Non-root-spans simply inherit the sampling decision from their parent.
2207
2429
  if (!isRootSpan) {
2430
+ if (this._isSpanStreaming) {
2431
+ // `ignoreSpans` is only applied at span start for streamed spans.
2432
+ // Static spans/transactions get filtered at transaction end.
2433
+ // Likewise, we only record client outcomes for child spans when streaming
2434
+ if (parentSampled) {
2435
+ if (ignoreSpans?.length) {
2436
+ const { description: inferredChildName, op: childOp } = inferSpanData(spanName, spanAttributes, spanKind);
2437
+ if (
2438
+ shouldIgnoreSpan(
2439
+ { description: inferredChildName, op: spanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] ?? childOp },
2440
+ ignoreSpans,
2441
+ )
2442
+ ) {
2443
+ this._client.recordDroppedEvent('ignored', 'span');
2444
+ return wrapSamplingDecision({
2445
+ decision: SamplingDecision.NOT_RECORD,
2446
+ context,
2447
+ spanAttributes,
2448
+ ignoredChildSpan: true,
2449
+ });
2450
+ }
2451
+ }
2452
+ }
2453
+
2454
+ if (!parentSampled) {
2455
+ const parentSegmentIgnored = parentContext?.traceState?.get(SENTRY_TRACE_STATE_SEGMENT_IGNORED) === '1';
2456
+ this._client.recordDroppedEvent(parentSegmentIgnored ? 'ignored' : 'sample_rate', 'span');
2457
+ }
2458
+ }
2459
+
2208
2460
  return wrapSamplingDecision({
2209
2461
  decision: parentSampled ? SamplingDecision.RECORD_AND_SAMPLED : SamplingDecision.NOT_RECORD,
2210
2462
  context,
@@ -2228,6 +2480,23 @@ class SentrySampler {
2228
2480
  mergedAttributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] = op;
2229
2481
  }
2230
2482
 
2483
+ if (
2484
+ this._isSpanStreaming &&
2485
+ ignoreSpans?.length &&
2486
+ shouldIgnoreSpan(
2487
+ { description: inferredSpanName, op: mergedAttributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] ?? op },
2488
+ ignoreSpans,
2489
+ )
2490
+ ) {
2491
+ this._client.recordDroppedEvent('ignored', 'span');
2492
+ return wrapSamplingDecision({
2493
+ decision: SamplingDecision.NOT_RECORD,
2494
+ context,
2495
+ spanAttributes,
2496
+ ignoredSegmentSpan: true,
2497
+ });
2498
+ }
2499
+
2231
2500
  const mutableSamplingDecision = { decision: true };
2232
2501
  this._client.emit(
2233
2502
  'beforeSampling',
@@ -2281,7 +2550,7 @@ class SentrySampler {
2281
2550
  parentSampled === undefined
2282
2551
  ) {
2283
2552
  DEBUG_BUILD && debug.log('[Tracing] Discarding root span because its trace was not chosen to be sampled.');
2284
- this._client.recordDroppedEvent('sample_rate', 'transaction');
2553
+ this._client.recordDroppedEvent('sample_rate', this._isSpanStreaming ? 'span' : 'transaction');
2285
2554
  }
2286
2555
 
2287
2556
  return {
@@ -2337,6 +2606,8 @@ function wrapSamplingDecision({
2337
2606
  spanAttributes,
2338
2607
  sampleRand,
2339
2608
  downstreamTraceSampleRate,
2609
+ ignoredChildSpan,
2610
+ ignoredSegmentSpan,
2340
2611
  }
2341
2612
 
2342
2613
  ) {
@@ -2354,6 +2625,14 @@ function wrapSamplingDecision({
2354
2625
  traceState = traceState.set(SENTRY_TRACE_STATE_SAMPLE_RAND, `${sampleRand}`);
2355
2626
  }
2356
2627
 
2628
+ if (ignoredChildSpan) {
2629
+ traceState = traceState.set(SENTRY_TRACE_STATE_CHILD_IGNORED, '1');
2630
+ }
2631
+
2632
+ if (ignoredSegmentSpan) {
2633
+ traceState = traceState.set(SENTRY_TRACE_STATE_SEGMENT_IGNORED, '1');
2634
+ }
2635
+
2357
2636
  // If the decision is undefined, we treat it as NOT_RECORDING, but we don't propagate this decision to downstream SDKs
2358
2637
  // Which is done by not setting `SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING` traceState
2359
2638
  if (decision == undefined) {
@@ -2393,5 +2672,50 @@ function getValidSpan(context) {
2393
2672
  return span && isSpanContextValid(span.spanContext()) ? span : undefined;
2394
2673
  }
2395
2674
 
2396
- export { SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION, SentryPropagator, SentrySampler, SentrySpanProcessor, continueTrace, enhanceDscWithOpenTelemetryRootSpanName, getActiveSpan, getRequestSpanData, getScopesFromContext, getSpanKind, getTraceContextForScope, isSentryRequestSpan, openTelemetrySetupCheck, setOpenTelemetryContextAsyncContextStrategy, setupEventContextTrace, spanHasAttributes, spanHasEvents, spanHasKind, spanHasName, spanHasParentId, spanHasStatus, startInactiveSpan, startSpan, startSpanManual, suppressTracing, withActiveSpan, wrapClientClass, wrapContextManagerClass, wrapSamplingDecision };
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
+ [ATTR_SERVICE_NAME]: serviceName,
2711
+ // eslint-disable-next-line deprecation/deprecation
2712
+ [SEMRESATTRS_SERVICE_NAMESPACE]: 'sentry',
2713
+ [ATTR_SERVICE_VERSION]: SDK_VERSION,
2714
+ [ATTR_TELEMETRY_SDK_LANGUAGE]: SDK_INFO[ATTR_TELEMETRY_SDK_LANGUAGE],
2715
+ [ATTR_TELEMETRY_SDK_NAME]: SDK_INFO[ATTR_TELEMETRY_SDK_NAME],
2716
+ [ATTR_TELEMETRY_SDK_VERSION]: SDK_INFO[ATTR_TELEMETRY_SDK_VERSION],
2717
+ });
2718
+ }
2719
+
2720
+ export { SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION, SentryAsyncLocalStorageContextManager, SentryPropagator, SentrySampler, SentrySpanProcessor, continueTrace, enhanceDscWithOpenTelemetryRootSpanName, getActiveSpan, getRequestSpanData, getScopesFromContext, getSentryResource, getSpanKind, getTraceContextForScope, isSentryRequestSpan, openTelemetrySetupCheck, setOpenTelemetryContextAsyncContextStrategy, setupEventContextTrace, spanHasAttributes, spanHasEvents, spanHasKind, spanHasName, spanHasParentId, spanHasStatus, startInactiveSpan, startSpan, startSpanManual, suppressTracing, withActiveSpan, wrapClientClass, wrapContextManagerClass, wrapSamplingDecision };
2397
2721
  //# sourceMappingURL=index.js.map