@sentry/opentelemetry 8.41.0-beta.1 → 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
  }
@@ -1149,6 +1132,25 @@ function continueTrace(options, callback) {
1149
1132
  });
1150
1133
  }
1151
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
+
1152
1154
  function getActiveSpanWrapper(parentSpan) {
1153
1155
  return parentSpan !== undefined
1154
1156
  ? (callback) => {
@@ -1211,19 +1213,21 @@ function setupEventContextTrace(client) {
1211
1213
  * Otel-specific implementation of `getTraceData`.
1212
1214
  * @see `@sentry/core` version of `getTraceData` for more information
1213
1215
  */
1214
- function getTraceData() {
1215
- const headersObject = {};
1216
-
1217
- api.propagation.inject(api.context.active(), headersObject);
1216
+ function getTraceData({ span } = {}) {
1217
+ let ctx = api.context.active();
1218
1218
 
1219
- if (!headersObject['sentry-trace']) {
1220
- 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);
1221
1223
  }
1222
1224
 
1223
- return core.dropUndefinedKeys({
1224
- 'sentry-trace': headersObject['sentry-trace'],
1225
- baggage: headersObject.baggage,
1226
- });
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
+ };
1227
1231
  }
1228
1232
 
1229
1233
  /**
@@ -1564,52 +1568,105 @@ const DEFAULT_TIMEOUT = 300; // 5 min
1564
1568
  */
1565
1569
  class SentrySpanExporter {
1566
1570
 
1567
- constructor(options) {
1568
- this._finishedSpans = [];
1569
- 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();
1570
1595
  }
1571
1596
 
1572
1597
  /** Export a single span. */
1573
1598
  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;
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;
1582
1616
  }
1583
1617
 
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);
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
+ }
1591
1637
  }
1592
1638
 
1593
1639
  /** Try to flush any pending spans immediately. */
1594
1640
  flush() {
1595
1641
  this._clearTimeout();
1596
1642
 
1597
- 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);
1598
1651
 
1599
- const remainingSpans = maybeSend(this._finishedSpans);
1652
+ const sentSpanCount = sentSpans.size;
1600
1653
 
1601
- const remainingOpenSpanCount = remainingSpans.length;
1602
- const sentSpanCount = openSpanCount - remainingOpenSpanCount;
1654
+ const remainingOpenSpanCount = finishedSpans.length - sentSpanCount;
1603
1655
 
1604
1656
  DEBUG_BUILD &&
1605
1657
  core.logger.log(`SpanExporter exported ${sentSpanCount} spans, ${remainingOpenSpanCount} unsent spans remaining`);
1606
1658
 
1607
- this._cleanupOldSpans(remainingSpans);
1659
+ sentSpans.forEach(span => {
1660
+ const bucketEntry = this._spansToBucketEntry.get(span);
1661
+ if (bucketEntry) {
1662
+ bucketEntry.spans.delete(span);
1663
+ }
1664
+ });
1608
1665
  }
1609
1666
 
1610
1667
  /** Clear the exporter. */
1611
1668
  clear() {
1612
- this._finishedSpans = [];
1669
+ this._finishedSpanBuckets = this._finishedSpanBuckets.fill(undefined);
1613
1670
  this._clearTimeout();
1614
1671
  }
1615
1672
 
@@ -1620,31 +1677,12 @@ class SentrySpanExporter {
1620
1677
  this._flushTimeout = undefined;
1621
1678
  }
1622
1679
  }
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
1680
  }
1643
1681
 
1644
1682
  /**
1645
1683
  * Send the given spans, but only if they are part of a finished transaction.
1646
1684
  *
1647
- * Returns the unsent spans.
1685
+ * Returns the sent spans.
1648
1686
  * Spans remain unsent when their parent span is not yet finished.
1649
1687
  * This will happen regularly, as child spans are generally finished before their parents.
1650
1688
  * But it _could_ also happen because, for whatever reason, a parent span was lost.
@@ -1652,20 +1690,20 @@ class SentrySpanExporter {
1652
1690
  */
1653
1691
  function maybeSend(spans) {
1654
1692
  const grouped = groupSpansWithParents(spans);
1655
- const remaining = new Set(grouped);
1693
+ const sentSpans = new Set();
1656
1694
 
1657
1695
  const rootNodes = getCompletedRootNodes(grouped);
1658
1696
 
1659
1697
  rootNodes.forEach(root => {
1660
- remaining.delete(root);
1661
1698
  const span = root.span;
1699
+ sentSpans.add(span);
1662
1700
  const transactionEvent = createTransactionForOtelSpan(span);
1663
1701
 
1664
1702
  // We'll recursively add all the child spans to this array
1665
1703
  const spans = transactionEvent.spans || [];
1666
1704
 
1667
1705
  root.children.forEach(child => {
1668
- createAndFinishSpanForOtelSpan(child, spans, remaining);
1706
+ createAndFinishSpanForOtelSpan(child, spans, sentSpans);
1669
1707
  });
1670
1708
 
1671
1709
  // spans.sort() mutates the array, but we do not use this anymore after this point
@@ -1683,9 +1721,7 @@ function maybeSend(spans) {
1683
1721
  core.captureEvent(transactionEvent);
1684
1722
  });
1685
1723
 
1686
- return Array.from(remaining)
1687
- .map(node => node.span)
1688
- .filter((span) => !!span);
1724
+ return sentSpans;
1689
1725
  }
1690
1726
 
1691
1727
  function nodeIsCompletedRootNode(node) {
@@ -1696,11 +1732,6 @@ function getCompletedRootNodes(nodes) {
1696
1732
  return nodes.filter(nodeIsCompletedRootNode);
1697
1733
  }
1698
1734
 
1699
- function shouldCleanupSpan(span, currentTimeSeconds, maxStartTimeOffsetSeconds) {
1700
- const cutoff = currentTimeSeconds - maxStartTimeOffsetSeconds;
1701
- return core.spanTimeInputToSeconds(span.startTime) < cutoff;
1702
- }
1703
-
1704
1735
  function parseSpan(span) {
1705
1736
  const attributes = span.attributes;
1706
1737
 
@@ -1781,16 +1812,19 @@ function createTransactionForOtelSpan(span) {
1781
1812
  return transactionEvent;
1782
1813
  }
1783
1814
 
1784
- function createAndFinishSpanForOtelSpan(node, spans, remaining) {
1785
- remaining.delete(node);
1815
+ function createAndFinishSpanForOtelSpan(node, spans, sentSpans) {
1786
1816
  const span = node.span;
1787
1817
 
1818
+ if (span) {
1819
+ sentSpans.add(span);
1820
+ }
1821
+
1788
1822
  const shouldDrop = !span;
1789
1823
 
1790
1824
  // If this span should be dropped, we still want to create spans for the children of this
1791
1825
  if (shouldDrop) {
1792
1826
  node.children.forEach(child => {
1793
- createAndFinishSpanForOtelSpan(child, spans, remaining);
1827
+ createAndFinishSpanForOtelSpan(child, spans, sentSpans);
1794
1828
  });
1795
1829
  return;
1796
1830
  }
@@ -1829,7 +1863,7 @@ function createAndFinishSpanForOtelSpan(node, spans, remaining) {
1829
1863
  spans.push(spanJSON);
1830
1864
 
1831
1865
  node.children.forEach(child => {
1832
- createAndFinishSpanForOtelSpan(child, spans, remaining);
1866
+ createAndFinishSpanForOtelSpan(child, spans, sentSpans);
1833
1867
  });
1834
1868
  }
1835
1869
 
@@ -2193,6 +2227,7 @@ exports.getPropagationContextFromSpan = getPropagationContextFromSpan;
2193
2227
  exports.getRequestSpanData = getRequestSpanData;
2194
2228
  exports.getScopesFromContext = getScopesFromContext;
2195
2229
  exports.getSpanKind = getSpanKind;
2230
+ exports.getTraceContextForScope = getTraceContextForScope;
2196
2231
  exports.isSentryRequestSpan = isSentryRequestSpan;
2197
2232
  exports.openTelemetrySetupCheck = openTelemetrySetupCheck;
2198
2233
  exports.setOpenTelemetryContextAsyncContextStrategy = setOpenTelemetryContextAsyncContextStrategy;