@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
@@ -1,6 +1,6 @@
1
1
  import { _optionalChain } from '@sentry/core';
2
2
  import { ATTR_URL_FULL, SEMATTRS_HTTP_URL, ATTR_HTTP_REQUEST_METHOD, SEMATTRS_HTTP_METHOD, 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';
3
- import { parseUrl, getSanitizedUrlString, SDK_VERSION, addNonEnumerableProperty, isSentryRequestUrl, getClient, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, stripUrlQueryAndFragment, spanToJSON, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, dynamicSamplingContextToSentryBaggageHeader, baggageHeaderToDynamicSamplingContext, getDynamicSamplingContextFromSpan, getRootSpan, LRUMap, logger, parseBaggageHeader, SENTRY_BAGGAGE_KEY_PREFIX, generateSentryTraceHeader, propagationContextFromHeaders, getCurrentScope, getIsolationScope, stringMatchesSomePattern, getDynamicSamplingContextFromClient, handleCallbackErrors, continueTrace as continueTrace$1, dropUndefinedKeys, setAsyncContextStrategy, getDefaultCurrentScope, getDefaultIsolationScope, SPAN_STATUS_OK, SPAN_STATUS_ERROR, getSpanStatusFromHttpCode, timedEventsToMeasurements, captureEvent, spanTimeInputToSeconds, getCapturedScopesOnSpan, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, getStatusMessage, getMetricSummaryJsonForSpan, addChildSpanToSpan, setCapturedScopesOnSpan, logSpanStart, logSpanEnd, hasTracingEnabled, sampleSpan } from '@sentry/core';
3
+ import { parseUrl, getSanitizedUrlString, SDK_VERSION, addNonEnumerableProperty, isSentryRequestUrl, getClient, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, stripUrlQueryAndFragment, spanToJSON, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, dynamicSamplingContextToSentryBaggageHeader, baggageHeaderToDynamicSamplingContext, getDynamicSamplingContextFromSpan, getRootSpan, LRUMap, logger, parseBaggageHeader, SENTRY_BAGGAGE_KEY_PREFIX, generateSentryTraceHeader, propagationContextFromHeaders, getCurrentScope, getIsolationScope, stringMatchesSomePattern, getDynamicSamplingContextFromScope, handleCallbackErrors, continueTrace as continueTrace$1, spanToTraceContext, getTraceContextFromScope, dropUndefinedKeys, getCapturedScopesOnSpan, setAsyncContextStrategy, getDefaultCurrentScope, getDefaultIsolationScope, SPAN_STATUS_OK, SPAN_STATUS_ERROR, getSpanStatusFromHttpCode, timedEventsToMeasurements, captureEvent, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, getStatusMessage, spanTimeInputToSeconds, getMetricSummaryJsonForSpan, addChildSpanToSpan, setCapturedScopesOnSpan, logSpanStart, logSpanEnd, hasTracingEnabled, sampleSpan } from '@sentry/core';
4
4
  export { getClient, getCurrentHubShim, getDynamicSamplingContextFromSpan } from '@sentry/core';
5
5
  import * as api from '@opentelemetry/api';
6
6
  import { trace, SpanKind, createContextKey, TraceFlags, propagation, INVALID_TRACEID, context, SpanStatusCode, INVALID_SPANID, ROOT_CONTEXT, isSpanContextValid } from '@opentelemetry/api';
@@ -532,8 +532,10 @@ function makeTraceState({
532
532
  /**
533
533
  * Generates a SpanContext that represents a PropagationContext.
534
534
  * This can be set on a `context` to make this a (virtual) active span.
535
+ *
536
+ * @deprecated This function is deprecated and will be removed in the next major version.
535
537
  */
536
- function generateSpanContextForPropagationContext(propagationContext) {
538
+ function generateSpanContextForPropagationContext$1(propagationContext) {
537
539
  // We store the DSC as OTEL trace state on the span context
538
540
  const traceState = makeTraceState({
539
541
  parentSpanId: propagationContext.parentSpanId,
@@ -543,6 +545,7 @@ function generateSpanContextForPropagationContext(propagationContext) {
543
545
 
544
546
  const spanContext = {
545
547
  traceId: propagationContext.traceId,
548
+ // TODO: Do not create an invalid span context here
546
549
  spanId: propagationContext.parentSpanId || '',
547
550
  isRemote: true,
548
551
  traceFlags: propagationContext.sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,
@@ -673,11 +676,7 @@ class SentryPropagator extends W3CBaggagePropagator {
673
676
  const url = activeSpan && getCurrentURL(activeSpan);
674
677
 
675
678
  const tracePropagationTargets = _optionalChain$6([getClient, 'call', _ => _(), 'optionalAccess', _2 => _2.getOptions, 'call', _3 => _3(), 'optionalAccess', _4 => _4.tracePropagationTargets]);
676
- if (
677
- typeof url === 'string' &&
678
- tracePropagationTargets &&
679
- !this._shouldInjectTraceData(tracePropagationTargets, url)
680
- ) {
679
+ if (!shouldPropagateTraceForUrl(url, tracePropagationTargets, this._urlMatchesTargetsMap)) {
681
680
  DEBUG_BUILD &&
682
681
  logger.log(
683
682
  '[Tracing] Not injecting trace data for url because it does not match tracePropagationTargets:',
@@ -753,36 +752,52 @@ class SentryPropagator extends W3CBaggagePropagator {
753
752
  fields() {
754
753
  return [SENTRY_TRACE_HEADER, SENTRY_BAGGAGE_HEADER];
755
754
  }
755
+ }
756
756
 
757
- /** If we want to inject trace data for a given URL. */
758
- _shouldInjectTraceData(tracePropagationTargets, url) {
759
- if (tracePropagationTargets === undefined) {
760
- return true;
761
- }
757
+ const NOT_PROPAGATED_MESSAGE =
758
+ '[Tracing] Not injecting trace data for url because it does not match tracePropagationTargets:';
762
759
 
763
- const cachedDecision = this._urlMatchesTargetsMap.get(url);
764
- if (cachedDecision !== undefined) {
765
- return cachedDecision;
766
- }
760
+ /**
761
+ * Check if a given URL should be propagated to or not.
762
+ * If no url is defined, or no trace propagation targets are defined, this will always return `true`.
763
+ * You can also optionally provide a decision map, to cache decisions and avoid repeated regex lookups.
764
+ */
765
+ function shouldPropagateTraceForUrl(
766
+ url,
767
+ tracePropagationTargets,
768
+ decisionMap,
769
+ ) {
770
+ if (typeof url !== 'string' || !tracePropagationTargets) {
771
+ return true;
772
+ }
767
773
 
768
- const decision = stringMatchesSomePattern(url, tracePropagationTargets);
769
- this._urlMatchesTargetsMap.set(url, decision);
770
- return decision;
774
+ const cachedDecision = _optionalChain$6([decisionMap, 'optionalAccess', _5 => _5.get, 'call', _6 => _6(url)]);
775
+ if (cachedDecision !== undefined) {
776
+ DEBUG_BUILD && !cachedDecision && logger.log(NOT_PROPAGATED_MESSAGE, url);
777
+ return cachedDecision;
771
778
  }
779
+
780
+ const decision = stringMatchesSomePattern(url, tracePropagationTargets);
781
+ _optionalChain$6([decisionMap, 'optionalAccess', _7 => _7.set, 'call', _8 => _8(url, decision)]);
782
+
783
+ DEBUG_BUILD && !decision && logger.log(NOT_PROPAGATED_MESSAGE, url);
784
+ return decision;
772
785
  }
773
786
 
787
+ /**
788
+ * Get propagation injection data for the given context.
789
+ */
774
790
  function getInjectionData(context)
775
791
 
776
792
  {
777
793
  const span = trace.getSpan(context);
778
- const spanIsRemote = _optionalChain$6([span, 'optionalAccess', _5 => _5.spanContext, 'call', _6 => _6(), 'access', _7 => _7.isRemote]);
794
+ const spanIsRemote = _optionalChain$6([span, 'optionalAccess', _9 => _9.spanContext, 'call', _10 => _10(), 'access', _11 => _11.isRemote]);
779
795
 
780
796
  // If we have a local span, we can just pick everything from it
781
797
  if (span && !spanIsRemote) {
782
798
  const spanContext = span.spanContext();
783
799
 
784
- const propagationContext = getPropagationContextFromSpan(span);
785
- const dynamicSamplingContext = getDynamicSamplingContext(propagationContext, spanContext.traceId);
800
+ const dynamicSamplingContext = getDynamicSamplingContextFromSpan(span);
786
801
  return {
787
802
  dynamicSamplingContext,
788
803
  traceId: spanContext.traceId,
@@ -792,38 +807,21 @@ function getInjectionData(context)
792
807
  }
793
808
 
794
809
  // Else we try to use the propagation context from the scope
795
- const scope = _optionalChain$6([getScopesFromContext, 'call', _8 => _8(context), 'optionalAccess', _9 => _9.scope]) || getCurrentScope();
810
+ const scope = _optionalChain$6([getScopesFromContext, 'call', _12 => _12(context), 'optionalAccess', _13 => _13.scope]) || getCurrentScope();
811
+ const client = getClient();
796
812
 
797
813
  const propagationContext = scope.getPropagationContext();
798
- const dynamicSamplingContext = getDynamicSamplingContext(propagationContext, propagationContext.traceId);
814
+ const dynamicSamplingContext = client ? getDynamicSamplingContextFromScope(client, scope) : undefined;
799
815
  return {
800
816
  dynamicSamplingContext,
801
817
  traceId: propagationContext.traceId,
818
+ // TODO(v9): Use generateSpanId() instead
819
+ // eslint-disable-next-line deprecation/deprecation
802
820
  spanId: propagationContext.spanId,
803
821
  sampled: propagationContext.sampled,
804
822
  };
805
823
  }
806
824
 
807
- /** Get the DSC from a context, or fall back to use the one from the client. */
808
- function getDynamicSamplingContext(
809
- propagationContext,
810
- traceId,
811
- ) {
812
- // If we have a DSC on the propagation context, we just use it
813
- if (_optionalChain$6([propagationContext, 'optionalAccess', _10 => _10.dsc])) {
814
- return propagationContext.dsc;
815
- }
816
-
817
- // Else, we try to generate a new one
818
- const client = getClient();
819
-
820
- if (client) {
821
- return getDynamicSamplingContextFromClient(traceId || propagationContext.traceId, client);
822
- }
823
-
824
- return undefined;
825
- }
826
-
827
825
  function getContextWithRemoteActiveSpan(
828
826
  ctx,
829
827
  { sentryTrace, baggage },
@@ -871,13 +869,13 @@ function getCurrentURL(span) {
871
869
  const spanData = spanToJSON(span).data;
872
870
  // `ATTR_URL_FULL` is the new attribute, but we still support the old one, `SEMATTRS_HTTP_URL`, for now.
873
871
  // eslint-disable-next-line deprecation/deprecation
874
- const urlAttribute = _optionalChain$6([spanData, 'optionalAccess', _11 => _11[SEMATTRS_HTTP_URL]]) || _optionalChain$6([spanData, 'optionalAccess', _12 => _12[ATTR_URL_FULL]]);
872
+ const urlAttribute = _optionalChain$6([spanData, 'optionalAccess', _14 => _14[SEMATTRS_HTTP_URL]]) || _optionalChain$6([spanData, 'optionalAccess', _15 => _15[ATTR_URL_FULL]]);
875
873
  if (urlAttribute) {
876
874
  return urlAttribute;
877
875
  }
878
876
 
879
877
  // Also look at the traceState, which we may set in the sampler even for unsampled spans
880
- 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)]);
878
+ 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)]);
881
879
  if (urlTraceState) {
882
880
  return urlTraceState;
883
881
  }
@@ -885,6 +883,26 @@ function getCurrentURL(span) {
885
883
  return undefined;
886
884
  }
887
885
 
886
+ // TODO: Adjust this behavior to avoid invalid spans
887
+ function generateSpanContextForPropagationContext(propagationContext) {
888
+ // We store the DSC as OTEL trace state on the span context
889
+ const traceState = makeTraceState({
890
+ parentSpanId: propagationContext.parentSpanId,
891
+ dsc: propagationContext.dsc,
892
+ sampled: propagationContext.sampled,
893
+ });
894
+
895
+ const spanContext = {
896
+ traceId: propagationContext.traceId,
897
+ spanId: propagationContext.parentSpanId || '',
898
+ isRemote: true,
899
+ traceFlags: propagationContext.sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,
900
+ traceState,
901
+ };
902
+
903
+ return spanContext;
904
+ }
905
+
888
906
  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; }
889
907
 
890
908
  /**
@@ -1065,6 +1083,7 @@ function getContext(scope, forceTransaction) {
1065
1083
 
1066
1084
  const spanOptions = {
1067
1085
  traceId: propagationContext.traceId,
1086
+ // eslint-disable-next-line deprecation/deprecation
1068
1087
  spanId: propagationContext.parentSpanId || propagationContext.spanId,
1069
1088
  isRemote: true,
1070
1089
  traceFlags: propagationContext.sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,
@@ -1146,6 +1165,25 @@ function continueTrace(options, callback) {
1146
1165
  });
1147
1166
  }
1148
1167
 
1168
+ /**
1169
+ * Get the trace context for a given scope.
1170
+ * We have a custom implemention here because we need an OTEL-specific way to get the span from a scope.
1171
+ */
1172
+ function getTraceContextForScope(
1173
+ client,
1174
+ scope,
1175
+ ) {
1176
+ const ctx = getContextFromScope(scope);
1177
+ const span = ctx && trace.getSpan(ctx);
1178
+
1179
+ const traceContext = span ? spanToTraceContext(span) : getTraceContextFromScope(scope);
1180
+
1181
+ const dynamicSamplingContext = span
1182
+ ? getDynamicSamplingContextFromSpan(span)
1183
+ : getDynamicSamplingContextFromScope(client, scope);
1184
+ return [dynamicSamplingContext, traceContext];
1185
+ }
1186
+
1149
1187
  function getActiveSpanWrapper(parentSpan) {
1150
1188
  return parentSpan !== undefined
1151
1189
  ? (callback) => {
@@ -1161,6 +1199,7 @@ function suppressTracing(callback) {
1161
1199
  }
1162
1200
 
1163
1201
  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; }
1202
+
1164
1203
  /** Ensure the `trace` context is set on all events. */
1165
1204
  function setupEventContextTrace(client) {
1166
1205
  client.on('preprocessEvent', event => {
@@ -1208,19 +1247,21 @@ function setupEventContextTrace(client) {
1208
1247
  * Otel-specific implementation of `getTraceData`.
1209
1248
  * @see `@sentry/core` version of `getTraceData` for more information
1210
1249
  */
1211
- function getTraceData() {
1212
- const headersObject = {};
1213
-
1214
- api.propagation.inject(api.context.active(), headersObject);
1250
+ function getTraceData({ span } = {}) {
1251
+ let ctx = api.context.active();
1215
1252
 
1216
- if (!headersObject['sentry-trace']) {
1217
- return {};
1253
+ if (span) {
1254
+ const { scope } = getCapturedScopesOnSpan(span);
1255
+ // fall back to current context if for whatever reason we can't find the one of the span
1256
+ ctx = (scope && getContextFromScope(scope)) || api.trace.setSpan(api.context.active(), span);
1218
1257
  }
1219
1258
 
1220
- return dropUndefinedKeys({
1221
- 'sentry-trace': headersObject['sentry-trace'],
1222
- baggage: headersObject.baggage,
1223
- });
1259
+ const { traceId, spanId, sampled, dynamicSamplingContext } = getInjectionData(ctx);
1260
+
1261
+ return {
1262
+ 'sentry-trace': generateSentryTraceHeader(traceId, spanId, sampled),
1263
+ baggage: dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext),
1264
+ };
1224
1265
  }
1225
1266
 
1226
1267
  /**
@@ -1561,52 +1602,105 @@ const DEFAULT_TIMEOUT = 300; // 5 min
1561
1602
  */
1562
1603
  class SentrySpanExporter {
1563
1604
 
1564
- constructor(options) {
1565
- this._finishedSpans = [];
1566
- this._timeout = _optionalChain$2([options, 'optionalAccess', _ => _.timeout]) || DEFAULT_TIMEOUT;
1605
+ /*
1606
+ * A quick explanation on the buckets: We do bucketing of finished spans for efficiency. This span exporter is
1607
+ * accumulating spans until a root span is encountered and then it flushes all the spans that are descendants of that
1608
+ * root span. Because it is totally in the realm of possibilities that root spans are never finished, and we don't
1609
+ * want to accumulate spans indefinitely in memory, we need to periodically evacuate spans. Naively we could simply
1610
+ * store the spans in an array and each time a new span comes in we could iterate through the entire array and
1611
+ * evacuate all spans that have an end-timestamp that is older than our limit. This could get quite expensive because
1612
+ * we would have to iterate a potentially large number of spans every time we evacuate. We want to avoid these large
1613
+ * bursts of computation.
1614
+ *
1615
+ * Instead we go for a bucketing approach and put spans into buckets, based on what second
1616
+ * (modulo the time limit) the span was put into the exporter. With buckets, when we decide to evacuate, we can
1617
+ * iterate through the bucket entries instead, which have an upper bound of items, making the evacuation much more
1618
+ * efficient. Cleaning up also becomes much more efficient since it simply involves de-referencing a bucket within the
1619
+ * bucket array, and letting garbage collection take care of the rest.
1620
+ */
1621
+
1622
+ constructor(options
1623
+
1624
+ ) {
1625
+ this._finishedSpanBucketSize = _optionalChain$2([options, 'optionalAccess', _ => _.timeout]) || DEFAULT_TIMEOUT;
1626
+ this._finishedSpanBuckets = new Array(this._finishedSpanBucketSize).fill(undefined);
1627
+ this._lastCleanupTimestampInS = Math.floor(Date.now() / 1000);
1628
+ this._spansToBucketEntry = new WeakMap();
1567
1629
  }
1568
1630
 
1569
1631
  /** Export a single span. */
1570
1632
  export(span) {
1571
- this._finishedSpans.push(span);
1572
-
1573
- // If the span has a local parent ID, we don't need to export anything just yet
1574
- if (getLocalParentId(span)) {
1575
- const openSpanCount = this._finishedSpans.length;
1576
- DEBUG_BUILD && logger.log(`SpanExporter has ${openSpanCount} unsent spans remaining`);
1577
- this._cleanupOldSpans();
1578
- return;
1633
+ const currentTimestampInS = Math.floor(Date.now() / 1000);
1634
+
1635
+ if (this._lastCleanupTimestampInS !== currentTimestampInS) {
1636
+ let droppedSpanCount = 0;
1637
+ this._finishedSpanBuckets.forEach((bucket, i) => {
1638
+ if (bucket && bucket.timestampInS <= currentTimestampInS - this._finishedSpanBucketSize) {
1639
+ droppedSpanCount += bucket.spans.size;
1640
+ this._finishedSpanBuckets[i] = undefined;
1641
+ }
1642
+ });
1643
+ if (droppedSpanCount > 0) {
1644
+ DEBUG_BUILD &&
1645
+ logger.log(
1646
+ `SpanExporter dropped ${droppedSpanCount} spans because they were pending for more than ${this._finishedSpanBucketSize} seconds.`,
1647
+ );
1648
+ }
1649
+ this._lastCleanupTimestampInS = currentTimestampInS;
1579
1650
  }
1580
1651
 
1581
- this._clearTimeout();
1582
-
1583
- // If we got a parent span, we try to send the span tree
1584
- // Wait a tick for this, to ensure we avoid race conditions
1585
- this._flushTimeout = setTimeout(() => {
1586
- this.flush();
1587
- }, 1);
1652
+ const currentBucketIndex = currentTimestampInS % this._finishedSpanBucketSize;
1653
+ const currentBucket = this._finishedSpanBuckets[currentBucketIndex] || {
1654
+ timestampInS: currentTimestampInS,
1655
+ spans: new Set(),
1656
+ };
1657
+ this._finishedSpanBuckets[currentBucketIndex] = currentBucket;
1658
+ currentBucket.spans.add(span);
1659
+ this._spansToBucketEntry.set(span, currentBucket);
1660
+
1661
+ // If the span doesn't have a local parent ID (it's a root span), we're gonna flush all the ended spans
1662
+ if (!getLocalParentId(span)) {
1663
+ this._clearTimeout();
1664
+
1665
+ // If we got a parent span, we try to send the span tree
1666
+ // Wait a tick for this, to ensure we avoid race conditions
1667
+ this._flushTimeout = setTimeout(() => {
1668
+ this.flush();
1669
+ }, 1);
1670
+ }
1588
1671
  }
1589
1672
 
1590
1673
  /** Try to flush any pending spans immediately. */
1591
1674
  flush() {
1592
1675
  this._clearTimeout();
1593
1676
 
1594
- const openSpanCount = this._finishedSpans.length;
1677
+ const finishedSpans = [];
1678
+ this._finishedSpanBuckets.forEach(bucket => {
1679
+ if (bucket) {
1680
+ finishedSpans.push(...bucket.spans);
1681
+ }
1682
+ });
1683
+
1684
+ const sentSpans = maybeSend(finishedSpans);
1595
1685
 
1596
- const remainingSpans = maybeSend(this._finishedSpans);
1686
+ const sentSpanCount = sentSpans.size;
1597
1687
 
1598
- const remainingOpenSpanCount = remainingSpans.length;
1599
- const sentSpanCount = openSpanCount - remainingOpenSpanCount;
1688
+ const remainingOpenSpanCount = finishedSpans.length - sentSpanCount;
1600
1689
 
1601
1690
  DEBUG_BUILD &&
1602
1691
  logger.log(`SpanExporter exported ${sentSpanCount} spans, ${remainingOpenSpanCount} unsent spans remaining`);
1603
1692
 
1604
- this._cleanupOldSpans(remainingSpans);
1693
+ sentSpans.forEach(span => {
1694
+ const bucketEntry = this._spansToBucketEntry.get(span);
1695
+ if (bucketEntry) {
1696
+ bucketEntry.spans.delete(span);
1697
+ }
1698
+ });
1605
1699
  }
1606
1700
 
1607
1701
  /** Clear the exporter. */
1608
1702
  clear() {
1609
- this._finishedSpans = [];
1703
+ this._finishedSpanBuckets = this._finishedSpanBuckets.fill(undefined);
1610
1704
  this._clearTimeout();
1611
1705
  }
1612
1706
 
@@ -1617,31 +1711,12 @@ class SentrySpanExporter {
1617
1711
  this._flushTimeout = undefined;
1618
1712
  }
1619
1713
  }
1620
-
1621
- /**
1622
- * Remove any span that is older than 5min.
1623
- * We do this to avoid leaking memory.
1624
- */
1625
- _cleanupOldSpans(spans = this._finishedSpans) {
1626
- const currentTimeSeconds = Date.now() / 1000;
1627
- this._finishedSpans = spans.filter(span => {
1628
- const shouldDrop = shouldCleanupSpan(span, currentTimeSeconds, this._timeout);
1629
- DEBUG_BUILD &&
1630
- shouldDrop &&
1631
- logger.log(
1632
- `SpanExporter dropping span ${span.name} (${
1633
- span.spanContext().spanId
1634
- }) because it is pending for more than 5 minutes.`,
1635
- );
1636
- return !shouldDrop;
1637
- });
1638
- }
1639
1714
  }
1640
1715
 
1641
1716
  /**
1642
1717
  * Send the given spans, but only if they are part of a finished transaction.
1643
1718
  *
1644
- * Returns the unsent spans.
1719
+ * Returns the sent spans.
1645
1720
  * Spans remain unsent when their parent span is not yet finished.
1646
1721
  * This will happen regularly, as child spans are generally finished before their parents.
1647
1722
  * But it _could_ also happen because, for whatever reason, a parent span was lost.
@@ -1649,20 +1724,20 @@ class SentrySpanExporter {
1649
1724
  */
1650
1725
  function maybeSend(spans) {
1651
1726
  const grouped = groupSpansWithParents(spans);
1652
- const remaining = new Set(grouped);
1727
+ const sentSpans = new Set();
1653
1728
 
1654
1729
  const rootNodes = getCompletedRootNodes(grouped);
1655
1730
 
1656
1731
  rootNodes.forEach(root => {
1657
- remaining.delete(root);
1658
1732
  const span = root.span;
1733
+ sentSpans.add(span);
1659
1734
  const transactionEvent = createTransactionForOtelSpan(span);
1660
1735
 
1661
1736
  // We'll recursively add all the child spans to this array
1662
1737
  const spans = transactionEvent.spans || [];
1663
1738
 
1664
1739
  root.children.forEach(child => {
1665
- createAndFinishSpanForOtelSpan(child, spans, remaining);
1740
+ createAndFinishSpanForOtelSpan(child, spans, sentSpans);
1666
1741
  });
1667
1742
 
1668
1743
  // spans.sort() mutates the array, but we do not use this anymore after this point
@@ -1680,9 +1755,7 @@ function maybeSend(spans) {
1680
1755
  captureEvent(transactionEvent);
1681
1756
  });
1682
1757
 
1683
- return Array.from(remaining)
1684
- .map(node => node.span)
1685
- .filter((span) => !!span);
1758
+ return sentSpans;
1686
1759
  }
1687
1760
 
1688
1761
  function nodeIsCompletedRootNode(node) {
@@ -1693,11 +1766,6 @@ function getCompletedRootNodes(nodes) {
1693
1766
  return nodes.filter(nodeIsCompletedRootNode);
1694
1767
  }
1695
1768
 
1696
- function shouldCleanupSpan(span, currentTimeSeconds, maxStartTimeOffsetSeconds) {
1697
- const cutoff = currentTimeSeconds - maxStartTimeOffsetSeconds;
1698
- return spanTimeInputToSeconds(span.startTime) < cutoff;
1699
- }
1700
-
1701
1769
  function parseSpan(span) {
1702
1770
  const attributes = span.attributes;
1703
1771
 
@@ -1778,16 +1846,19 @@ function createTransactionForOtelSpan(span) {
1778
1846
  return transactionEvent;
1779
1847
  }
1780
1848
 
1781
- function createAndFinishSpanForOtelSpan(node, spans, remaining) {
1782
- remaining.delete(node);
1849
+ function createAndFinishSpanForOtelSpan(node, spans, sentSpans) {
1783
1850
  const span = node.span;
1784
1851
 
1852
+ if (span) {
1853
+ sentSpans.add(span);
1854
+ }
1855
+
1785
1856
  const shouldDrop = !span;
1786
1857
 
1787
1858
  // If this span should be dropped, we still want to create spans for the children of this
1788
1859
  if (shouldDrop) {
1789
1860
  node.children.forEach(child => {
1790
- createAndFinishSpanForOtelSpan(child, spans, remaining);
1861
+ createAndFinishSpanForOtelSpan(child, spans, sentSpans);
1791
1862
  });
1792
1863
  return;
1793
1864
  }
@@ -1826,7 +1897,7 @@ function createAndFinishSpanForOtelSpan(node, spans, remaining) {
1826
1897
  spans.push(spanJSON);
1827
1898
 
1828
1899
  node.children.forEach(child => {
1829
- createAndFinishSpanForOtelSpan(child, spans, remaining);
1900
+ createAndFinishSpanForOtelSpan(child, spans, sentSpans);
1830
1901
  });
1831
1902
  }
1832
1903
 
@@ -2001,7 +2072,7 @@ class SentrySampler {
2001
2072
  ) {
2002
2073
  const options = this._client.getOptions();
2003
2074
 
2004
- const parentSpan = trace.getSpan(context);
2075
+ const parentSpan = getValidSpan(context);
2005
2076
  const parentContext = _optionalChain([parentSpan, 'optionalAccess', _ => _.spanContext, 'call', _2 => _2()]);
2006
2077
 
2007
2078
  if (!hasTracingEnabled(options)) {
@@ -2164,9 +2235,21 @@ function getBaseTraceState(context, spanAttributes) {
2164
2235
  return traceState;
2165
2236
  }
2166
2237
 
2238
+ /**
2239
+ * If the active span is invalid, we want to ignore it as parent.
2240
+ * This aligns with how otel tracers and default samplers handle these cases.
2241
+ */
2242
+ function getValidSpan(context) {
2243
+ const span = trace.getSpan(context);
2244
+ return span && isSpanContextValid(span.spanContext()) ? span : undefined;
2245
+ }
2246
+
2167
2247
  /**
2168
2248
  * This method takes an OpenTelemetry instrumentation or
2169
2249
  * array of instrumentations and registers them with OpenTelemetry.
2250
+ *
2251
+ * @deprecated This method will be removed in the next major version of the SDK.
2252
+ * Use the `openTelemetryInstrumentations` option in `Sentry.init()` or your custom Sentry Client instead.
2170
2253
  */
2171
2254
  function addOpenTelemetryInstrumentation(...instrumentations) {
2172
2255
  registerInstrumentations({
@@ -2174,5 +2257,5 @@ function addOpenTelemetryInstrumentation(...instrumentations) {
2174
2257
  });
2175
2258
  }
2176
2259
 
2177
- export { SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION, SentryPropagator, SentrySampler, SentrySpanProcessor, addOpenTelemetryInstrumentation, continueTrace, enhanceDscWithOpenTelemetryRootSpanName, generateSpanContextForPropagationContext, getActiveSpan, getPropagationContextFromSpan, getRequestSpanData, getScopesFromContext, getSpanKind, isSentryRequestSpan, openTelemetrySetupCheck, setOpenTelemetryContextAsyncContextStrategy, setupEventContextTrace, spanHasAttributes, spanHasEvents, spanHasKind, spanHasName, spanHasParentId, spanHasStatus, startInactiveSpan, startSpan, startSpanManual, suppressTracing, withActiveSpan, wrapClientClass, wrapContextManagerClass, wrapSamplingDecision };
2260
+ export { SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION, SentryPropagator, SentrySampler, SentrySpanProcessor, addOpenTelemetryInstrumentation, continueTrace, enhanceDscWithOpenTelemetryRootSpanName, generateSpanContextForPropagationContext$1 as generateSpanContextForPropagationContext, getActiveSpan, getPropagationContextFromSpan, getRequestSpanData, getScopesFromContext, getSpanKind, getTraceContextForScope, isSentryRequestSpan, openTelemetrySetupCheck, setOpenTelemetryContextAsyncContextStrategy, setupEventContextTrace, shouldPropagateTraceForUrl, spanHasAttributes, spanHasEvents, spanHasKind, spanHasName, spanHasParentId, spanHasStatus, startInactiveSpan, startSpan, startSpanManual, suppressTracing, withActiveSpan, wrapClientClass, wrapContextManagerClass, wrapSamplingDecision };
2178
2261
  //# sourceMappingURL=index.js.map