@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.
@@ -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';
@@ -771,6 +771,9 @@ class SentryPropagator extends W3CBaggagePropagator {
771
771
  }
772
772
  }
773
773
 
774
+ /**
775
+ * Get propagation injection data for the given context.
776
+ */
774
777
  function getInjectionData(context)
775
778
 
776
779
  {
@@ -781,8 +784,7 @@ function getInjectionData(context)
781
784
  if (span && !spanIsRemote) {
782
785
  const spanContext = span.spanContext();
783
786
 
784
- const propagationContext = getPropagationContextFromSpan(span);
785
- const dynamicSamplingContext = getDynamicSamplingContext(propagationContext, spanContext.traceId);
787
+ const dynamicSamplingContext = getDynamicSamplingContextFromSpan(span);
786
788
  return {
787
789
  dynamicSamplingContext,
788
790
  traceId: spanContext.traceId,
@@ -793,9 +795,10 @@ function getInjectionData(context)
793
795
 
794
796
  // Else we try to use the propagation context from the scope
795
797
  const scope = _optionalChain$6([getScopesFromContext, 'call', _8 => _8(context), 'optionalAccess', _9 => _9.scope]) || getCurrentScope();
798
+ const client = getClient();
796
799
 
797
800
  const propagationContext = scope.getPropagationContext();
798
- const dynamicSamplingContext = getDynamicSamplingContext(propagationContext, propagationContext.traceId);
801
+ const dynamicSamplingContext = client ? getDynamicSamplingContextFromScope(client, scope) : undefined;
799
802
  return {
800
803
  dynamicSamplingContext,
801
804
  traceId: propagationContext.traceId,
@@ -804,26 +807,6 @@ function getInjectionData(context)
804
807
  };
805
808
  }
806
809
 
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
810
  function getContextWithRemoteActiveSpan(
828
811
  ctx,
829
812
  { sentryTrace, baggage },
@@ -871,13 +854,13 @@ function getCurrentURL(span) {
871
854
  const spanData = spanToJSON(span).data;
872
855
  // `ATTR_URL_FULL` is the new attribute, but we still support the old one, `SEMATTRS_HTTP_URL`, for now.
873
856
  // 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]]);
857
+ const urlAttribute = _optionalChain$6([spanData, 'optionalAccess', _10 => _10[SEMATTRS_HTTP_URL]]) || _optionalChain$6([spanData, 'optionalAccess', _11 => _11[ATTR_URL_FULL]]);
875
858
  if (urlAttribute) {
876
859
  return urlAttribute;
877
860
  }
878
861
 
879
862
  // 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)]);
863
+ 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)]);
881
864
  if (urlTraceState) {
882
865
  return urlTraceState;
883
866
  }
@@ -1146,6 +1129,25 @@ function continueTrace(options, callback) {
1146
1129
  });
1147
1130
  }
1148
1131
 
1132
+ /**
1133
+ * Get the trace context for a given scope.
1134
+ * We have a custom implemention here because we need an OTEL-specific way to get the span from a scope.
1135
+ */
1136
+ function getTraceContextForScope(
1137
+ client,
1138
+ scope,
1139
+ ) {
1140
+ const ctx = getContextFromScope(scope);
1141
+ const span = ctx && trace.getSpan(ctx);
1142
+
1143
+ const traceContext = span ? spanToTraceContext(span) : getTraceContextFromScope(scope);
1144
+
1145
+ const dynamicSamplingContext = span
1146
+ ? getDynamicSamplingContextFromSpan(span)
1147
+ : getDynamicSamplingContextFromScope(client, scope);
1148
+ return [dynamicSamplingContext, traceContext];
1149
+ }
1150
+
1149
1151
  function getActiveSpanWrapper(parentSpan) {
1150
1152
  return parentSpan !== undefined
1151
1153
  ? (callback) => {
@@ -1208,19 +1210,21 @@ function setupEventContextTrace(client) {
1208
1210
  * Otel-specific implementation of `getTraceData`.
1209
1211
  * @see `@sentry/core` version of `getTraceData` for more information
1210
1212
  */
1211
- function getTraceData() {
1212
- const headersObject = {};
1213
-
1214
- api.propagation.inject(api.context.active(), headersObject);
1213
+ function getTraceData({ span } = {}) {
1214
+ let ctx = api.context.active();
1215
1215
 
1216
- if (!headersObject['sentry-trace']) {
1217
- return {};
1216
+ if (span) {
1217
+ const { scope } = getCapturedScopesOnSpan(span);
1218
+ // fall back to current context if for whatever reason we can't find the one of the span
1219
+ ctx = (scope && getContextFromScope(scope)) || api.trace.setSpan(api.context.active(), span);
1218
1220
  }
1219
1221
 
1220
- return dropUndefinedKeys({
1221
- 'sentry-trace': headersObject['sentry-trace'],
1222
- baggage: headersObject.baggage,
1223
- });
1222
+ const { traceId, spanId, sampled, dynamicSamplingContext } = getInjectionData(ctx);
1223
+
1224
+ return {
1225
+ 'sentry-trace': generateSentryTraceHeader(traceId, spanId, sampled),
1226
+ baggage: dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext),
1227
+ };
1224
1228
  }
1225
1229
 
1226
1230
  /**
@@ -1561,52 +1565,105 @@ const DEFAULT_TIMEOUT = 300; // 5 min
1561
1565
  */
1562
1566
  class SentrySpanExporter {
1563
1567
 
1564
- constructor(options) {
1565
- this._finishedSpans = [];
1566
- this._timeout = _optionalChain$2([options, 'optionalAccess', _ => _.timeout]) || DEFAULT_TIMEOUT;
1568
+ /*
1569
+ * A quick explanation on the buckets: We do bucketing of finished spans for efficiency. This span exporter is
1570
+ * accumulating spans until a root span is encountered and then it flushes all the spans that are descendants of that
1571
+ * root span. Because it is totally in the realm of possibilities that root spans are never finished, and we don't
1572
+ * want to accumulate spans indefinitely in memory, we need to periodically evacuate spans. Naively we could simply
1573
+ * store the spans in an array and each time a new span comes in we could iterate through the entire array and
1574
+ * evacuate all spans that have an end-timestamp that is older than our limit. This could get quite expensive because
1575
+ * we would have to iterate a potentially large number of spans every time we evacuate. We want to avoid these large
1576
+ * bursts of computation.
1577
+ *
1578
+ * Instead we go for a bucketing approach and put spans into buckets, based on what second
1579
+ * (modulo the time limit) the span was put into the exporter. With buckets, when we decide to evacuate, we can
1580
+ * iterate through the bucket entries instead, which have an upper bound of items, making the evacuation much more
1581
+ * efficient. Cleaning up also becomes much more efficient since it simply involves de-referencing a bucket within the
1582
+ * bucket array, and letting garbage collection take care of the rest.
1583
+ */
1584
+
1585
+ constructor(options
1586
+
1587
+ ) {
1588
+ this._finishedSpanBucketSize = _optionalChain$2([options, 'optionalAccess', _ => _.timeout]) || DEFAULT_TIMEOUT;
1589
+ this._finishedSpanBuckets = new Array(this._finishedSpanBucketSize).fill(undefined);
1590
+ this._lastCleanupTimestampInS = Math.floor(Date.now() / 1000);
1591
+ this._spansToBucketEntry = new WeakMap();
1567
1592
  }
1568
1593
 
1569
1594
  /** Export a single span. */
1570
1595
  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;
1596
+ const currentTimestampInS = Math.floor(Date.now() / 1000);
1597
+
1598
+ if (this._lastCleanupTimestampInS !== currentTimestampInS) {
1599
+ let droppedSpanCount = 0;
1600
+ this._finishedSpanBuckets.forEach((bucket, i) => {
1601
+ if (bucket && bucket.timestampInS <= currentTimestampInS - this._finishedSpanBucketSize) {
1602
+ droppedSpanCount += bucket.spans.size;
1603
+ this._finishedSpanBuckets[i] = undefined;
1604
+ }
1605
+ });
1606
+ if (droppedSpanCount > 0) {
1607
+ DEBUG_BUILD &&
1608
+ logger.log(
1609
+ `SpanExporter dropped ${droppedSpanCount} spans because they were pending for more than ${this._finishedSpanBucketSize} seconds.`,
1610
+ );
1611
+ }
1612
+ this._lastCleanupTimestampInS = currentTimestampInS;
1579
1613
  }
1580
1614
 
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);
1615
+ const currentBucketIndex = currentTimestampInS % this._finishedSpanBucketSize;
1616
+ const currentBucket = this._finishedSpanBuckets[currentBucketIndex] || {
1617
+ timestampInS: currentTimestampInS,
1618
+ spans: new Set(),
1619
+ };
1620
+ this._finishedSpanBuckets[currentBucketIndex] = currentBucket;
1621
+ currentBucket.spans.add(span);
1622
+ this._spansToBucketEntry.set(span, currentBucket);
1623
+
1624
+ // If the span doesn't have a local parent ID (it's a root span), we're gonna flush all the ended spans
1625
+ if (!getLocalParentId(span)) {
1626
+ this._clearTimeout();
1627
+
1628
+ // If we got a parent span, we try to send the span tree
1629
+ // Wait a tick for this, to ensure we avoid race conditions
1630
+ this._flushTimeout = setTimeout(() => {
1631
+ this.flush();
1632
+ }, 1);
1633
+ }
1588
1634
  }
1589
1635
 
1590
1636
  /** Try to flush any pending spans immediately. */
1591
1637
  flush() {
1592
1638
  this._clearTimeout();
1593
1639
 
1594
- const openSpanCount = this._finishedSpans.length;
1640
+ const finishedSpans = [];
1641
+ this._finishedSpanBuckets.forEach(bucket => {
1642
+ if (bucket) {
1643
+ finishedSpans.push(...bucket.spans);
1644
+ }
1645
+ });
1646
+
1647
+ const sentSpans = maybeSend(finishedSpans);
1595
1648
 
1596
- const remainingSpans = maybeSend(this._finishedSpans);
1649
+ const sentSpanCount = sentSpans.size;
1597
1650
 
1598
- const remainingOpenSpanCount = remainingSpans.length;
1599
- const sentSpanCount = openSpanCount - remainingOpenSpanCount;
1651
+ const remainingOpenSpanCount = finishedSpans.length - sentSpanCount;
1600
1652
 
1601
1653
  DEBUG_BUILD &&
1602
1654
  logger.log(`SpanExporter exported ${sentSpanCount} spans, ${remainingOpenSpanCount} unsent spans remaining`);
1603
1655
 
1604
- this._cleanupOldSpans(remainingSpans);
1656
+ sentSpans.forEach(span => {
1657
+ const bucketEntry = this._spansToBucketEntry.get(span);
1658
+ if (bucketEntry) {
1659
+ bucketEntry.spans.delete(span);
1660
+ }
1661
+ });
1605
1662
  }
1606
1663
 
1607
1664
  /** Clear the exporter. */
1608
1665
  clear() {
1609
- this._finishedSpans = [];
1666
+ this._finishedSpanBuckets = this._finishedSpanBuckets.fill(undefined);
1610
1667
  this._clearTimeout();
1611
1668
  }
1612
1669
 
@@ -1617,31 +1674,12 @@ class SentrySpanExporter {
1617
1674
  this._flushTimeout = undefined;
1618
1675
  }
1619
1676
  }
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
1677
  }
1640
1678
 
1641
1679
  /**
1642
1680
  * Send the given spans, but only if they are part of a finished transaction.
1643
1681
  *
1644
- * Returns the unsent spans.
1682
+ * Returns the sent spans.
1645
1683
  * Spans remain unsent when their parent span is not yet finished.
1646
1684
  * This will happen regularly, as child spans are generally finished before their parents.
1647
1685
  * But it _could_ also happen because, for whatever reason, a parent span was lost.
@@ -1649,20 +1687,20 @@ class SentrySpanExporter {
1649
1687
  */
1650
1688
  function maybeSend(spans) {
1651
1689
  const grouped = groupSpansWithParents(spans);
1652
- const remaining = new Set(grouped);
1690
+ const sentSpans = new Set();
1653
1691
 
1654
1692
  const rootNodes = getCompletedRootNodes(grouped);
1655
1693
 
1656
1694
  rootNodes.forEach(root => {
1657
- remaining.delete(root);
1658
1695
  const span = root.span;
1696
+ sentSpans.add(span);
1659
1697
  const transactionEvent = createTransactionForOtelSpan(span);
1660
1698
 
1661
1699
  // We'll recursively add all the child spans to this array
1662
1700
  const spans = transactionEvent.spans || [];
1663
1701
 
1664
1702
  root.children.forEach(child => {
1665
- createAndFinishSpanForOtelSpan(child, spans, remaining);
1703
+ createAndFinishSpanForOtelSpan(child, spans, sentSpans);
1666
1704
  });
1667
1705
 
1668
1706
  // spans.sort() mutates the array, but we do not use this anymore after this point
@@ -1680,9 +1718,7 @@ function maybeSend(spans) {
1680
1718
  captureEvent(transactionEvent);
1681
1719
  });
1682
1720
 
1683
- return Array.from(remaining)
1684
- .map(node => node.span)
1685
- .filter((span) => !!span);
1721
+ return sentSpans;
1686
1722
  }
1687
1723
 
1688
1724
  function nodeIsCompletedRootNode(node) {
@@ -1693,11 +1729,6 @@ function getCompletedRootNodes(nodes) {
1693
1729
  return nodes.filter(nodeIsCompletedRootNode);
1694
1730
  }
1695
1731
 
1696
- function shouldCleanupSpan(span, currentTimeSeconds, maxStartTimeOffsetSeconds) {
1697
- const cutoff = currentTimeSeconds - maxStartTimeOffsetSeconds;
1698
- return spanTimeInputToSeconds(span.startTime) < cutoff;
1699
- }
1700
-
1701
1732
  function parseSpan(span) {
1702
1733
  const attributes = span.attributes;
1703
1734
 
@@ -1778,16 +1809,19 @@ function createTransactionForOtelSpan(span) {
1778
1809
  return transactionEvent;
1779
1810
  }
1780
1811
 
1781
- function createAndFinishSpanForOtelSpan(node, spans, remaining) {
1782
- remaining.delete(node);
1812
+ function createAndFinishSpanForOtelSpan(node, spans, sentSpans) {
1783
1813
  const span = node.span;
1784
1814
 
1815
+ if (span) {
1816
+ sentSpans.add(span);
1817
+ }
1818
+
1785
1819
  const shouldDrop = !span;
1786
1820
 
1787
1821
  // If this span should be dropped, we still want to create spans for the children of this
1788
1822
  if (shouldDrop) {
1789
1823
  node.children.forEach(child => {
1790
- createAndFinishSpanForOtelSpan(child, spans, remaining);
1824
+ createAndFinishSpanForOtelSpan(child, spans, sentSpans);
1791
1825
  });
1792
1826
  return;
1793
1827
  }
@@ -1826,7 +1860,7 @@ function createAndFinishSpanForOtelSpan(node, spans, remaining) {
1826
1860
  spans.push(spanJSON);
1827
1861
 
1828
1862
  node.children.forEach(child => {
1829
- createAndFinishSpanForOtelSpan(child, spans, remaining);
1863
+ createAndFinishSpanForOtelSpan(child, spans, sentSpans);
1830
1864
  });
1831
1865
  }
1832
1866
 
@@ -2174,5 +2208,5 @@ function addOpenTelemetryInstrumentation(...instrumentations) {
2174
2208
  });
2175
2209
  }
2176
2210
 
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 };
2211
+ export { SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION, SentryPropagator, SentrySampler, SentrySpanProcessor, addOpenTelemetryInstrumentation, continueTrace, enhanceDscWithOpenTelemetryRootSpanName, generateSpanContextForPropagationContext, getActiveSpan, getPropagationContextFromSpan, getRequestSpanData, getScopesFromContext, getSpanKind, getTraceContextForScope, isSentryRequestSpan, openTelemetrySetupCheck, setOpenTelemetryContextAsyncContextStrategy, setupEventContextTrace, spanHasAttributes, spanHasEvents, spanHasKind, spanHasName, spanHasParentId, spanHasStatus, startInactiveSpan, startSpan, startSpanManual, suppressTracing, withActiveSpan, wrapClientClass, wrapContextManagerClass, wrapSamplingDecision };
2178
2212
  //# sourceMappingURL=index.js.map