@sentry/opentelemetry 8.0.0-alpha.5 → 8.0.0-alpha.7

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.
package/cjs/index.js CHANGED
@@ -265,6 +265,13 @@ function getContextFromScope(scope) {
265
265
  return SCOPE_CONTEXT_MAP.get(scope);
266
266
  }
267
267
 
268
+ /**
269
+ * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.
270
+ *
271
+ * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.
272
+ */
273
+ const DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);
274
+
268
275
  const setupElements = new Set();
269
276
 
270
277
  /** Get all the OpenTelemetry elements that have been set up. */
@@ -302,9 +309,14 @@ function getPropagationContextFromSpanContext(spanContext) {
302
309
  * Injects and extracts `sentry-trace` and `baggage` headers from carriers.
303
310
  */
304
311
  class SentryPropagator extends core$1.W3CBaggagePropagator {
312
+ /** A map of URLs that have already been checked for if they match tracePropagationTargets. */
313
+
305
314
  constructor() {
306
315
  super();
307
316
  setIsSetup('SentryPropagator');
317
+
318
+ // We're caching results so we don't have to recompute regexp every time we create a request.
319
+ this._urlMatchesTargetsMap = new utils.LRUMap(100);
308
320
  }
309
321
 
310
322
  /**
@@ -312,6 +324,20 @@ class SentryPropagator extends core$1.W3CBaggagePropagator {
312
324
  */
313
325
  inject(context, carrier, setter) {
314
326
  if (core$1.isTracingSuppressed(context)) {
327
+ DEBUG_BUILD && utils.logger.log('[Tracing] Not injecting trace data for url because tracing is suppressed.');
328
+ return;
329
+ }
330
+
331
+ const activeSpan = api.trace.getSpan(context);
332
+ const url = activeSpan && _optionalChain$7([core.spanToJSON, 'call', _ => _(activeSpan), 'access', _2 => _2.data, 'optionalAccess', _3 => _3[semanticConventions.SemanticAttributes.HTTP_URL]]);
333
+ const tracePropagationTargets = _optionalChain$7([core.getClient, 'call', _4 => _4(), 'optionalAccess', _5 => _5.getOptions, 'call', _6 => _6(), 'optionalAccess', _7 => _7.tracePropagationTargets]);
334
+ if (
335
+ typeof url === 'string' &&
336
+ tracePropagationTargets &&
337
+ !this._shouldInjectTraceData(tracePropagationTargets, url)
338
+ ) {
339
+ DEBUG_BUILD &&
340
+ utils.logger.log('[Tracing] Not injecting trace data for url because it does not matchTracePropagationTargets:', url);
315
341
  return;
316
342
  }
317
343
 
@@ -368,6 +394,22 @@ class SentryPropagator extends core$1.W3CBaggagePropagator {
368
394
  fields() {
369
395
  return [SENTRY_TRACE_HEADER, SENTRY_BAGGAGE_HEADER];
370
396
  }
397
+
398
+ /** If we want to inject trace data for a given URL. */
399
+ _shouldInjectTraceData(tracePropagationTargets, url) {
400
+ if (tracePropagationTargets === undefined) {
401
+ return true;
402
+ }
403
+
404
+ const cachedDecision = this._urlMatchesTargetsMap.get(url);
405
+ if (cachedDecision !== undefined) {
406
+ return cachedDecision;
407
+ }
408
+
409
+ const decision = utils.stringMatchesSomePattern(url, tracePropagationTargets);
410
+ this._urlMatchesTargetsMap.set(url, decision);
411
+ return decision;
412
+ }
371
413
  }
372
414
 
373
415
  /** Exported for tests. */
@@ -400,7 +442,7 @@ function getInjectionData(context)
400
442
 
401
443
  {
402
444
  const span = api.trace.getSpan(context);
403
- const spanIsRemote = _optionalChain$7([span, 'optionalAccess', _ => _.spanContext, 'call', _2 => _2(), 'access', _3 => _3.isRemote]);
445
+ const spanIsRemote = _optionalChain$7([span, 'optionalAccess', _8 => _8.spanContext, 'call', _9 => _9(), 'access', _10 => _10.isRemote]);
404
446
 
405
447
  // If we have a local span, we can just pick everything from it
406
448
  if (span && !spanIsRemote) {
@@ -416,7 +458,7 @@ function getInjectionData(context)
416
458
  }
417
459
 
418
460
  // Else we try to use the propagation context from the scope
419
- const scope = _optionalChain$7([getScopesFromContext, 'call', _4 => _4(context), 'optionalAccess', _5 => _5.scope]);
461
+ const scope = _optionalChain$7([getScopesFromContext, 'call', _11 => _11(context), 'optionalAccess', _12 => _12.scope]);
420
462
  if (scope) {
421
463
  const propagationContext = scope.getPropagationContext();
422
464
  const dynamicSamplingContext = getDynamicSamplingContext(propagationContext, propagationContext.traceId);
@@ -458,7 +500,7 @@ function getDynamicSamplingContext(
458
500
  traceId,
459
501
  ) {
460
502
  // If we have a DSC on the propagation context, we just use it
461
- if (_optionalChain$7([propagationContext, 'optionalAccess', _6 => _6.dsc])) {
503
+ if (_optionalChain$7([propagationContext, 'optionalAccess', _13 => _13.dsc])) {
462
504
  return propagationContext.dsc;
463
505
  }
464
506
 
@@ -538,10 +580,10 @@ function getSamplingDecision(spanContext) {
538
580
  const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : undefined;
539
581
  const dsc = dscString ? utils.baggageHeaderToDynamicSamplingContext(dscString) : undefined;
540
582
 
541
- if (_optionalChain$7([dsc, 'optionalAccess', _7 => _7.sampled]) === 'true') {
583
+ if (_optionalChain$7([dsc, 'optionalAccess', _14 => _14.sampled]) === 'true') {
542
584
  return true;
543
585
  }
544
- if (_optionalChain$7([dsc, 'optionalAccess', _8 => _8.sampled]) === 'false') {
586
+ if (_optionalChain$7([dsc, 'optionalAccess', _15 => _15.sampled]) === 'false') {
545
587
  return false;
546
588
  }
547
589
 
@@ -632,11 +674,12 @@ function _optionalChain$5(ops) { let lastAccessLHS = undefined; let value = ops[
632
674
  /**
633
675
  * Wraps a function with a transaction/span and finishes the span after the function is done.
634
676
  * The created span is the active span and will be used as parent by other spans created inside the function
635
- * and can be accessed via `Sentry.getSpan()`, as long as the function is executed while the scope is active.
677
+ * and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.
636
678
  *
637
679
  * If you want to create a span that is not set as active, use {@link startInactiveSpan}.
638
680
  *
639
- * Note that you'll always get a span passed to the callback, it may just be a NonRecordingSpan if the span is not sampled.
681
+ * You'll always get a span passed to the callback,
682
+ * it may just be a non-recording span if the span is not sampled or if tracing is disabled.
640
683
  */
641
684
  function startSpan(options, callback) {
642
685
  const tracer = getTracer();
@@ -655,7 +698,10 @@ function startSpan(options, callback) {
655
698
  return core.handleCallbackErrors(
656
699
  () => callback(span),
657
700
  () => {
658
- span.setStatus({ code: api.SpanStatusCode.ERROR });
701
+ // Only set the span status to ERROR when there wasn't any status set before, in order to avoid stomping useful span statuses
702
+ if (core.spanToJSON(span).status === undefined) {
703
+ span.setStatus({ code: api.SpanStatusCode.ERROR });
704
+ }
659
705
  },
660
706
  () => span.end(),
661
707
  );
@@ -669,7 +715,8 @@ function startSpan(options, callback) {
669
715
  * The created span is the active span and will be used as parent by other spans created inside the function
670
716
  * and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.
671
717
  *
672
- * Note that you'll always get a span passed to the callback, it may just be a NonRecordingSpan if the span is not sampled.
718
+ * You'll always get a span passed to the callback,
719
+ * it may just be a non-recording span if the span is not sampled or if tracing is disabled.
673
720
  */
674
721
  function startSpanManual(
675
722
  options,
@@ -691,7 +738,10 @@ function startSpanManual(
691
738
  return core.handleCallbackErrors(
692
739
  () => callback(span, () => span.end()),
693
740
  () => {
694
- span.setStatus({ code: api.SpanStatusCode.ERROR });
741
+ // Only set the span status to ERROR when there wasn't any status set before, in order to avoid stomping useful span statuses
742
+ if (core.spanToJSON(span).status === undefined) {
743
+ span.setStatus({ code: api.SpanStatusCode.ERROR });
744
+ }
695
745
  },
696
746
  );
697
747
  });
@@ -699,13 +749,12 @@ function startSpanManual(
699
749
 
700
750
  /**
701
751
  * Creates a span. This span is not set as active, so will not get automatic instrumentation spans
702
- * as children or be able to be accessed via `Sentry.getSpan()`.
752
+ * as children or be able to be accessed via `Sentry.getActiveSpan()`.
703
753
  *
704
754
  * If you want to create a span that is set as active, use {@link startSpan}.
705
755
  *
706
- * Note that if you have not enabled tracing extensions via `addTracingExtensions`
707
- * or you didn't set `tracesSampleRate` or `tracesSampler`, this function will not generate spans
708
- * and the `span` returned from the callback will be undefined.
756
+ * This function will always return a span,
757
+ * it may just be a non-recording span if the span is not sampled or if tracing is disabled.
709
758
  */
710
759
  function startInactiveSpan(options) {
711
760
  const tracer = getTracer();
@@ -730,7 +779,7 @@ function startInactiveSpan(options) {
730
779
  * passed `null` to start an entirely new span tree.
731
780
  *
732
781
  * @param span Spans started in the context of the provided callback will be children of this span. If `null` is passed,
733
- * spans started within the callback will not be attached to a parent span.
782
+ * spans started within the callback will be root spans.
734
783
  * @param callback Execution context in which the provided span will be active. Is passed the newly forked scope.
735
784
  * @returns the value returned from the provided callback function.
736
785
  */
@@ -1177,13 +1226,6 @@ function wrapContextManagerClass(
1177
1226
  return SentryContextManager ;
1178
1227
  }
1179
1228
 
1180
- /**
1181
- * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.
1182
- *
1183
- * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.
1184
- */
1185
- const DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);
1186
-
1187
1229
  /** If this attribute is true, it means that the parent is a remote span. */
1188
1230
  const SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE = 'sentry.parentIsRemote';
1189
1231
 
@@ -1208,14 +1250,19 @@ function groupSpansWithParents(spans) {
1208
1250
  });
1209
1251
  }
1210
1252
 
1211
- function createOrUpdateSpanNodeAndRefs(nodeMap, span) {
1253
+ /**
1254
+ * This returns the _local_ parent ID - `parentId` on the span may point to a remote span.
1255
+ */
1256
+ function getLocalParentId(span) {
1212
1257
  const parentIsRemote = span.attributes[SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE] === true;
1213
-
1214
- const id = span.spanContext().spanId;
1215
-
1216
1258
  // If the parentId is the trace parent ID, we pretend it's undefined
1217
1259
  // As this means the parent exists somewhere else
1218
- const parentId = !parentIsRemote ? span.parentSpanId : undefined;
1260
+ return !parentIsRemote ? span.parentSpanId : undefined;
1261
+ }
1262
+
1263
+ function createOrUpdateSpanNodeAndRefs(nodeMap, span) {
1264
+ const id = span.spanContext().spanId;
1265
+ const parentId = getLocalParentId(span);
1219
1266
 
1220
1267
  if (!parentId) {
1221
1268
  createOrUpdateNode(nodeMap, { id, span, children: [] });
@@ -1475,36 +1522,70 @@ function _optionalChain$2(ops) { let lastAccessLHS = undefined; let value = ops[
1475
1522
  /**
1476
1523
  * A Sentry-specific exporter that converts OpenTelemetry Spans to Sentry Spans & Transactions.
1477
1524
  */
1478
- class SentrySpanExporter {
1525
+ class SentrySpanExporter {
1479
1526
 
1480
1527
  constructor() {
1481
- this._stopped = false;
1482
1528
  this._finishedSpans = [];
1483
1529
  }
1484
1530
 
1485
- /** @inheritDoc */
1486
- export(spans, resultCallback) {
1487
- if (this._stopped) {
1488
- return resultCallback({
1489
- code: core$1.ExportResultCode.FAILED,
1490
- error: new Error('Exporter has been stopped'),
1491
- });
1531
+ /** Export a single span. */
1532
+ export(span) {
1533
+ this._finishedSpans.push(span);
1534
+
1535
+ // If the span has a local parent ID, we don't need to export anything just yet
1536
+ if (getLocalParentId(span)) {
1537
+ const openSpanCount = this._finishedSpans.length;
1538
+ DEBUG_BUILD && utils.logger.log(`SpanExporter has ${openSpanCount} unsent spans remaining`);
1539
+ this._cleanupOldSpans();
1540
+ return;
1492
1541
  }
1493
1542
 
1494
- const openSpanCount = this._finishedSpans.length;
1495
- const newSpanCount = spans.length;
1543
+ this._clearTimeout();
1544
+
1545
+ // If we got a parent span, we try to send the span tree
1546
+ // Wait a tick for this, to ensure we avoid race conditions
1547
+ this._flushTimeout = setTimeout(() => {
1548
+ this.flush();
1549
+ }, 1);
1550
+ }
1551
+
1552
+ /** Try to flush any pending spans immediately. */
1553
+ flush() {
1554
+ this._clearTimeout();
1496
1555
 
1497
- this._finishedSpans.push(...spans);
1556
+ const openSpanCount = this._finishedSpans.length;
1498
1557
 
1499
1558
  const remainingSpans = maybeSend(this._finishedSpans);
1500
1559
 
1501
1560
  const remainingOpenSpanCount = remainingSpans.length;
1502
- const sentSpanCount = openSpanCount + newSpanCount - remainingOpenSpanCount;
1561
+ const sentSpanCount = openSpanCount - remainingOpenSpanCount;
1503
1562
 
1504
1563
  DEBUG_BUILD &&
1505
1564
  utils.logger.log(`SpanExporter exported ${sentSpanCount} spans, ${remainingOpenSpanCount} unsent spans remaining`);
1506
1565
 
1507
- this._finishedSpans = remainingSpans.filter(span => {
1566
+ this._cleanupOldSpans(remainingSpans);
1567
+ }
1568
+
1569
+ /** Clear the exporter. */
1570
+ clear() {
1571
+ this._finishedSpans = [];
1572
+ this._clearTimeout();
1573
+ }
1574
+
1575
+ /** Clear the flush timeout. */
1576
+ _clearTimeout() {
1577
+ if (this._flushTimeout) {
1578
+ clearTimeout(this._flushTimeout);
1579
+ this._flushTimeout = undefined;
1580
+ }
1581
+ }
1582
+
1583
+ /**
1584
+ * Remove any span that is older than 5min.
1585
+ * We do this to avoid leaking memory.
1586
+ */
1587
+ _cleanupOldSpans(spans = this._finishedSpans) {
1588
+ this._finishedSpans = spans.filter(span => {
1508
1589
  const shouldDrop = shouldCleanupSpan(span, 5 * 60);
1509
1590
  DEBUG_BUILD &&
1510
1591
  shouldDrop &&
@@ -1515,23 +1596,6 @@ class SentrySpanExporter {
1515
1596
  );
1516
1597
  return !shouldDrop;
1517
1598
  });
1518
-
1519
- resultCallback({ code: core$1.ExportResultCode.SUCCESS });
1520
- }
1521
-
1522
- /** @inheritDoc */
1523
- shutdown() {
1524
- const forceFlush = this.forceFlush();
1525
- this._stopped = true;
1526
- this._finishedSpans = [];
1527
- return forceFlush;
1528
- }
1529
-
1530
- /** @inheritDoc */
1531
- forceFlush() {
1532
- return new Promise(resolve => {
1533
- this.export(this._finishedSpans, () => resolve());
1534
- });
1535
1599
  }
1536
1600
  }
1537
1601
 
@@ -1574,8 +1638,12 @@ function maybeSend(spans) {
1574
1638
  .filter((span) => !!span);
1575
1639
  }
1576
1640
 
1641
+ function nodeIsCompletedRootNode(node) {
1642
+ return !!node.span && !node.parentNode;
1643
+ }
1644
+
1577
1645
  function getCompletedRootNodes(nodes) {
1578
- return nodes.filter((node) => !!node.span && !node.parentNode);
1646
+ return nodes.filter(nodeIsCompletedRootNode);
1579
1647
  }
1580
1648
 
1581
1649
  function shouldCleanupSpan(span, maxStartTimeOffsetSeconds) {
@@ -1620,7 +1688,7 @@ function createTransactionForOtelSpan(span) {
1620
1688
  data: attributes,
1621
1689
  origin,
1622
1690
  op,
1623
- status: core.getStatusMessage(status),
1691
+ status: core.getStatusMessage(status), // As per protocol, span status is allowed to be undefined
1624
1692
  });
1625
1693
 
1626
1694
  const transactionEvent = {
@@ -1694,7 +1762,7 @@ function createAndFinishSpanForOtelSpan(node, spans, remaining) {
1694
1762
  start_timestamp: convertOtelTimeToSeconds(startTime),
1695
1763
  // This is [0,0] by default in OTEL, in which case we want to interpret this as no end time
1696
1764
  timestamp: convertOtelTimeToSeconds(endTime) || undefined,
1697
- status: core.getStatusMessage(status),
1765
+ status: core.getStatusMessage(status), // As per protocol, span status is allowed to be undefined
1698
1766
  op,
1699
1767
  origin,
1700
1768
  _metrics_summary: core.getMetricSummaryJsonForSpan(span ),
@@ -1807,18 +1875,32 @@ function onSpanStart(span, parentContext) {
1807
1875
 
1808
1876
  function onSpanEnd(span) {
1809
1877
  const client = core.getClient();
1810
- _optionalChain$1([client, 'optionalAccess', _3 => _3.emit, 'call', _4 => _4('spanEnd', span)]);
1878
+ _optionalChain$1([client, 'optionalAccess', _3 => _3.emit, 'call', _4 => _4('spanEnd', span )]);
1811
1879
  }
1812
1880
 
1813
1881
  /**
1814
1882
  * Converts OpenTelemetry Spans to Sentry Spans and sends them to Sentry via
1815
1883
  * the Sentry SDK.
1816
1884
  */
1817
- class SentrySpanProcessor extends sdkTraceBase.BatchSpanProcessor {
1818
- constructor() {
1819
- super(new SentrySpanExporter());
1885
+ class SentrySpanProcessor {
1820
1886
 
1887
+ constructor() {
1821
1888
  setIsSetup('SentrySpanProcessor');
1889
+ this._exporter = new SentrySpanExporter();
1890
+ }
1891
+
1892
+ /**
1893
+ * @inheritDoc
1894
+ */
1895
+ async forceFlush() {
1896
+ this._exporter.flush();
1897
+ }
1898
+
1899
+ /**
1900
+ * @inheritDoc
1901
+ */
1902
+ async shutdown() {
1903
+ this._exporter.clear();
1822
1904
  }
1823
1905
 
1824
1906
  /**
@@ -1831,30 +1913,20 @@ class SentrySpanProcessor extends sdkTraceBase.BatchSpanProcessor {
1831
1913
  // once we decoupled opentelemetry from SentrySpan
1832
1914
 
1833
1915
  DEBUG_BUILD && utils.logger.log(`[Tracing] Starting span "${span.name}" (${span.spanContext().spanId})`);
1834
-
1835
- return super.onStart(span, parentContext);
1836
1916
  }
1837
1917
 
1838
1918
  /** @inheritDoc */
1839
1919
  onEnd(span) {
1840
- DEBUG_BUILD && utils.logger.log(`[Tracing] Finishing span "${span.name}" (${span.spanContext().spanId})`);
1841
-
1842
- if (!this._shouldSendSpanToSentry(span)) {
1843
- // Prevent this being called to super.onEnd(), which would pass this to the span exporter
1920
+ if (span.spanContext().traceFlags !== api.TraceFlags.SAMPLED) {
1921
+ DEBUG_BUILD && utils.logger.log(`[Tracing] Finishing unsampled span "${span.name}" (${span.spanContext().spanId})`);
1844
1922
  return;
1845
1923
  }
1846
1924
 
1847
- onSpanEnd(span);
1925
+ DEBUG_BUILD && utils.logger.log(`[Tracing] Finishing span "${span.name}" (${span.spanContext().spanId})`);
1848
1926
 
1849
- return super.onEnd(span);
1850
- }
1927
+ onSpanEnd(span);
1851
1928
 
1852
- /**
1853
- * You can overwrite this in a sub class to implement custom behavior for dropping spans.
1854
- * If you return `false` here, the span will not be passed to the exporter and thus not be sent.
1855
- */
1856
- _shouldSendSpanToSentry(_span) {
1857
- return true;
1929
+ this._exporter.export(span);
1858
1930
  }
1859
1931
  }
1860
1932