@sentry/opentelemetry 8.41.0-beta.0 → 8.41.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.
@@ -774,6 +774,9 @@ class SentryPropagator extends core$1.W3CBaggagePropagator {
774
774
  }
775
775
  }
776
776
 
777
+ /**
778
+ * Get propagation injection data for the given context.
779
+ */
777
780
  function getInjectionData(context)
778
781
 
779
782
  {
@@ -784,8 +787,7 @@ function getInjectionData(context)
784
787
  if (span && !spanIsRemote) {
785
788
  const spanContext = span.spanContext();
786
789
 
787
- const propagationContext = getPropagationContextFromSpan(span);
788
- const dynamicSamplingContext = getDynamicSamplingContext(propagationContext, spanContext.traceId);
790
+ const dynamicSamplingContext = core.getDynamicSamplingContextFromSpan(span);
789
791
  return {
790
792
  dynamicSamplingContext,
791
793
  traceId: spanContext.traceId,
@@ -796,9 +798,10 @@ function getInjectionData(context)
796
798
 
797
799
  // Else we try to use the propagation context from the scope
798
800
  const scope = _optionalChain$6([getScopesFromContext, 'call', _8 => _8(context), 'optionalAccess', _9 => _9.scope]) || core.getCurrentScope();
801
+ const client = core.getClient();
799
802
 
800
803
  const propagationContext = scope.getPropagationContext();
801
- const dynamicSamplingContext = getDynamicSamplingContext(propagationContext, propagationContext.traceId);
804
+ const dynamicSamplingContext = client ? core.getDynamicSamplingContextFromScope(client, scope) : undefined;
802
805
  return {
803
806
  dynamicSamplingContext,
804
807
  traceId: propagationContext.traceId,
@@ -807,26 +810,6 @@ function getInjectionData(context)
807
810
  };
808
811
  }
809
812
 
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
813
  function getContextWithRemoteActiveSpan(
831
814
  ctx,
832
815
  { sentryTrace, baggage },
@@ -874,13 +857,13 @@ function getCurrentURL(span) {
874
857
  const spanData = core.spanToJSON(span).data;
875
858
  // `ATTR_URL_FULL` is the new attribute, but we still support the old one, `SEMATTRS_HTTP_URL`, for now.
876
859
  // 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]]);
860
+ const urlAttribute = _optionalChain$6([spanData, 'optionalAccess', _10 => _10[semanticConventions.SEMATTRS_HTTP_URL]]) || _optionalChain$6([spanData, 'optionalAccess', _11 => _11[semanticConventions.ATTR_URL_FULL]]);
878
861
  if (urlAttribute) {
879
862
  return urlAttribute;
880
863
  }
881
864
 
882
865
  // 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)]);
866
+ const urlTraceState = _optionalChain$6([span, 'access', _12 => _12.spanContext, 'call', _13 => _13(), 'access', _14 => _14.traceState, 'optionalAccess', _15 => _15.get, 'call', _16 => _16(SENTRY_TRACE_STATE_URL)]);
884
867
  if (urlTraceState) {
885
868
  return urlTraceState;
886
869
  }
@@ -1046,8 +1029,9 @@ function ensureTimestampInMilliseconds(timestamp) {
1046
1029
 
1047
1030
  function getContext(scope, forceTransaction) {
1048
1031
  const ctx = getContextForScope(scope);
1032
+ // Note: If the context is the ROOT_CONTEXT, no scope is attached
1033
+ // Thus we will not use the propagation context in this case, which is desired
1049
1034
  const actualScope = _optionalChain$5([getScopesFromContext, 'call', _ => _(ctx), 'optionalAccess', _2 => _2.scope]);
1050
-
1051
1035
  const parentSpan = api.trace.getSpan(ctx);
1052
1036
 
1053
1037
  // In the case that we have no parent span, we need to "simulate" one to ensure the propagation context is correct
@@ -1148,6 +1132,25 @@ function continueTrace(options, callback) {
1148
1132
  });
1149
1133
  }
1150
1134
 
1135
+ /**
1136
+ * Get the trace context for a given scope.
1137
+ * We have a custom implemention here because we need an OTEL-specific way to get the span from a scope.
1138
+ */
1139
+ function getTraceContextForScope(
1140
+ client,
1141
+ scope,
1142
+ ) {
1143
+ const ctx = getContextFromScope(scope);
1144
+ const span = ctx && api.trace.getSpan(ctx);
1145
+
1146
+ const traceContext = span ? core.spanToTraceContext(span) : core.getTraceContextFromScope(scope);
1147
+
1148
+ const dynamicSamplingContext = span
1149
+ ? core.getDynamicSamplingContextFromSpan(span)
1150
+ : core.getDynamicSamplingContextFromScope(client, scope);
1151
+ return [dynamicSamplingContext, traceContext];
1152
+ }
1153
+
1151
1154
  function getActiveSpanWrapper(parentSpan) {
1152
1155
  return parentSpan !== undefined
1153
1156
  ? (callback) => {
@@ -1210,19 +1213,21 @@ function setupEventContextTrace(client) {
1210
1213
  * Otel-specific implementation of `getTraceData`.
1211
1214
  * @see `@sentry/core` version of `getTraceData` for more information
1212
1215
  */
1213
- function getTraceData() {
1214
- const headersObject = {};
1216
+ function getTraceData({ span } = {}) {
1217
+ let ctx = api.context.active();
1215
1218
 
1216
- api.propagation.inject(api.context.active(), headersObject);
1217
-
1218
- if (!headersObject['sentry-trace']) {
1219
- return {};
1219
+ if (span) {
1220
+ const { scope } = core.getCapturedScopesOnSpan(span);
1221
+ // fall back to current context if for whatever reason we can't find the one of the span
1222
+ ctx = (scope && getContextFromScope(scope)) || api.trace.setSpan(api.context.active(), span);
1220
1223
  }
1221
1224
 
1222
- return core.dropUndefinedKeys({
1223
- 'sentry-trace': headersObject['sentry-trace'],
1224
- baggage: headersObject.baggage,
1225
- });
1225
+ const { traceId, spanId, sampled, dynamicSamplingContext } = getInjectionData(ctx);
1226
+
1227
+ return {
1228
+ 'sentry-trace': core.generateSentryTraceHeader(traceId, spanId, sampled),
1229
+ baggage: core.dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext),
1230
+ };
1226
1231
  }
1227
1232
 
1228
1233
  /**
@@ -1563,52 +1568,105 @@ const DEFAULT_TIMEOUT = 300; // 5 min
1563
1568
  */
1564
1569
  class SentrySpanExporter {
1565
1570
 
1566
- constructor(options) {
1567
- this._finishedSpans = [];
1568
- this._timeout = _optionalChain$2([options, 'optionalAccess', _ => _.timeout]) || DEFAULT_TIMEOUT;
1571
+ /*
1572
+ * A quick explanation on the buckets: We do bucketing of finished spans for efficiency. This span exporter is
1573
+ * accumulating spans until a root span is encountered and then it flushes all the spans that are descendants of that
1574
+ * root span. Because it is totally in the realm of possibilities that root spans are never finished, and we don't
1575
+ * want to accumulate spans indefinitely in memory, we need to periodically evacuate spans. Naively we could simply
1576
+ * store the spans in an array and each time a new span comes in we could iterate through the entire array and
1577
+ * evacuate all spans that have an end-timestamp that is older than our limit. This could get quite expensive because
1578
+ * we would have to iterate a potentially large number of spans every time we evacuate. We want to avoid these large
1579
+ * bursts of computation.
1580
+ *
1581
+ * Instead we go for a bucketing approach and put spans into buckets, based on what second
1582
+ * (modulo the time limit) the span was put into the exporter. With buckets, when we decide to evacuate, we can
1583
+ * iterate through the bucket entries instead, which have an upper bound of items, making the evacuation much more
1584
+ * efficient. Cleaning up also becomes much more efficient since it simply involves de-referencing a bucket within the
1585
+ * bucket array, and letting garbage collection take care of the rest.
1586
+ */
1587
+
1588
+ constructor(options
1589
+
1590
+ ) {
1591
+ this._finishedSpanBucketSize = _optionalChain$2([options, 'optionalAccess', _ => _.timeout]) || DEFAULT_TIMEOUT;
1592
+ this._finishedSpanBuckets = new Array(this._finishedSpanBucketSize).fill(undefined);
1593
+ this._lastCleanupTimestampInS = Math.floor(Date.now() / 1000);
1594
+ this._spansToBucketEntry = new WeakMap();
1569
1595
  }
1570
1596
 
1571
1597
  /** Export a single span. */
1572
1598
  export(span) {
1573
- this._finishedSpans.push(span);
1574
-
1575
- // If the span has a local parent ID, we don't need to export anything just yet
1576
- if (getLocalParentId(span)) {
1577
- const openSpanCount = this._finishedSpans.length;
1578
- DEBUG_BUILD && core.logger.log(`SpanExporter has ${openSpanCount} unsent spans remaining`);
1579
- this._cleanupOldSpans();
1580
- return;
1599
+ const currentTimestampInS = Math.floor(Date.now() / 1000);
1600
+
1601
+ if (this._lastCleanupTimestampInS !== currentTimestampInS) {
1602
+ let droppedSpanCount = 0;
1603
+ this._finishedSpanBuckets.forEach((bucket, i) => {
1604
+ if (bucket && bucket.timestampInS <= currentTimestampInS - this._finishedSpanBucketSize) {
1605
+ droppedSpanCount += bucket.spans.size;
1606
+ this._finishedSpanBuckets[i] = undefined;
1607
+ }
1608
+ });
1609
+ if (droppedSpanCount > 0) {
1610
+ DEBUG_BUILD &&
1611
+ core.logger.log(
1612
+ `SpanExporter dropped ${droppedSpanCount} spans because they were pending for more than ${this._finishedSpanBucketSize} seconds.`,
1613
+ );
1614
+ }
1615
+ this._lastCleanupTimestampInS = currentTimestampInS;
1581
1616
  }
1582
1617
 
1583
- this._clearTimeout();
1584
-
1585
- // If we got a parent span, we try to send the span tree
1586
- // Wait a tick for this, to ensure we avoid race conditions
1587
- this._flushTimeout = setTimeout(() => {
1588
- this.flush();
1589
- }, 1);
1618
+ const currentBucketIndex = currentTimestampInS % this._finishedSpanBucketSize;
1619
+ const currentBucket = this._finishedSpanBuckets[currentBucketIndex] || {
1620
+ timestampInS: currentTimestampInS,
1621
+ spans: new Set(),
1622
+ };
1623
+ this._finishedSpanBuckets[currentBucketIndex] = currentBucket;
1624
+ currentBucket.spans.add(span);
1625
+ this._spansToBucketEntry.set(span, currentBucket);
1626
+
1627
+ // If the span doesn't have a local parent ID (it's a root span), we're gonna flush all the ended spans
1628
+ if (!getLocalParentId(span)) {
1629
+ this._clearTimeout();
1630
+
1631
+ // If we got a parent span, we try to send the span tree
1632
+ // Wait a tick for this, to ensure we avoid race conditions
1633
+ this._flushTimeout = setTimeout(() => {
1634
+ this.flush();
1635
+ }, 1);
1636
+ }
1590
1637
  }
1591
1638
 
1592
1639
  /** Try to flush any pending spans immediately. */
1593
1640
  flush() {
1594
1641
  this._clearTimeout();
1595
1642
 
1596
- const openSpanCount = this._finishedSpans.length;
1643
+ const finishedSpans = [];
1644
+ this._finishedSpanBuckets.forEach(bucket => {
1645
+ if (bucket) {
1646
+ finishedSpans.push(...bucket.spans);
1647
+ }
1648
+ });
1649
+
1650
+ const sentSpans = maybeSend(finishedSpans);
1597
1651
 
1598
- const remainingSpans = maybeSend(this._finishedSpans);
1652
+ const sentSpanCount = sentSpans.size;
1599
1653
 
1600
- const remainingOpenSpanCount = remainingSpans.length;
1601
- const sentSpanCount = openSpanCount - remainingOpenSpanCount;
1654
+ const remainingOpenSpanCount = finishedSpans.length - sentSpanCount;
1602
1655
 
1603
1656
  DEBUG_BUILD &&
1604
1657
  core.logger.log(`SpanExporter exported ${sentSpanCount} spans, ${remainingOpenSpanCount} unsent spans remaining`);
1605
1658
 
1606
- this._cleanupOldSpans(remainingSpans);
1659
+ sentSpans.forEach(span => {
1660
+ const bucketEntry = this._spansToBucketEntry.get(span);
1661
+ if (bucketEntry) {
1662
+ bucketEntry.spans.delete(span);
1663
+ }
1664
+ });
1607
1665
  }
1608
1666
 
1609
1667
  /** Clear the exporter. */
1610
1668
  clear() {
1611
- this._finishedSpans = [];
1669
+ this._finishedSpanBuckets = this._finishedSpanBuckets.fill(undefined);
1612
1670
  this._clearTimeout();
1613
1671
  }
1614
1672
 
@@ -1619,31 +1677,12 @@ class SentrySpanExporter {
1619
1677
  this._flushTimeout = undefined;
1620
1678
  }
1621
1679
  }
1622
-
1623
- /**
1624
- * Remove any span that is older than 5min.
1625
- * We do this to avoid leaking memory.
1626
- */
1627
- _cleanupOldSpans(spans = this._finishedSpans) {
1628
- const currentTimeSeconds = Date.now() / 1000;
1629
- this._finishedSpans = spans.filter(span => {
1630
- const shouldDrop = shouldCleanupSpan(span, currentTimeSeconds, this._timeout);
1631
- DEBUG_BUILD &&
1632
- shouldDrop &&
1633
- core.logger.log(
1634
- `SpanExporter dropping span ${span.name} (${
1635
- span.spanContext().spanId
1636
- }) because it is pending for more than 5 minutes.`,
1637
- );
1638
- return !shouldDrop;
1639
- });
1640
- }
1641
1680
  }
1642
1681
 
1643
1682
  /**
1644
1683
  * Send the given spans, but only if they are part of a finished transaction.
1645
1684
  *
1646
- * Returns the unsent spans.
1685
+ * Returns the sent spans.
1647
1686
  * Spans remain unsent when their parent span is not yet finished.
1648
1687
  * This will happen regularly, as child spans are generally finished before their parents.
1649
1688
  * But it _could_ also happen because, for whatever reason, a parent span was lost.
@@ -1651,20 +1690,20 @@ class SentrySpanExporter {
1651
1690
  */
1652
1691
  function maybeSend(spans) {
1653
1692
  const grouped = groupSpansWithParents(spans);
1654
- const remaining = new Set(grouped);
1693
+ const sentSpans = new Set();
1655
1694
 
1656
1695
  const rootNodes = getCompletedRootNodes(grouped);
1657
1696
 
1658
1697
  rootNodes.forEach(root => {
1659
- remaining.delete(root);
1660
1698
  const span = root.span;
1699
+ sentSpans.add(span);
1661
1700
  const transactionEvent = createTransactionForOtelSpan(span);
1662
1701
 
1663
1702
  // We'll recursively add all the child spans to this array
1664
1703
  const spans = transactionEvent.spans || [];
1665
1704
 
1666
1705
  root.children.forEach(child => {
1667
- createAndFinishSpanForOtelSpan(child, spans, remaining);
1706
+ createAndFinishSpanForOtelSpan(child, spans, sentSpans);
1668
1707
  });
1669
1708
 
1670
1709
  // spans.sort() mutates the array, but we do not use this anymore after this point
@@ -1682,9 +1721,7 @@ function maybeSend(spans) {
1682
1721
  core.captureEvent(transactionEvent);
1683
1722
  });
1684
1723
 
1685
- return Array.from(remaining)
1686
- .map(node => node.span)
1687
- .filter((span) => !!span);
1724
+ return sentSpans;
1688
1725
  }
1689
1726
 
1690
1727
  function nodeIsCompletedRootNode(node) {
@@ -1695,11 +1732,6 @@ function getCompletedRootNodes(nodes) {
1695
1732
  return nodes.filter(nodeIsCompletedRootNode);
1696
1733
  }
1697
1734
 
1698
- function shouldCleanupSpan(span, currentTimeSeconds, maxStartTimeOffsetSeconds) {
1699
- const cutoff = currentTimeSeconds - maxStartTimeOffsetSeconds;
1700
- return core.spanTimeInputToSeconds(span.startTime) < cutoff;
1701
- }
1702
-
1703
1735
  function parseSpan(span) {
1704
1736
  const attributes = span.attributes;
1705
1737
 
@@ -1780,16 +1812,19 @@ function createTransactionForOtelSpan(span) {
1780
1812
  return transactionEvent;
1781
1813
  }
1782
1814
 
1783
- function createAndFinishSpanForOtelSpan(node, spans, remaining) {
1784
- remaining.delete(node);
1815
+ function createAndFinishSpanForOtelSpan(node, spans, sentSpans) {
1785
1816
  const span = node.span;
1786
1817
 
1818
+ if (span) {
1819
+ sentSpans.add(span);
1820
+ }
1821
+
1787
1822
  const shouldDrop = !span;
1788
1823
 
1789
1824
  // If this span should be dropped, we still want to create spans for the children of this
1790
1825
  if (shouldDrop) {
1791
1826
  node.children.forEach(child => {
1792
- createAndFinishSpanForOtelSpan(child, spans, remaining);
1827
+ createAndFinishSpanForOtelSpan(child, spans, sentSpans);
1793
1828
  });
1794
1829
  return;
1795
1830
  }
@@ -1828,7 +1863,7 @@ function createAndFinishSpanForOtelSpan(node, spans, remaining) {
1828
1863
  spans.push(spanJSON);
1829
1864
 
1830
1865
  node.children.forEach(child => {
1831
- createAndFinishSpanForOtelSpan(child, spans, remaining);
1866
+ createAndFinishSpanForOtelSpan(child, spans, sentSpans);
1832
1867
  });
1833
1868
  }
1834
1869
 
@@ -2192,6 +2227,7 @@ exports.getPropagationContextFromSpan = getPropagationContextFromSpan;
2192
2227
  exports.getRequestSpanData = getRequestSpanData;
2193
2228
  exports.getScopesFromContext = getScopesFromContext;
2194
2229
  exports.getSpanKind = getSpanKind;
2230
+ exports.getTraceContextForScope = getTraceContextForScope;
2195
2231
  exports.isSentryRequestSpan = isSentryRequestSpan;
2196
2232
  exports.openTelemetrySetupCheck = openTelemetrySetupCheck;
2197
2233
  exports.setOpenTelemetryContextAsyncContextStrategy = setOpenTelemetryContextAsyncContextStrategy;