@sentry/opentelemetry 8.0.0-alpha.4 → 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/esm/index.js CHANGED
@@ -1,63 +1,12 @@
1
1
  import { _optionalChain } from '@sentry/utils';
2
2
  import { SemanticAttributes } from '@opentelemetry/semantic-conventions';
3
- import { captureException, SDK_VERSION, getCurrentScope, getIsolationScope, getClient, getDynamicSamplingContextFromClient, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, isSentryRequestUrl, handleCallbackErrors, SEMANTIC_ATTRIBUTE_SENTRY_OP, getRootSpan, continueTrace as continueTrace$1, withScope, captureEvent, addBreadcrumb, setUser, setTags, setTag, setExtra, setExtras, setContext, startSession, endSession, setAsyncContextStrategy, getDefaultCurrentScope, getDefaultIsolationScope, SPAN_STATUS_ERROR, SPAN_STATUS_OK, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, getStatusMessage, getMetricSummaryJsonForSpan, addChildSpanToSpan, hasTracingEnabled } from '@sentry/core';
4
- export { getClient } from '@sentry/core';
5
- import { isString, parseUrl, getSanitizedUrlString, SENTRY_BAGGAGE_KEY_PREFIX, generateSentryTraceHeader, propagationContextFromHeaders, baggageHeaderToDynamicSamplingContext, dynamicSamplingContextToSentryBaggageHeader, dropUndefinedKeys, stripUrlQueryAndFragment, logger, isNaN } from '@sentry/utils';
3
+ import { parseUrl, getSanitizedUrlString, LRUMap, logger, SENTRY_BAGGAGE_KEY_PREFIX, generateSentryTraceHeader, propagationContextFromHeaders, stringMatchesSomePattern, baggageHeaderToDynamicSamplingContext, dynamicSamplingContextToSentryBaggageHeader, dropUndefinedKeys, stripUrlQueryAndFragment, isNaN } from '@sentry/utils';
6
4
  import * as api from '@opentelemetry/api';
7
5
  import { trace, SpanKind, createContextKey, propagation, TraceFlags, context, SpanStatusCode, ROOT_CONTEXT, isSpanContextValid } from '@opentelemetry/api';
8
- import { W3CBaggagePropagator, isTracingSuppressed, TraceState, suppressTracing, ExportResultCode } from '@opentelemetry/core';
9
- import { BatchSpanProcessor, SamplingDecision } from '@opentelemetry/sdk-trace-base';
10
-
11
- /**
12
- * Maybe capture a Sentry exception for an OTEL timed event.
13
- * This will check if the event is exception-like and in that case capture it as an exception.
14
- */
15
- function maybeCaptureExceptionForTimedEvent(event, otelSpan) {
16
- if (event.name !== 'exception') {
17
- return;
18
- }
19
-
20
- const attributes = event.attributes;
21
- if (!attributes) {
22
- return;
23
- }
24
-
25
- const message = attributes[SemanticAttributes.EXCEPTION_MESSAGE];
26
-
27
- if (typeof message !== 'string') {
28
- return;
29
- }
30
-
31
- const syntheticError = new Error(message);
32
-
33
- const stack = attributes[SemanticAttributes.EXCEPTION_STACKTRACE];
34
- if (isString(stack)) {
35
- syntheticError.stack = stack;
36
- }
37
-
38
- const type = attributes[SemanticAttributes.EXCEPTION_TYPE];
39
- if (isString(type)) {
40
- syntheticError.name = type;
41
- }
42
-
43
- captureException(syntheticError, {
44
- captureContext: otelSpan
45
- ? {
46
- contexts: {
47
- otel: {
48
- attributes: otelSpan.attributes,
49
- resource: otelSpan.resource.attributes,
50
- },
51
- trace: {
52
- trace_id: otelSpan.spanContext().traceId,
53
- span_id: otelSpan.spanContext().spanId,
54
- parent_span_id: otelSpan.parentSpanId,
55
- },
56
- },
57
- }
58
- : undefined,
59
- });
60
- }
6
+ import { SDK_VERSION, getCurrentScope, getIsolationScope, getClient, getDynamicSamplingContextFromClient, spanToJSON, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, isSentryRequestUrl, handleCallbackErrors, SEMANTIC_ATTRIBUTE_SENTRY_OP, getRootSpan, continueTrace as continueTrace$1, withScope, captureEvent, addBreadcrumb, setUser, setTags, setTag, setExtra, setExtras, setContext, startSession, endSession, setAsyncContextStrategy, getDefaultCurrentScope, getDefaultIsolationScope, SPAN_STATUS_OK, SPAN_STATUS_ERROR, getSpanStatusFromHttpCode, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, getStatusMessage, getMetricSummaryJsonForSpan, addChildSpanToSpan, hasTracingEnabled } from '@sentry/core';
7
+ export { getClient } from '@sentry/core';
8
+ import { W3CBaggagePropagator, isTracingSuppressed, TraceState, suppressTracing } from '@opentelemetry/core';
9
+ import { SamplingDecision } from '@opentelemetry/sdk-trace-base';
61
10
 
62
11
  /**
63
12
  * Check if a given span has attributes.
@@ -313,6 +262,13 @@ function getContextFromScope(scope) {
313
262
  return SCOPE_CONTEXT_MAP.get(scope);
314
263
  }
315
264
 
265
+ /**
266
+ * 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.
267
+ *
268
+ * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.
269
+ */
270
+ const DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);
271
+
316
272
  const setupElements = new Set();
317
273
 
318
274
  /** Get all the OpenTelemetry elements that have been set up. */
@@ -350,9 +306,14 @@ function getPropagationContextFromSpanContext(spanContext) {
350
306
  * Injects and extracts `sentry-trace` and `baggage` headers from carriers.
351
307
  */
352
308
  class SentryPropagator extends W3CBaggagePropagator {
309
+ /** A map of URLs that have already been checked for if they match tracePropagationTargets. */
310
+
353
311
  constructor() {
354
312
  super();
355
313
  setIsSetup('SentryPropagator');
314
+
315
+ // We're caching results so we don't have to recompute regexp every time we create a request.
316
+ this._urlMatchesTargetsMap = new LRUMap(100);
356
317
  }
357
318
 
358
319
  /**
@@ -360,6 +321,20 @@ class SentryPropagator extends W3CBaggagePropagator {
360
321
  */
361
322
  inject(context, carrier, setter) {
362
323
  if (isTracingSuppressed(context)) {
324
+ DEBUG_BUILD && logger.log('[Tracing] Not injecting trace data for url because tracing is suppressed.');
325
+ return;
326
+ }
327
+
328
+ const activeSpan = trace.getSpan(context);
329
+ const url = activeSpan && _optionalChain$7([spanToJSON, 'call', _ => _(activeSpan), 'access', _2 => _2.data, 'optionalAccess', _3 => _3[SemanticAttributes.HTTP_URL]]);
330
+ const tracePropagationTargets = _optionalChain$7([getClient, 'call', _4 => _4(), 'optionalAccess', _5 => _5.getOptions, 'call', _6 => _6(), 'optionalAccess', _7 => _7.tracePropagationTargets]);
331
+ if (
332
+ typeof url === 'string' &&
333
+ tracePropagationTargets &&
334
+ !this._shouldInjectTraceData(tracePropagationTargets, url)
335
+ ) {
336
+ DEBUG_BUILD &&
337
+ logger.log('[Tracing] Not injecting trace data for url because it does not matchTracePropagationTargets:', url);
363
338
  return;
364
339
  }
365
340
 
@@ -416,6 +391,22 @@ class SentryPropagator extends W3CBaggagePropagator {
416
391
  fields() {
417
392
  return [SENTRY_TRACE_HEADER, SENTRY_BAGGAGE_HEADER];
418
393
  }
394
+
395
+ /** If we want to inject trace data for a given URL. */
396
+ _shouldInjectTraceData(tracePropagationTargets, url) {
397
+ if (tracePropagationTargets === undefined) {
398
+ return true;
399
+ }
400
+
401
+ const cachedDecision = this._urlMatchesTargetsMap.get(url);
402
+ if (cachedDecision !== undefined) {
403
+ return cachedDecision;
404
+ }
405
+
406
+ const decision = stringMatchesSomePattern(url, tracePropagationTargets);
407
+ this._urlMatchesTargetsMap.set(url, decision);
408
+ return decision;
409
+ }
419
410
  }
420
411
 
421
412
  /** Exported for tests. */
@@ -448,7 +439,7 @@ function getInjectionData(context)
448
439
 
449
440
  {
450
441
  const span = trace.getSpan(context);
451
- const spanIsRemote = _optionalChain$7([span, 'optionalAccess', _ => _.spanContext, 'call', _2 => _2(), 'access', _3 => _3.isRemote]);
442
+ const spanIsRemote = _optionalChain$7([span, 'optionalAccess', _8 => _8.spanContext, 'call', _9 => _9(), 'access', _10 => _10.isRemote]);
452
443
 
453
444
  // If we have a local span, we can just pick everything from it
454
445
  if (span && !spanIsRemote) {
@@ -464,7 +455,7 @@ function getInjectionData(context)
464
455
  }
465
456
 
466
457
  // Else we try to use the propagation context from the scope
467
- const scope = _optionalChain$7([getScopesFromContext, 'call', _4 => _4(context), 'optionalAccess', _5 => _5.scope]);
458
+ const scope = _optionalChain$7([getScopesFromContext, 'call', _11 => _11(context), 'optionalAccess', _12 => _12.scope]);
468
459
  if (scope) {
469
460
  const propagationContext = scope.getPropagationContext();
470
461
  const dynamicSamplingContext = getDynamicSamplingContext(propagationContext, propagationContext.traceId);
@@ -506,7 +497,7 @@ function getDynamicSamplingContext(
506
497
  traceId,
507
498
  ) {
508
499
  // If we have a DSC on the propagation context, we just use it
509
- if (_optionalChain$7([propagationContext, 'optionalAccess', _6 => _6.dsc])) {
500
+ if (_optionalChain$7([propagationContext, 'optionalAccess', _13 => _13.dsc])) {
510
501
  return propagationContext.dsc;
511
502
  }
512
503
 
@@ -586,10 +577,10 @@ function getSamplingDecision(spanContext) {
586
577
  const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : undefined;
587
578
  const dsc = dscString ? baggageHeaderToDynamicSamplingContext(dscString) : undefined;
588
579
 
589
- if (_optionalChain$7([dsc, 'optionalAccess', _7 => _7.sampled]) === 'true') {
580
+ if (_optionalChain$7([dsc, 'optionalAccess', _14 => _14.sampled]) === 'true') {
590
581
  return true;
591
582
  }
592
- if (_optionalChain$7([dsc, 'optionalAccess', _8 => _8.sampled]) === 'false') {
583
+ if (_optionalChain$7([dsc, 'optionalAccess', _15 => _15.sampled]) === 'false') {
593
584
  return false;
594
585
  }
595
586
 
@@ -680,11 +671,12 @@ function _optionalChain$5(ops) { let lastAccessLHS = undefined; let value = ops[
680
671
  /**
681
672
  * Wraps a function with a transaction/span and finishes the span after the function is done.
682
673
  * The created span is the active span and will be used as parent by other spans created inside the function
683
- * and can be accessed via `Sentry.getSpan()`, as long as the function is executed while the scope is active.
674
+ * and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.
684
675
  *
685
676
  * If you want to create a span that is not set as active, use {@link startInactiveSpan}.
686
677
  *
687
- * Note that you'll always get a span passed to the callback, it may just be a NonRecordingSpan if the span is not sampled.
678
+ * You'll always get a span passed to the callback,
679
+ * it may just be a non-recording span if the span is not sampled or if tracing is disabled.
688
680
  */
689
681
  function startSpan(options, callback) {
690
682
  const tracer = getTracer();
@@ -703,7 +695,10 @@ function startSpan(options, callback) {
703
695
  return handleCallbackErrors(
704
696
  () => callback(span),
705
697
  () => {
706
- span.setStatus({ code: SpanStatusCode.ERROR });
698
+ // Only set the span status to ERROR when there wasn't any status set before, in order to avoid stomping useful span statuses
699
+ if (spanToJSON(span).status === undefined) {
700
+ span.setStatus({ code: SpanStatusCode.ERROR });
701
+ }
707
702
  },
708
703
  () => span.end(),
709
704
  );
@@ -717,7 +712,8 @@ function startSpan(options, callback) {
717
712
  * The created span is the active span and will be used as parent by other spans created inside the function
718
713
  * and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.
719
714
  *
720
- * Note that you'll always get a span passed to the callback, it may just be a NonRecordingSpan if the span is not sampled.
715
+ * You'll always get a span passed to the callback,
716
+ * it may just be a non-recording span if the span is not sampled or if tracing is disabled.
721
717
  */
722
718
  function startSpanManual(
723
719
  options,
@@ -739,7 +735,10 @@ function startSpanManual(
739
735
  return handleCallbackErrors(
740
736
  () => callback(span, () => span.end()),
741
737
  () => {
742
- span.setStatus({ code: SpanStatusCode.ERROR });
738
+ // Only set the span status to ERROR when there wasn't any status set before, in order to avoid stomping useful span statuses
739
+ if (spanToJSON(span).status === undefined) {
740
+ span.setStatus({ code: SpanStatusCode.ERROR });
741
+ }
743
742
  },
744
743
  );
745
744
  });
@@ -747,13 +746,12 @@ function startSpanManual(
747
746
 
748
747
  /**
749
748
  * Creates a span. This span is not set as active, so will not get automatic instrumentation spans
750
- * as children or be able to be accessed via `Sentry.getSpan()`.
749
+ * as children or be able to be accessed via `Sentry.getActiveSpan()`.
751
750
  *
752
751
  * If you want to create a span that is set as active, use {@link startSpan}.
753
752
  *
754
- * Note that if you have not enabled tracing extensions via `addTracingExtensions`
755
- * or you didn't set `tracesSampleRate` or `tracesSampler`, this function will not generate spans
756
- * and the `span` returned from the callback will be undefined.
753
+ * This function will always return a span,
754
+ * it may just be a non-recording span if the span is not sampled or if tracing is disabled.
757
755
  */
758
756
  function startInactiveSpan(options) {
759
757
  const tracer = getTracer();
@@ -778,7 +776,7 @@ function startInactiveSpan(options) {
778
776
  * passed `null` to start an entirely new span tree.
779
777
  *
780
778
  * @param span Spans started in the context of the provided callback will be children of this span. If `null` is passed,
781
- * spans started within the callback will not be attached to a parent span.
779
+ * spans started within the callback will be root spans.
782
780
  * @param callback Execution context in which the provided span will be active. Is passed the newly forked scope.
783
781
  * @returns the value returned from the provided callback function.
784
782
  */
@@ -977,8 +975,7 @@ function getCurrentHub() {
977
975
  setContext,
978
976
 
979
977
  getIntegration(integration) {
980
- // eslint-disable-next-line deprecation/deprecation
981
- return _optionalChain$4([getClient, 'call', _ => _(), 'optionalAccess', _2 => _2.getIntegration, 'call', _3 => _3(integration)]) || null;
978
+ return _optionalChain$4([getClient, 'call', _ => _(), 'optionalAccess', _2 => _2.getIntegrationByName, 'call', _3 => _3(integration.id)]) || null;
982
979
  },
983
980
 
984
981
  startSession,
@@ -1226,13 +1223,6 @@ function wrapContextManagerClass(
1226
1223
  return SentryContextManager ;
1227
1224
  }
1228
1225
 
1229
- /**
1230
- * 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.
1231
- *
1232
- * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.
1233
- */
1234
- const DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);
1235
-
1236
1226
  /** If this attribute is true, it means that the parent is a remote span. */
1237
1227
  const SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE = 'sentry.parentIsRemote';
1238
1228
 
@@ -1257,14 +1247,19 @@ function groupSpansWithParents(spans) {
1257
1247
  });
1258
1248
  }
1259
1249
 
1260
- function createOrUpdateSpanNodeAndRefs(nodeMap, span) {
1250
+ /**
1251
+ * This returns the _local_ parent ID - `parentId` on the span may point to a remote span.
1252
+ */
1253
+ function getLocalParentId(span) {
1261
1254
  const parentIsRemote = span.attributes[SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE] === true;
1262
-
1263
- const id = span.spanContext().spanId;
1264
-
1265
1255
  // If the parentId is the trace parent ID, we pretend it's undefined
1266
1256
  // As this means the parent exists somewhere else
1267
- const parentId = !parentIsRemote ? span.parentSpanId : undefined;
1257
+ return !parentIsRemote ? span.parentSpanId : undefined;
1258
+ }
1259
+
1260
+ function createOrUpdateSpanNodeAndRefs(nodeMap, span) {
1261
+ const id = span.spanContext().spanId;
1262
+ const parentId = getLocalParentId(span);
1268
1263
 
1269
1264
  if (!parentId) {
1270
1265
  createOrUpdateNode(nodeMap, { id, span, children: [] });
@@ -1308,23 +1303,8 @@ function createOrUpdateNode(nodeMap, spanNode) {
1308
1303
  return spanNode;
1309
1304
  }
1310
1305
 
1311
- // canonicalCodesHTTPMap maps some HTTP codes to Sentry's span statuses. See possible mapping in https://develop.sentry.dev/sdk/event-payloads/span/
1312
- const canonicalCodesHTTPMap = {
1313
- '400': 'failed_precondition',
1314
- '401': 'unauthenticated',
1315
- '403': 'permission_denied',
1316
- '404': 'not_found',
1317
- '409': 'aborted',
1318
- '429': 'resource_exhausted',
1319
- '499': 'cancelled',
1320
- '500': 'internal_error',
1321
- '501': 'unimplemented',
1322
- '503': 'unavailable',
1323
- '504': 'deadline_exceeded',
1324
- } ;
1325
-
1326
1306
  // canonicalCodesGrpcMap maps some GRPC codes to Sentry's span statuses. See description in grpc documentation.
1327
- const canonicalCodesGrpcMap = {
1307
+ const canonicalGrpcErrorCodesMap = {
1328
1308
  '1': 'cancelled',
1329
1309
  '2': 'unknown_error',
1330
1310
  '3': 'invalid_argument',
@@ -1350,30 +1330,42 @@ function mapStatus(span) {
1350
1330
  const attributes = spanHasAttributes(span) ? span.attributes : {};
1351
1331
  const status = spanHasStatus(span) ? span.status : undefined;
1352
1332
 
1353
- const httpCode = attributes[SemanticAttributes.HTTP_STATUS_CODE];
1354
- const grpcCode = attributes[SemanticAttributes.RPC_GRPC_STATUS_CODE];
1355
-
1356
- const code = typeof httpCode === 'string' ? httpCode : typeof httpCode === 'number' ? httpCode.toString() : undefined;
1357
- if (code) {
1358
- const sentryStatus = canonicalCodesHTTPMap[code];
1359
- if (sentryStatus) {
1360
- return { code: SPAN_STATUS_ERROR, message: sentryStatus };
1333
+ if (status) {
1334
+ // Since span status OK is not set by default, we give it priority: https://opentelemetry.io/docs/concepts/signals/traces/#span-status
1335
+ if (status.code === SpanStatusCode.OK) {
1336
+ return { code: SPAN_STATUS_OK };
1337
+ // If the span is already marked as erroneous we return that exact status
1338
+ } else if (status.code === SpanStatusCode.ERROR) {
1339
+ return { code: SPAN_STATUS_ERROR, message: status.message };
1361
1340
  }
1362
1341
  }
1363
1342
 
1364
- if (typeof grpcCode === 'string') {
1365
- const sentryStatus = canonicalCodesGrpcMap[grpcCode];
1366
- if (sentryStatus) {
1367
- return { code: SPAN_STATUS_ERROR, message: sentryStatus };
1368
- }
1343
+ // If the span status is UNSET, we try to infer it from HTTP or GRPC status codes.
1344
+
1345
+ const httpCodeAttribute = attributes[SemanticAttributes.HTTP_STATUS_CODE];
1346
+ const grpcCodeAttribute = attributes[SemanticAttributes.RPC_GRPC_STATUS_CODE];
1347
+
1348
+ const numberHttpCode =
1349
+ typeof httpCodeAttribute === 'number'
1350
+ ? httpCodeAttribute
1351
+ : typeof httpCodeAttribute === 'string'
1352
+ ? parseInt(httpCodeAttribute)
1353
+ : undefined;
1354
+
1355
+ if (numberHttpCode) {
1356
+ return getSpanStatusFromHttpCode(numberHttpCode);
1369
1357
  }
1370
1358
 
1371
- const statusCode = status && status.code;
1372
- if (statusCode === SpanStatusCode.OK || statusCode === SpanStatusCode.UNSET) {
1373
- return { code: SPAN_STATUS_OK };
1359
+ if (typeof grpcCodeAttribute === 'string') {
1360
+ return { code: SPAN_STATUS_ERROR, message: canonicalGrpcErrorCodesMap[grpcCodeAttribute] || 'unknown_error' };
1374
1361
  }
1375
1362
 
1376
- return { code: SPAN_STATUS_ERROR, message: 'unknown_error' };
1363
+ // We default to setting the spans status to ok.
1364
+ if (status && status.code === SpanStatusCode.UNSET) {
1365
+ return { code: SPAN_STATUS_OK };
1366
+ } else {
1367
+ return { code: SPAN_STATUS_ERROR, message: 'unknown_error' };
1368
+ }
1377
1369
  }
1378
1370
 
1379
1371
  /**
@@ -1527,36 +1519,70 @@ function _optionalChain$2(ops) { let lastAccessLHS = undefined; let value = ops[
1527
1519
  /**
1528
1520
  * A Sentry-specific exporter that converts OpenTelemetry Spans to Sentry Spans & Transactions.
1529
1521
  */
1530
- class SentrySpanExporter {
1522
+ class SentrySpanExporter {
1531
1523
 
1532
1524
  constructor() {
1533
- this._stopped = false;
1534
1525
  this._finishedSpans = [];
1535
1526
  }
1536
1527
 
1537
- /** @inheritDoc */
1538
- export(spans, resultCallback) {
1539
- if (this._stopped) {
1540
- return resultCallback({
1541
- code: ExportResultCode.FAILED,
1542
- error: new Error('Exporter has been stopped'),
1543
- });
1528
+ /** Export a single span. */
1529
+ export(span) {
1530
+ this._finishedSpans.push(span);
1531
+
1532
+ // If the span has a local parent ID, we don't need to export anything just yet
1533
+ if (getLocalParentId(span)) {
1534
+ const openSpanCount = this._finishedSpans.length;
1535
+ DEBUG_BUILD && logger.log(`SpanExporter has ${openSpanCount} unsent spans remaining`);
1536
+ this._cleanupOldSpans();
1537
+ return;
1544
1538
  }
1545
1539
 
1546
- const openSpanCount = this._finishedSpans.length;
1547
- const newSpanCount = spans.length;
1540
+ this._clearTimeout();
1541
+
1542
+ // If we got a parent span, we try to send the span tree
1543
+ // Wait a tick for this, to ensure we avoid race conditions
1544
+ this._flushTimeout = setTimeout(() => {
1545
+ this.flush();
1546
+ }, 1);
1547
+ }
1548
1548
 
1549
- this._finishedSpans.push(...spans);
1549
+ /** Try to flush any pending spans immediately. */
1550
+ flush() {
1551
+ this._clearTimeout();
1552
+
1553
+ const openSpanCount = this._finishedSpans.length;
1550
1554
 
1551
1555
  const remainingSpans = maybeSend(this._finishedSpans);
1552
1556
 
1553
1557
  const remainingOpenSpanCount = remainingSpans.length;
1554
- const sentSpanCount = openSpanCount + newSpanCount - remainingOpenSpanCount;
1558
+ const sentSpanCount = openSpanCount - remainingOpenSpanCount;
1555
1559
 
1556
1560
  DEBUG_BUILD &&
1557
1561
  logger.log(`SpanExporter exported ${sentSpanCount} spans, ${remainingOpenSpanCount} unsent spans remaining`);
1558
1562
 
1559
- this._finishedSpans = remainingSpans.filter(span => {
1563
+ this._cleanupOldSpans(remainingSpans);
1564
+ }
1565
+
1566
+ /** Clear the exporter. */
1567
+ clear() {
1568
+ this._finishedSpans = [];
1569
+ this._clearTimeout();
1570
+ }
1571
+
1572
+ /** Clear the flush timeout. */
1573
+ _clearTimeout() {
1574
+ if (this._flushTimeout) {
1575
+ clearTimeout(this._flushTimeout);
1576
+ this._flushTimeout = undefined;
1577
+ }
1578
+ }
1579
+
1580
+ /**
1581
+ * Remove any span that is older than 5min.
1582
+ * We do this to avoid leaking memory.
1583
+ */
1584
+ _cleanupOldSpans(spans = this._finishedSpans) {
1585
+ this._finishedSpans = spans.filter(span => {
1560
1586
  const shouldDrop = shouldCleanupSpan(span, 5 * 60);
1561
1587
  DEBUG_BUILD &&
1562
1588
  shouldDrop &&
@@ -1567,23 +1593,6 @@ class SentrySpanExporter {
1567
1593
  );
1568
1594
  return !shouldDrop;
1569
1595
  });
1570
-
1571
- resultCallback({ code: ExportResultCode.SUCCESS });
1572
- }
1573
-
1574
- /** @inheritDoc */
1575
- shutdown() {
1576
- const forceFlush = this.forceFlush();
1577
- this._stopped = true;
1578
- this._finishedSpans = [];
1579
- return forceFlush;
1580
- }
1581
-
1582
- /** @inheritDoc */
1583
- forceFlush() {
1584
- return new Promise(resolve => {
1585
- this.export(this._finishedSpans, () => resolve());
1586
- });
1587
1596
  }
1588
1597
  }
1589
1598
 
@@ -1626,8 +1635,12 @@ function maybeSend(spans) {
1626
1635
  .filter((span) => !!span);
1627
1636
  }
1628
1637
 
1638
+ function nodeIsCompletedRootNode(node) {
1639
+ return !!node.span && !node.parentNode;
1640
+ }
1641
+
1629
1642
  function getCompletedRootNodes(nodes) {
1630
- return nodes.filter((node) => !!node.span && !node.parentNode);
1643
+ return nodes.filter(nodeIsCompletedRootNode);
1631
1644
  }
1632
1645
 
1633
1646
  function shouldCleanupSpan(span, maxStartTimeOffsetSeconds) {
@@ -1672,7 +1685,7 @@ function createTransactionForOtelSpan(span) {
1672
1685
  data: attributes,
1673
1686
  origin,
1674
1687
  op,
1675
- status: getStatusMessage(status),
1688
+ status: getStatusMessage(status), // As per protocol, span status is allowed to be undefined
1676
1689
  });
1677
1690
 
1678
1691
  const transactionEvent = {
@@ -1746,7 +1759,7 @@ function createAndFinishSpanForOtelSpan(node, spans, remaining) {
1746
1759
  start_timestamp: convertOtelTimeToSeconds(startTime),
1747
1760
  // This is [0,0] by default in OTEL, in which case we want to interpret this as no end time
1748
1761
  timestamp: convertOtelTimeToSeconds(endTime) || undefined,
1749
- status: getStatusMessage(status),
1762
+ status: getStatusMessage(status), // As per protocol, span status is allowed to be undefined
1750
1763
  op,
1751
1764
  origin,
1752
1765
  _metrics_summary: getMetricSummaryJsonForSpan(span ),
@@ -1858,24 +1871,33 @@ function onSpanStart(span, parentContext) {
1858
1871
  }
1859
1872
 
1860
1873
  function onSpanEnd(span) {
1861
- // Capture exceptions as events
1862
- span.events.forEach(event => {
1863
- maybeCaptureExceptionForTimedEvent(event, span);
1864
- });
1865
-
1866
1874
  const client = getClient();
1867
- _optionalChain$1([client, 'optionalAccess', _3 => _3.emit, 'call', _4 => _4('spanEnd', span)]);
1875
+ _optionalChain$1([client, 'optionalAccess', _3 => _3.emit, 'call', _4 => _4('spanEnd', span )]);
1868
1876
  }
1869
1877
 
1870
1878
  /**
1871
1879
  * Converts OpenTelemetry Spans to Sentry Spans and sends them to Sentry via
1872
1880
  * the Sentry SDK.
1873
1881
  */
1874
- class SentrySpanProcessor extends BatchSpanProcessor {
1875
- constructor() {
1876
- super(new SentrySpanExporter());
1882
+ class SentrySpanProcessor {
1877
1883
 
1884
+ constructor() {
1878
1885
  setIsSetup('SentrySpanProcessor');
1886
+ this._exporter = new SentrySpanExporter();
1887
+ }
1888
+
1889
+ /**
1890
+ * @inheritDoc
1891
+ */
1892
+ async forceFlush() {
1893
+ this._exporter.flush();
1894
+ }
1895
+
1896
+ /**
1897
+ * @inheritDoc
1898
+ */
1899
+ async shutdown() {
1900
+ this._exporter.clear();
1879
1901
  }
1880
1902
 
1881
1903
  /**
@@ -1888,30 +1910,20 @@ class SentrySpanProcessor extends BatchSpanProcessor {
1888
1910
  // once we decoupled opentelemetry from SentrySpan
1889
1911
 
1890
1912
  DEBUG_BUILD && logger.log(`[Tracing] Starting span "${span.name}" (${span.spanContext().spanId})`);
1891
-
1892
- return super.onStart(span, parentContext);
1893
1913
  }
1894
1914
 
1895
1915
  /** @inheritDoc */
1896
1916
  onEnd(span) {
1897
- DEBUG_BUILD && logger.log(`[Tracing] Finishing span "${span.name}" (${span.spanContext().spanId})`);
1898
-
1899
- if (!this._shouldSendSpanToSentry(span)) {
1900
- // Prevent this being called to super.onEnd(), which would pass this to the span exporter
1917
+ if (span.spanContext().traceFlags !== TraceFlags.SAMPLED) {
1918
+ DEBUG_BUILD && logger.log(`[Tracing] Finishing unsampled span "${span.name}" (${span.spanContext().spanId})`);
1901
1919
  return;
1902
1920
  }
1903
1921
 
1904
- onSpanEnd(span);
1922
+ DEBUG_BUILD && logger.log(`[Tracing] Finishing span "${span.name}" (${span.spanContext().spanId})`);
1905
1923
 
1906
- return super.onEnd(span);
1907
- }
1924
+ onSpanEnd(span);
1908
1925
 
1909
- /**
1910
- * You can overwrite this in a sub class to implement custom behavior for dropping spans.
1911
- * If you return `false` here, the span will not be passed to the exporter and thus not be sent.
1912
- */
1913
- _shouldSendSpanToSentry(_span) {
1914
- return true;
1926
+ this._exporter.export(span);
1915
1927
  }
1916
1928
  }
1917
1929
 
@@ -2095,7 +2107,6 @@ function getParentRemoteSampled(spanContext) {
2095
2107
  * @hidden
2096
2108
  */
2097
2109
  const _INTERNAL = {
2098
- maybeCaptureExceptionForTimedEvent,
2099
2110
  getRequestSpanData,
2100
2111
  } ;
2101
2112