@sentry/opentelemetry 9.29.0 → 9.31.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.
@@ -796,8 +796,12 @@ function shouldPropagateTraceForUrl(
796
796
 
797
797
  /**
798
798
  * Get propagation injection data for the given context.
799
+ * The additional options can be passed to override the scope and client that is otherwise derived from the context.
799
800
  */
800
- function getInjectionData(context)
801
+ function getInjectionData(
802
+ context,
803
+ options = {},
804
+ )
801
805
 
802
806
  {
803
807
  const span = api.trace.getSpan(context);
@@ -831,8 +835,8 @@ function getInjectionData(context)
831
835
 
832
836
  // Else we try to use the propagation context from the scope
833
837
  // The only scenario where this should happen is when we neither have a span, nor an incoming trace
834
- const scope = getScopesFromContext(context)?.scope || core.getCurrentScope();
835
- const client = core.getClient();
838
+ const scope = options.scope || getScopesFromContext(context)?.scope || core.getCurrentScope();
839
+ const client = options.client || core.getClient();
836
840
 
837
841
  const propagationContext = scope.getPropagationContext();
838
842
  const dynamicSamplingContext = client ? core.getDynamicSamplingContextFromScope(client, scope) : undefined;
@@ -1250,8 +1254,12 @@ function setupEventContextTrace(client) {
1250
1254
  * Otel-specific implementation of `getTraceData`.
1251
1255
  * @see `@sentry/core` version of `getTraceData` for more information
1252
1256
  */
1253
- function getTraceData({ span } = {}) {
1254
- let ctx = api.context.active();
1257
+ function getTraceData({
1258
+ span,
1259
+ scope,
1260
+ client,
1261
+ } = {}) {
1262
+ let ctx = (scope && getContextFromScope(scope)) ?? api.context.active();
1255
1263
 
1256
1264
  if (span) {
1257
1265
  const { scope } = core.getCapturedScopesOnSpan(span);
@@ -1259,7 +1267,7 @@ function getTraceData({ span } = {}) {
1259
1267
  ctx = (scope && getContextFromScope(scope)) || api.trace.setSpan(api.context.active(), span);
1260
1268
  }
1261
1269
 
1262
- const { traceId, spanId, sampled, dynamicSamplingContext } = getInjectionData(ctx);
1270
+ const { traceId, spanId, sampled, dynamicSamplingContext } = getInjectionData(ctx, { scope, client });
1263
1271
 
1264
1272
  return {
1265
1273
  'sentry-trace': core.generateSentryTraceHeader(traceId, spanId, sampled),
@@ -1601,7 +1609,6 @@ const DEFAULT_TIMEOUT = 300; // 5 min
1601
1609
  * A Sentry-specific exporter that converts OpenTelemetry Spans to Sentry Spans & Transactions.
1602
1610
  */
1603
1611
  class SentrySpanExporter {
1604
-
1605
1612
  /*
1606
1613
  * A quick explanation on the buckets: We do bucketing of finished spans for efficiency. This span exporter is
1607
1614
  * accumulating spans until a root span is encountered and then it flushes all the spans that are descendants of that
@@ -1622,6 +1629,8 @@ class SentrySpanExporter {
1622
1629
  // Essentially a a set of span ids that are already sent. The values are expiration
1623
1630
  // times in this cache so we don't hold onto them indefinitely.
1624
1631
 
1632
+ /* Internally, we use a debounced flush to give some wiggle room to the span processor to accumulate more spans. */
1633
+
1625
1634
  constructor(options
1626
1635
 
1627
1636
  ) {
@@ -1630,50 +1639,13 @@ class SentrySpanExporter {
1630
1639
  this._lastCleanupTimestampInS = Math.floor(Date.now() / 1000);
1631
1640
  this._spansToBucketEntry = new WeakMap();
1632
1641
  this._sentSpans = new Map();
1642
+ this._debouncedFlush = core.debounce(this.flush.bind(this), 1, { maxWait: 100 });
1633
1643
  }
1634
1644
 
1635
1645
  /**
1636
- * Check if a span with the given ID has already been sent using the `_sentSpans` as a cache.
1637
- * Purges "expired" spans from the cache upon checking.
1638
- * @param spanId The span id to check.
1639
- * @returns Whether the span is already sent in the past X seconds.
1646
+ * Export a single span.
1647
+ * This is called by the span processor whenever a span is ended.
1640
1648
  */
1641
- isSpanAlreadySent(spanId) {
1642
- const expirationTime = this._sentSpans.get(spanId);
1643
- if (expirationTime) {
1644
- if (Date.now() >= expirationTime) {
1645
- this._sentSpans.delete(spanId); // Remove expired span
1646
- } else {
1647
- return true;
1648
- }
1649
- }
1650
- return false;
1651
- }
1652
-
1653
- /** Remove "expired" span id entries from the _sentSpans cache. */
1654
- flushSentSpanCache() {
1655
- const currentTimestamp = Date.now();
1656
- // Note, it is safe to delete items from the map as we go: https://stackoverflow.com/a/35943995/90297
1657
- for (const [spanId, expirationTime] of this._sentSpans.entries()) {
1658
- if (expirationTime <= currentTimestamp) {
1659
- this._sentSpans.delete(spanId);
1660
- }
1661
- }
1662
- }
1663
-
1664
- /** Check if a node is a completed root node or a node whose parent has already been sent */
1665
- nodeIsCompletedRootNode(node) {
1666
- return !!node.span && (!node.parentNode || this.isSpanAlreadySent(node.parentNode.id));
1667
- }
1668
-
1669
- /** Get all completed root nodes from a list of nodes */
1670
- getCompletedRootNodes(nodes) {
1671
- // TODO: We should be able to remove the explicit `node is SpanNodeCompleted` type guard
1672
- // once we stop supporting TS < 5.5
1673
- return nodes.filter((node) => this.nodeIsCompletedRootNode(node));
1674
- }
1675
-
1676
- /** Export a single span. */
1677
1649
  export(span) {
1678
1650
  const currentTimestampInS = Math.floor(Date.now() / 1000);
1679
1651
 
@@ -1705,30 +1677,21 @@ class SentrySpanExporter {
1705
1677
 
1706
1678
  // If the span doesn't have a local parent ID (it's a root span), we're gonna flush all the ended spans
1707
1679
  const localParentId = getLocalParentId(span);
1708
- if (!localParentId || this.isSpanAlreadySent(localParentId)) {
1709
- this._clearTimeout();
1710
-
1711
- // If we got a parent span, we try to send the span tree
1712
- // Wait a tick for this, to ensure we avoid race conditions
1713
- this._flushTimeout = setTimeout(() => {
1714
- this.flush();
1715
- }, 1);
1680
+ if (!localParentId || this._sentSpans.has(localParentId)) {
1681
+ this._debouncedFlush();
1716
1682
  }
1717
1683
  }
1718
1684
 
1719
- /** Try to flush any pending spans immediately. */
1685
+ /**
1686
+ * Try to flush any pending spans immediately.
1687
+ * This is called internally by the exporter (via _debouncedFlush),
1688
+ * but can also be triggered externally if we force-flush.
1689
+ */
1720
1690
  flush() {
1721
- this._clearTimeout();
1722
-
1723
- const finishedSpans = this._finishedSpanBuckets.flatMap(bucket =>
1724
- bucket ? Array.from(bucket.spans) : [],
1725
- );
1691
+ const finishedSpans = this._finishedSpanBuckets.flatMap(bucket => (bucket ? Array.from(bucket.spans) : []));
1726
1692
 
1727
- this.flushSentSpanCache();
1693
+ this._flushSentSpanCache();
1728
1694
  const sentSpans = this._maybeSend(finishedSpans);
1729
- for (const span of finishedSpans) {
1730
- this._sentSpans.set(span.spanContext().spanId, Date.now() + DEFAULT_TIMEOUT * 1000);
1731
- }
1732
1695
 
1733
1696
  const sentSpanCount = sentSpans.size;
1734
1697
  const remainingOpenSpanCount = finishedSpans.length - sentSpanCount;
@@ -1737,26 +1700,29 @@ class SentrySpanExporter {
1737
1700
  `SpanExporter exported ${sentSpanCount} spans, ${remainingOpenSpanCount} spans are waiting for their parent spans to finish`,
1738
1701
  );
1739
1702
 
1703
+ const expirationDate = Date.now() + DEFAULT_TIMEOUT * 1000;
1704
+
1740
1705
  for (const span of sentSpans) {
1706
+ this._sentSpans.set(span.spanContext().spanId, expirationDate);
1741
1707
  const bucketEntry = this._spansToBucketEntry.get(span);
1742
1708
  if (bucketEntry) {
1743
1709
  bucketEntry.spans.delete(span);
1744
1710
  }
1745
1711
  }
1712
+ // Cancel a pending debounced flush, if there is one
1713
+ // This can be relevant if we directly flush, circumventing the debounce
1714
+ // in that case, we want to cancel any pending debounced flush
1715
+ this._debouncedFlush.cancel();
1746
1716
  }
1747
1717
 
1748
- /** Clear the exporter. */
1718
+ /**
1719
+ * Clear the exporter.
1720
+ * This is called when the span processor is shut down.
1721
+ */
1749
1722
  clear() {
1750
1723
  this._finishedSpanBuckets = this._finishedSpanBuckets.fill(undefined);
1751
- this._clearTimeout();
1752
- }
1753
-
1754
- /** Clear the flush timeout. */
1755
- _clearTimeout() {
1756
- if (this._flushTimeout) {
1757
- clearTimeout(this._flushTimeout);
1758
- this._flushTimeout = undefined;
1759
- }
1724
+ this._sentSpans.clear();
1725
+ this._debouncedFlush.cancel();
1760
1726
  }
1761
1727
 
1762
1728
  /**
@@ -1772,7 +1738,7 @@ class SentrySpanExporter {
1772
1738
  const grouped = groupSpansWithParents(spans);
1773
1739
  const sentSpans = new Set();
1774
1740
 
1775
- const rootNodes = this.getCompletedRootNodes(grouped);
1741
+ const rootNodes = this._getCompletedRootNodes(grouped);
1776
1742
 
1777
1743
  for (const root of rootNodes) {
1778
1744
  const span = root.span;
@@ -1803,6 +1769,29 @@ class SentrySpanExporter {
1803
1769
 
1804
1770
  return sentSpans;
1805
1771
  }
1772
+
1773
+ /** Remove "expired" span id entries from the _sentSpans cache. */
1774
+ _flushSentSpanCache() {
1775
+ const currentTimestamp = Date.now();
1776
+ // Note, it is safe to delete items from the map as we go: https://stackoverflow.com/a/35943995/90297
1777
+ for (const [spanId, expirationTime] of this._sentSpans.entries()) {
1778
+ if (expirationTime <= currentTimestamp) {
1779
+ this._sentSpans.delete(spanId);
1780
+ }
1781
+ }
1782
+ }
1783
+
1784
+ /** Check if a node is a completed root node or a node whose parent has already been sent */
1785
+ _nodeIsCompletedRootNodeOrHasSentParent(node) {
1786
+ return !!node.span && (!node.parentNode || this._sentSpans.has(node.parentNode.id));
1787
+ }
1788
+
1789
+ /** Get all completed root nodes from a list of nodes */
1790
+ _getCompletedRootNodes(nodes) {
1791
+ // TODO: We should be able to remove the explicit `node is SpanNodeCompleted` type guard
1792
+ // once we stop supporting TS < 5.5
1793
+ return nodes.filter((node) => this._nodeIsCompletedRootNodeOrHasSentParent(node));
1794
+ }
1806
1795
  }
1807
1796
 
1808
1797
  function parseSpan(span) {