@sentry/opentelemetry 8.41.0-beta.1 → 8.42.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 (61) hide show
  1. package/build/cjs/index.js +201 -116
  2. package/build/cjs/index.js.map +1 -1
  3. package/build/esm/index.js +200 -117
  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/custom/client.d.ts +1 -2
  8. package/build/types/custom/client.d.ts.map +1 -1
  9. package/build/types/index.d.ts +2 -2
  10. package/build/types/index.d.ts.map +1 -1
  11. package/build/types/instrumentation.d.ts +3 -0
  12. package/build/types/instrumentation.d.ts.map +1 -1
  13. package/build/types/propagator.d.ts +17 -4
  14. package/build/types/propagator.d.ts.map +1 -1
  15. package/build/types/sampler.d.ts +1 -1
  16. package/build/types/sampler.d.ts.map +1 -1
  17. package/build/types/setupEventContextTrace.d.ts +1 -1
  18. package/build/types/setupEventContextTrace.d.ts.map +1 -1
  19. package/build/types/spanExporter.d.ts +5 -7
  20. package/build/types/spanExporter.d.ts.map +1 -1
  21. package/build/types/trace.d.ts +6 -1
  22. package/build/types/trace.d.ts.map +1 -1
  23. package/build/types/types.d.ts +1 -1
  24. package/build/types/types.d.ts.map +1 -1
  25. package/build/types/utils/addOriginToSpan.d.ts +1 -1
  26. package/build/types/utils/addOriginToSpan.d.ts.map +1 -1
  27. package/build/types/utils/contextData.d.ts +1 -1
  28. package/build/types/utils/contextData.d.ts.map +1 -1
  29. package/build/types/utils/enhanceDscWithOpenTelemetryRootSpanName.d.ts +1 -1
  30. package/build/types/utils/enhanceDscWithOpenTelemetryRootSpanName.d.ts.map +1 -1
  31. package/build/types/utils/generateSpanContextForPropagationContext.d.ts +3 -1
  32. package/build/types/utils/generateSpanContextForPropagationContext.d.ts.map +1 -1
  33. package/build/types/utils/getRequestSpanData.d.ts +1 -1
  34. package/build/types/utils/getRequestSpanData.d.ts.map +1 -1
  35. package/build/types/utils/getTraceData.d.ts +4 -2
  36. package/build/types/utils/getTraceData.d.ts.map +1 -1
  37. package/build/types/utils/makeTraceState.d.ts +1 -1
  38. package/build/types/utils/makeTraceState.d.ts.map +1 -1
  39. package/build/types/utils/mapStatus.d.ts +1 -1
  40. package/build/types/utils/mapStatus.d.ts.map +1 -1
  41. package/build/types/utils/parseSpanDescription.d.ts +1 -1
  42. package/build/types/utils/parseSpanDescription.d.ts.map +1 -1
  43. package/build/types-ts3.8/custom/client.d.ts +1 -2
  44. package/build/types-ts3.8/index.d.ts +2 -2
  45. package/build/types-ts3.8/instrumentation.d.ts +3 -0
  46. package/build/types-ts3.8/propagator.d.ts +17 -4
  47. package/build/types-ts3.8/sampler.d.ts +1 -1
  48. package/build/types-ts3.8/setupEventContextTrace.d.ts +1 -1
  49. package/build/types-ts3.8/spanExporter.d.ts +5 -7
  50. package/build/types-ts3.8/trace.d.ts +9 -1
  51. package/build/types-ts3.8/types.d.ts +1 -1
  52. package/build/types-ts3.8/utils/addOriginToSpan.d.ts +1 -1
  53. package/build/types-ts3.8/utils/contextData.d.ts +1 -1
  54. package/build/types-ts3.8/utils/enhanceDscWithOpenTelemetryRootSpanName.d.ts +1 -1
  55. package/build/types-ts3.8/utils/generateSpanContextForPropagationContext.d.ts +3 -1
  56. package/build/types-ts3.8/utils/getRequestSpanData.d.ts +1 -1
  57. package/build/types-ts3.8/utils/getTraceData.d.ts +4 -2
  58. package/build/types-ts3.8/utils/makeTraceState.d.ts +1 -1
  59. package/build/types-ts3.8/utils/mapStatus.d.ts +1 -1
  60. package/build/types-ts3.8/utils/parseSpanDescription.d.ts +1 -1
  61. package/package.json +2 -3
@@ -535,8 +535,10 @@ function makeTraceState({
535
535
  /**
536
536
  * Generates a SpanContext that represents a PropagationContext.
537
537
  * This can be set on a `context` to make this a (virtual) active span.
538
+ *
539
+ * @deprecated This function is deprecated and will be removed in the next major version.
538
540
  */
539
- function generateSpanContextForPropagationContext(propagationContext) {
541
+ function generateSpanContextForPropagationContext$1(propagationContext) {
540
542
  // We store the DSC as OTEL trace state on the span context
541
543
  const traceState = makeTraceState({
542
544
  parentSpanId: propagationContext.parentSpanId,
@@ -546,6 +548,7 @@ function generateSpanContextForPropagationContext(propagationContext) {
546
548
 
547
549
  const spanContext = {
548
550
  traceId: propagationContext.traceId,
551
+ // TODO: Do not create an invalid span context here
549
552
  spanId: propagationContext.parentSpanId || '',
550
553
  isRemote: true,
551
554
  traceFlags: propagationContext.sampled ? api.TraceFlags.SAMPLED : api.TraceFlags.NONE,
@@ -676,11 +679,7 @@ class SentryPropagator extends core$1.W3CBaggagePropagator {
676
679
  const url = activeSpan && getCurrentURL(activeSpan);
677
680
 
678
681
  const tracePropagationTargets = _optionalChain$6([core.getClient, 'call', _ => _(), 'optionalAccess', _2 => _2.getOptions, 'call', _3 => _3(), 'optionalAccess', _4 => _4.tracePropagationTargets]);
679
- if (
680
- typeof url === 'string' &&
681
- tracePropagationTargets &&
682
- !this._shouldInjectTraceData(tracePropagationTargets, url)
683
- ) {
682
+ if (!shouldPropagateTraceForUrl(url, tracePropagationTargets, this._urlMatchesTargetsMap)) {
684
683
  DEBUG_BUILD &&
685
684
  core.logger.log(
686
685
  '[Tracing] Not injecting trace data for url because it does not match tracePropagationTargets:',
@@ -756,36 +755,52 @@ class SentryPropagator extends core$1.W3CBaggagePropagator {
756
755
  fields() {
757
756
  return [SENTRY_TRACE_HEADER, SENTRY_BAGGAGE_HEADER];
758
757
  }
758
+ }
759
759
 
760
- /** If we want to inject trace data for a given URL. */
761
- _shouldInjectTraceData(tracePropagationTargets, url) {
762
- if (tracePropagationTargets === undefined) {
763
- return true;
764
- }
760
+ const NOT_PROPAGATED_MESSAGE =
761
+ '[Tracing] Not injecting trace data for url because it does not match tracePropagationTargets:';
765
762
 
766
- const cachedDecision = this._urlMatchesTargetsMap.get(url);
767
- if (cachedDecision !== undefined) {
768
- return cachedDecision;
769
- }
763
+ /**
764
+ * Check if a given URL should be propagated to or not.
765
+ * If no url is defined, or no trace propagation targets are defined, this will always return `true`.
766
+ * You can also optionally provide a decision map, to cache decisions and avoid repeated regex lookups.
767
+ */
768
+ function shouldPropagateTraceForUrl(
769
+ url,
770
+ tracePropagationTargets,
771
+ decisionMap,
772
+ ) {
773
+ if (typeof url !== 'string' || !tracePropagationTargets) {
774
+ return true;
775
+ }
770
776
 
771
- const decision = core.stringMatchesSomePattern(url, tracePropagationTargets);
772
- this._urlMatchesTargetsMap.set(url, decision);
773
- return decision;
777
+ const cachedDecision = _optionalChain$6([decisionMap, 'optionalAccess', _5 => _5.get, 'call', _6 => _6(url)]);
778
+ if (cachedDecision !== undefined) {
779
+ DEBUG_BUILD && !cachedDecision && core.logger.log(NOT_PROPAGATED_MESSAGE, url);
780
+ return cachedDecision;
774
781
  }
782
+
783
+ const decision = core.stringMatchesSomePattern(url, tracePropagationTargets);
784
+ _optionalChain$6([decisionMap, 'optionalAccess', _7 => _7.set, 'call', _8 => _8(url, decision)]);
785
+
786
+ DEBUG_BUILD && !decision && core.logger.log(NOT_PROPAGATED_MESSAGE, url);
787
+ return decision;
775
788
  }
776
789
 
790
+ /**
791
+ * Get propagation injection data for the given context.
792
+ */
777
793
  function getInjectionData(context)
778
794
 
779
795
  {
780
796
  const span = api.trace.getSpan(context);
781
- const spanIsRemote = _optionalChain$6([span, 'optionalAccess', _5 => _5.spanContext, 'call', _6 => _6(), 'access', _7 => _7.isRemote]);
797
+ const spanIsRemote = _optionalChain$6([span, 'optionalAccess', _9 => _9.spanContext, 'call', _10 => _10(), 'access', _11 => _11.isRemote]);
782
798
 
783
799
  // If we have a local span, we can just pick everything from it
784
800
  if (span && !spanIsRemote) {
785
801
  const spanContext = span.spanContext();
786
802
 
787
- const propagationContext = getPropagationContextFromSpan(span);
788
- const dynamicSamplingContext = getDynamicSamplingContext(propagationContext, spanContext.traceId);
803
+ const dynamicSamplingContext = core.getDynamicSamplingContextFromSpan(span);
789
804
  return {
790
805
  dynamicSamplingContext,
791
806
  traceId: spanContext.traceId,
@@ -795,38 +810,21 @@ function getInjectionData(context)
795
810
  }
796
811
 
797
812
  // Else we try to use the propagation context from the scope
798
- const scope = _optionalChain$6([getScopesFromContext, 'call', _8 => _8(context), 'optionalAccess', _9 => _9.scope]) || core.getCurrentScope();
813
+ const scope = _optionalChain$6([getScopesFromContext, 'call', _12 => _12(context), 'optionalAccess', _13 => _13.scope]) || core.getCurrentScope();
814
+ const client = core.getClient();
799
815
 
800
816
  const propagationContext = scope.getPropagationContext();
801
- const dynamicSamplingContext = getDynamicSamplingContext(propagationContext, propagationContext.traceId);
817
+ const dynamicSamplingContext = client ? core.getDynamicSamplingContextFromScope(client, scope) : undefined;
802
818
  return {
803
819
  dynamicSamplingContext,
804
820
  traceId: propagationContext.traceId,
821
+ // TODO(v9): Use generateSpanId() instead
822
+ // eslint-disable-next-line deprecation/deprecation
805
823
  spanId: propagationContext.spanId,
806
824
  sampled: propagationContext.sampled,
807
825
  };
808
826
  }
809
827
 
810
- /** Get the DSC from a context, or fall back to use the one from the client. */
811
- function getDynamicSamplingContext(
812
- propagationContext,
813
- traceId,
814
- ) {
815
- // If we have a DSC on the propagation context, we just use it
816
- if (_optionalChain$6([propagationContext, 'optionalAccess', _10 => _10.dsc])) {
817
- return propagationContext.dsc;
818
- }
819
-
820
- // Else, we try to generate a new one
821
- const client = core.getClient();
822
-
823
- if (client) {
824
- return core.getDynamicSamplingContextFromClient(traceId || propagationContext.traceId, client);
825
- }
826
-
827
- return undefined;
828
- }
829
-
830
828
  function getContextWithRemoteActiveSpan(
831
829
  ctx,
832
830
  { sentryTrace, baggage },
@@ -874,13 +872,13 @@ function getCurrentURL(span) {
874
872
  const spanData = core.spanToJSON(span).data;
875
873
  // `ATTR_URL_FULL` is the new attribute, but we still support the old one, `SEMATTRS_HTTP_URL`, for now.
876
874
  // eslint-disable-next-line deprecation/deprecation
877
- const urlAttribute = _optionalChain$6([spanData, 'optionalAccess', _11 => _11[semanticConventions.SEMATTRS_HTTP_URL]]) || _optionalChain$6([spanData, 'optionalAccess', _12 => _12[semanticConventions.ATTR_URL_FULL]]);
875
+ const urlAttribute = _optionalChain$6([spanData, 'optionalAccess', _14 => _14[semanticConventions.SEMATTRS_HTTP_URL]]) || _optionalChain$6([spanData, 'optionalAccess', _15 => _15[semanticConventions.ATTR_URL_FULL]]);
878
876
  if (urlAttribute) {
879
877
  return urlAttribute;
880
878
  }
881
879
 
882
880
  // Also look at the traceState, which we may set in the sampler even for unsampled spans
883
- const urlTraceState = _optionalChain$6([span, 'access', _13 => _13.spanContext, 'call', _14 => _14(), 'access', _15 => _15.traceState, 'optionalAccess', _16 => _16.get, 'call', _17 => _17(SENTRY_TRACE_STATE_URL)]);
881
+ const urlTraceState = _optionalChain$6([span, 'access', _16 => _16.spanContext, 'call', _17 => _17(), 'access', _18 => _18.traceState, 'optionalAccess', _19 => _19.get, 'call', _20 => _20(SENTRY_TRACE_STATE_URL)]);
884
882
  if (urlTraceState) {
885
883
  return urlTraceState;
886
884
  }
@@ -888,6 +886,26 @@ function getCurrentURL(span) {
888
886
  return undefined;
889
887
  }
890
888
 
889
+ // TODO: Adjust this behavior to avoid invalid spans
890
+ function generateSpanContextForPropagationContext(propagationContext) {
891
+ // We store the DSC as OTEL trace state on the span context
892
+ const traceState = makeTraceState({
893
+ parentSpanId: propagationContext.parentSpanId,
894
+ dsc: propagationContext.dsc,
895
+ sampled: propagationContext.sampled,
896
+ });
897
+
898
+ const spanContext = {
899
+ traceId: propagationContext.traceId,
900
+ spanId: propagationContext.parentSpanId || '',
901
+ isRemote: true,
902
+ traceFlags: propagationContext.sampled ? api.TraceFlags.SAMPLED : api.TraceFlags.NONE,
903
+ traceState,
904
+ };
905
+
906
+ return spanContext;
907
+ }
908
+
891
909
  function _optionalChain$5(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
892
910
 
893
911
  /**
@@ -1068,6 +1086,7 @@ function getContext(scope, forceTransaction) {
1068
1086
 
1069
1087
  const spanOptions = {
1070
1088
  traceId: propagationContext.traceId,
1089
+ // eslint-disable-next-line deprecation/deprecation
1071
1090
  spanId: propagationContext.parentSpanId || propagationContext.spanId,
1072
1091
  isRemote: true,
1073
1092
  traceFlags: propagationContext.sampled ? api.TraceFlags.SAMPLED : api.TraceFlags.NONE,
@@ -1149,6 +1168,25 @@ function continueTrace(options, callback) {
1149
1168
  });
1150
1169
  }
1151
1170
 
1171
+ /**
1172
+ * Get the trace context for a given scope.
1173
+ * We have a custom implemention here because we need an OTEL-specific way to get the span from a scope.
1174
+ */
1175
+ function getTraceContextForScope(
1176
+ client,
1177
+ scope,
1178
+ ) {
1179
+ const ctx = getContextFromScope(scope);
1180
+ const span = ctx && api.trace.getSpan(ctx);
1181
+
1182
+ const traceContext = span ? core.spanToTraceContext(span) : core.getTraceContextFromScope(scope);
1183
+
1184
+ const dynamicSamplingContext = span
1185
+ ? core.getDynamicSamplingContextFromSpan(span)
1186
+ : core.getDynamicSamplingContextFromScope(client, scope);
1187
+ return [dynamicSamplingContext, traceContext];
1188
+ }
1189
+
1152
1190
  function getActiveSpanWrapper(parentSpan) {
1153
1191
  return parentSpan !== undefined
1154
1192
  ? (callback) => {
@@ -1164,6 +1202,7 @@ function suppressTracing(callback) {
1164
1202
  }
1165
1203
 
1166
1204
  function _optionalChain$4(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
1205
+
1167
1206
  /** Ensure the `trace` context is set on all events. */
1168
1207
  function setupEventContextTrace(client) {
1169
1208
  client.on('preprocessEvent', event => {
@@ -1211,19 +1250,21 @@ function setupEventContextTrace(client) {
1211
1250
  * Otel-specific implementation of `getTraceData`.
1212
1251
  * @see `@sentry/core` version of `getTraceData` for more information
1213
1252
  */
1214
- function getTraceData() {
1215
- const headersObject = {};
1216
-
1217
- api.propagation.inject(api.context.active(), headersObject);
1253
+ function getTraceData({ span } = {}) {
1254
+ let ctx = api.context.active();
1218
1255
 
1219
- if (!headersObject['sentry-trace']) {
1220
- return {};
1256
+ if (span) {
1257
+ const { scope } = core.getCapturedScopesOnSpan(span);
1258
+ // fall back to current context if for whatever reason we can't find the one of the span
1259
+ ctx = (scope && getContextFromScope(scope)) || api.trace.setSpan(api.context.active(), span);
1221
1260
  }
1222
1261
 
1223
- return core.dropUndefinedKeys({
1224
- 'sentry-trace': headersObject['sentry-trace'],
1225
- baggage: headersObject.baggage,
1226
- });
1262
+ const { traceId, spanId, sampled, dynamicSamplingContext } = getInjectionData(ctx);
1263
+
1264
+ return {
1265
+ 'sentry-trace': core.generateSentryTraceHeader(traceId, spanId, sampled),
1266
+ baggage: core.dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext),
1267
+ };
1227
1268
  }
1228
1269
 
1229
1270
  /**
@@ -1564,52 +1605,105 @@ const DEFAULT_TIMEOUT = 300; // 5 min
1564
1605
  */
1565
1606
  class SentrySpanExporter {
1566
1607
 
1567
- constructor(options) {
1568
- this._finishedSpans = [];
1569
- this._timeout = _optionalChain$2([options, 'optionalAccess', _ => _.timeout]) || DEFAULT_TIMEOUT;
1608
+ /*
1609
+ * A quick explanation on the buckets: We do bucketing of finished spans for efficiency. This span exporter is
1610
+ * accumulating spans until a root span is encountered and then it flushes all the spans that are descendants of that
1611
+ * root span. Because it is totally in the realm of possibilities that root spans are never finished, and we don't
1612
+ * want to accumulate spans indefinitely in memory, we need to periodically evacuate spans. Naively we could simply
1613
+ * store the spans in an array and each time a new span comes in we could iterate through the entire array and
1614
+ * evacuate all spans that have an end-timestamp that is older than our limit. This could get quite expensive because
1615
+ * we would have to iterate a potentially large number of spans every time we evacuate. We want to avoid these large
1616
+ * bursts of computation.
1617
+ *
1618
+ * Instead we go for a bucketing approach and put spans into buckets, based on what second
1619
+ * (modulo the time limit) the span was put into the exporter. With buckets, when we decide to evacuate, we can
1620
+ * iterate through the bucket entries instead, which have an upper bound of items, making the evacuation much more
1621
+ * efficient. Cleaning up also becomes much more efficient since it simply involves de-referencing a bucket within the
1622
+ * bucket array, and letting garbage collection take care of the rest.
1623
+ */
1624
+
1625
+ constructor(options
1626
+
1627
+ ) {
1628
+ this._finishedSpanBucketSize = _optionalChain$2([options, 'optionalAccess', _ => _.timeout]) || DEFAULT_TIMEOUT;
1629
+ this._finishedSpanBuckets = new Array(this._finishedSpanBucketSize).fill(undefined);
1630
+ this._lastCleanupTimestampInS = Math.floor(Date.now() / 1000);
1631
+ this._spansToBucketEntry = new WeakMap();
1570
1632
  }
1571
1633
 
1572
1634
  /** Export a single span. */
1573
1635
  export(span) {
1574
- this._finishedSpans.push(span);
1575
-
1576
- // If the span has a local parent ID, we don't need to export anything just yet
1577
- if (getLocalParentId(span)) {
1578
- const openSpanCount = this._finishedSpans.length;
1579
- DEBUG_BUILD && core.logger.log(`SpanExporter has ${openSpanCount} unsent spans remaining`);
1580
- this._cleanupOldSpans();
1581
- return;
1636
+ const currentTimestampInS = Math.floor(Date.now() / 1000);
1637
+
1638
+ if (this._lastCleanupTimestampInS !== currentTimestampInS) {
1639
+ let droppedSpanCount = 0;
1640
+ this._finishedSpanBuckets.forEach((bucket, i) => {
1641
+ if (bucket && bucket.timestampInS <= currentTimestampInS - this._finishedSpanBucketSize) {
1642
+ droppedSpanCount += bucket.spans.size;
1643
+ this._finishedSpanBuckets[i] = undefined;
1644
+ }
1645
+ });
1646
+ if (droppedSpanCount > 0) {
1647
+ DEBUG_BUILD &&
1648
+ core.logger.log(
1649
+ `SpanExporter dropped ${droppedSpanCount} spans because they were pending for more than ${this._finishedSpanBucketSize} seconds.`,
1650
+ );
1651
+ }
1652
+ this._lastCleanupTimestampInS = currentTimestampInS;
1582
1653
  }
1583
1654
 
1584
- this._clearTimeout();
1585
-
1586
- // If we got a parent span, we try to send the span tree
1587
- // Wait a tick for this, to ensure we avoid race conditions
1588
- this._flushTimeout = setTimeout(() => {
1589
- this.flush();
1590
- }, 1);
1655
+ const currentBucketIndex = currentTimestampInS % this._finishedSpanBucketSize;
1656
+ const currentBucket = this._finishedSpanBuckets[currentBucketIndex] || {
1657
+ timestampInS: currentTimestampInS,
1658
+ spans: new Set(),
1659
+ };
1660
+ this._finishedSpanBuckets[currentBucketIndex] = currentBucket;
1661
+ currentBucket.spans.add(span);
1662
+ this._spansToBucketEntry.set(span, currentBucket);
1663
+
1664
+ // If the span doesn't have a local parent ID (it's a root span), we're gonna flush all the ended spans
1665
+ if (!getLocalParentId(span)) {
1666
+ this._clearTimeout();
1667
+
1668
+ // If we got a parent span, we try to send the span tree
1669
+ // Wait a tick for this, to ensure we avoid race conditions
1670
+ this._flushTimeout = setTimeout(() => {
1671
+ this.flush();
1672
+ }, 1);
1673
+ }
1591
1674
  }
1592
1675
 
1593
1676
  /** Try to flush any pending spans immediately. */
1594
1677
  flush() {
1595
1678
  this._clearTimeout();
1596
1679
 
1597
- const openSpanCount = this._finishedSpans.length;
1680
+ const finishedSpans = [];
1681
+ this._finishedSpanBuckets.forEach(bucket => {
1682
+ if (bucket) {
1683
+ finishedSpans.push(...bucket.spans);
1684
+ }
1685
+ });
1686
+
1687
+ const sentSpans = maybeSend(finishedSpans);
1598
1688
 
1599
- const remainingSpans = maybeSend(this._finishedSpans);
1689
+ const sentSpanCount = sentSpans.size;
1600
1690
 
1601
- const remainingOpenSpanCount = remainingSpans.length;
1602
- const sentSpanCount = openSpanCount - remainingOpenSpanCount;
1691
+ const remainingOpenSpanCount = finishedSpans.length - sentSpanCount;
1603
1692
 
1604
1693
  DEBUG_BUILD &&
1605
1694
  core.logger.log(`SpanExporter exported ${sentSpanCount} spans, ${remainingOpenSpanCount} unsent spans remaining`);
1606
1695
 
1607
- this._cleanupOldSpans(remainingSpans);
1696
+ sentSpans.forEach(span => {
1697
+ const bucketEntry = this._spansToBucketEntry.get(span);
1698
+ if (bucketEntry) {
1699
+ bucketEntry.spans.delete(span);
1700
+ }
1701
+ });
1608
1702
  }
1609
1703
 
1610
1704
  /** Clear the exporter. */
1611
1705
  clear() {
1612
- this._finishedSpans = [];
1706
+ this._finishedSpanBuckets = this._finishedSpanBuckets.fill(undefined);
1613
1707
  this._clearTimeout();
1614
1708
  }
1615
1709
 
@@ -1620,31 +1714,12 @@ class SentrySpanExporter {
1620
1714
  this._flushTimeout = undefined;
1621
1715
  }
1622
1716
  }
1623
-
1624
- /**
1625
- * Remove any span that is older than 5min.
1626
- * We do this to avoid leaking memory.
1627
- */
1628
- _cleanupOldSpans(spans = this._finishedSpans) {
1629
- const currentTimeSeconds = Date.now() / 1000;
1630
- this._finishedSpans = spans.filter(span => {
1631
- const shouldDrop = shouldCleanupSpan(span, currentTimeSeconds, this._timeout);
1632
- DEBUG_BUILD &&
1633
- shouldDrop &&
1634
- core.logger.log(
1635
- `SpanExporter dropping span ${span.name} (${
1636
- span.spanContext().spanId
1637
- }) because it is pending for more than 5 minutes.`,
1638
- );
1639
- return !shouldDrop;
1640
- });
1641
- }
1642
1717
  }
1643
1718
 
1644
1719
  /**
1645
1720
  * Send the given spans, but only if they are part of a finished transaction.
1646
1721
  *
1647
- * Returns the unsent spans.
1722
+ * Returns the sent spans.
1648
1723
  * Spans remain unsent when their parent span is not yet finished.
1649
1724
  * This will happen regularly, as child spans are generally finished before their parents.
1650
1725
  * But it _could_ also happen because, for whatever reason, a parent span was lost.
@@ -1652,20 +1727,20 @@ class SentrySpanExporter {
1652
1727
  */
1653
1728
  function maybeSend(spans) {
1654
1729
  const grouped = groupSpansWithParents(spans);
1655
- const remaining = new Set(grouped);
1730
+ const sentSpans = new Set();
1656
1731
 
1657
1732
  const rootNodes = getCompletedRootNodes(grouped);
1658
1733
 
1659
1734
  rootNodes.forEach(root => {
1660
- remaining.delete(root);
1661
1735
  const span = root.span;
1736
+ sentSpans.add(span);
1662
1737
  const transactionEvent = createTransactionForOtelSpan(span);
1663
1738
 
1664
1739
  // We'll recursively add all the child spans to this array
1665
1740
  const spans = transactionEvent.spans || [];
1666
1741
 
1667
1742
  root.children.forEach(child => {
1668
- createAndFinishSpanForOtelSpan(child, spans, remaining);
1743
+ createAndFinishSpanForOtelSpan(child, spans, sentSpans);
1669
1744
  });
1670
1745
 
1671
1746
  // spans.sort() mutates the array, but we do not use this anymore after this point
@@ -1683,9 +1758,7 @@ function maybeSend(spans) {
1683
1758
  core.captureEvent(transactionEvent);
1684
1759
  });
1685
1760
 
1686
- return Array.from(remaining)
1687
- .map(node => node.span)
1688
- .filter((span) => !!span);
1761
+ return sentSpans;
1689
1762
  }
1690
1763
 
1691
1764
  function nodeIsCompletedRootNode(node) {
@@ -1696,11 +1769,6 @@ function getCompletedRootNodes(nodes) {
1696
1769
  return nodes.filter(nodeIsCompletedRootNode);
1697
1770
  }
1698
1771
 
1699
- function shouldCleanupSpan(span, currentTimeSeconds, maxStartTimeOffsetSeconds) {
1700
- const cutoff = currentTimeSeconds - maxStartTimeOffsetSeconds;
1701
- return core.spanTimeInputToSeconds(span.startTime) < cutoff;
1702
- }
1703
-
1704
1772
  function parseSpan(span) {
1705
1773
  const attributes = span.attributes;
1706
1774
 
@@ -1781,16 +1849,19 @@ function createTransactionForOtelSpan(span) {
1781
1849
  return transactionEvent;
1782
1850
  }
1783
1851
 
1784
- function createAndFinishSpanForOtelSpan(node, spans, remaining) {
1785
- remaining.delete(node);
1852
+ function createAndFinishSpanForOtelSpan(node, spans, sentSpans) {
1786
1853
  const span = node.span;
1787
1854
 
1855
+ if (span) {
1856
+ sentSpans.add(span);
1857
+ }
1858
+
1788
1859
  const shouldDrop = !span;
1789
1860
 
1790
1861
  // If this span should be dropped, we still want to create spans for the children of this
1791
1862
  if (shouldDrop) {
1792
1863
  node.children.forEach(child => {
1793
- createAndFinishSpanForOtelSpan(child, spans, remaining);
1864
+ createAndFinishSpanForOtelSpan(child, spans, sentSpans);
1794
1865
  });
1795
1866
  return;
1796
1867
  }
@@ -1829,7 +1900,7 @@ function createAndFinishSpanForOtelSpan(node, spans, remaining) {
1829
1900
  spans.push(spanJSON);
1830
1901
 
1831
1902
  node.children.forEach(child => {
1832
- createAndFinishSpanForOtelSpan(child, spans, remaining);
1903
+ createAndFinishSpanForOtelSpan(child, spans, sentSpans);
1833
1904
  });
1834
1905
  }
1835
1906
 
@@ -2004,7 +2075,7 @@ class SentrySampler {
2004
2075
  ) {
2005
2076
  const options = this._client.getOptions();
2006
2077
 
2007
- const parentSpan = api.trace.getSpan(context);
2078
+ const parentSpan = getValidSpan(context);
2008
2079
  const parentContext = _optionalChain([parentSpan, 'optionalAccess', _ => _.spanContext, 'call', _2 => _2()]);
2009
2080
 
2010
2081
  if (!core.hasTracingEnabled(options)) {
@@ -2167,9 +2238,21 @@ function getBaseTraceState(context, spanAttributes) {
2167
2238
  return traceState;
2168
2239
  }
2169
2240
 
2241
+ /**
2242
+ * If the active span is invalid, we want to ignore it as parent.
2243
+ * This aligns with how otel tracers and default samplers handle these cases.
2244
+ */
2245
+ function getValidSpan(context) {
2246
+ const span = api.trace.getSpan(context);
2247
+ return span && api.isSpanContextValid(span.spanContext()) ? span : undefined;
2248
+ }
2249
+
2170
2250
  /**
2171
2251
  * This method takes an OpenTelemetry instrumentation or
2172
2252
  * array of instrumentations and registers them with OpenTelemetry.
2253
+ *
2254
+ * @deprecated This method will be removed in the next major version of the SDK.
2255
+ * Use the `openTelemetryInstrumentations` option in `Sentry.init()` or your custom Sentry Client instead.
2173
2256
  */
2174
2257
  function addOpenTelemetryInstrumentation(...instrumentations) {
2175
2258
  instrumentation.registerInstrumentations({
@@ -2187,16 +2270,18 @@ exports.SentrySpanProcessor = SentrySpanProcessor;
2187
2270
  exports.addOpenTelemetryInstrumentation = addOpenTelemetryInstrumentation;
2188
2271
  exports.continueTrace = continueTrace;
2189
2272
  exports.enhanceDscWithOpenTelemetryRootSpanName = enhanceDscWithOpenTelemetryRootSpanName;
2190
- exports.generateSpanContextForPropagationContext = generateSpanContextForPropagationContext;
2273
+ exports.generateSpanContextForPropagationContext = generateSpanContextForPropagationContext$1;
2191
2274
  exports.getActiveSpan = getActiveSpan;
2192
2275
  exports.getPropagationContextFromSpan = getPropagationContextFromSpan;
2193
2276
  exports.getRequestSpanData = getRequestSpanData;
2194
2277
  exports.getScopesFromContext = getScopesFromContext;
2195
2278
  exports.getSpanKind = getSpanKind;
2279
+ exports.getTraceContextForScope = getTraceContextForScope;
2196
2280
  exports.isSentryRequestSpan = isSentryRequestSpan;
2197
2281
  exports.openTelemetrySetupCheck = openTelemetrySetupCheck;
2198
2282
  exports.setOpenTelemetryContextAsyncContextStrategy = setOpenTelemetryContextAsyncContextStrategy;
2199
2283
  exports.setupEventContextTrace = setupEventContextTrace;
2284
+ exports.shouldPropagateTraceForUrl = shouldPropagateTraceForUrl;
2200
2285
  exports.spanHasAttributes = spanHasAttributes;
2201
2286
  exports.spanHasEvents = spanHasEvents;
2202
2287
  exports.spanHasKind = spanHasKind;