@sentry/opentelemetry 8.42.0 → 8.44.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,9 +1,9 @@
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, 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';
3
+ import { parseUrl, getSanitizedUrlString, SDK_VERSION, addNonEnumerableProperty, isSentryRequestUrl, getClient, baggageHeaderToDynamicSamplingContext, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, stripUrlQueryAndFragment, spanToJSON, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, hasTracingEnabled, dynamicSamplingContextToSentryBaggageHeader, getDynamicSamplingContextFromSpan, getRootSpan, LRUMap, logger, parseBaggageHeader, SENTRY_BAGGAGE_KEY_PREFIX, generateSentryTraceHeader, stringMatchesSomePattern, generateSpanId, getCurrentScope, getDynamicSamplingContextFromScope, propagationContextFromHeaders, getIsolationScope, handleCallbackErrors, continueTrace as continueTrace$1, spanToTraceContext, getTraceContextFromScope, getCapturedScopesOnSpan, setAsyncContextStrategy, getDefaultCurrentScope, getDefaultIsolationScope, SPAN_STATUS_OK, SPAN_STATUS_ERROR, getSpanStatusFromHttpCode, timedEventsToMeasurements, captureEvent, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, dropUndefinedKeys, getStatusMessage, spanTimeInputToSeconds, getMetricSummaryJsonForSpan, addChildSpanToSpan, setCapturedScopesOnSpan, logSpanStart, logSpanEnd, sampleSpan } from '@sentry/core';
4
4
  export { getClient, getCurrentHubShim, getDynamicSamplingContextFromSpan } from '@sentry/core';
5
5
  import * as api from '@opentelemetry/api';
6
- import { trace, SpanKind, createContextKey, TraceFlags, propagation, INVALID_TRACEID, context, SpanStatusCode, INVALID_SPANID, ROOT_CONTEXT, isSpanContextValid } from '@opentelemetry/api';
6
+ import { trace, SpanKind, createContextKey, TraceFlags, propagation, INVALID_TRACEID, context, SpanStatusCode, ROOT_CONTEXT, isSpanContextValid } from '@opentelemetry/api';
7
7
  import { TraceState, W3CBaggagePropagator, isTracingSuppressed, suppressTracing as suppressTracing$1 } from '@opentelemetry/core';
8
8
  import { SamplingDecision } from '@opentelemetry/sdk-trace-base';
9
9
  import { registerInstrumentations } from '@opentelemetry/instrumentation';
@@ -129,7 +129,7 @@ function getRequestSpanData(span) {
129
129
  return data;
130
130
  }
131
131
 
132
- function _optionalChain$8(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
132
+ function _optionalChain$6(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
133
133
 
134
134
  // Typescript complains if we do not use `...args: any[]` for the mixin, with:
135
135
  // A mixin class must have a constructor with a single rest parameter of type 'any[]'.ts(2545)
@@ -170,7 +170,7 @@ function wrapClientClass
170
170
  */
171
171
  async flush(timeout) {
172
172
  const provider = this.traceProvider;
173
- const spanProcessor = _optionalChain$8([provider, 'optionalAccess', _ => _.activeSpanProcessor]);
173
+ const spanProcessor = _optionalChain$6([provider, 'optionalAccess', _ => _.activeSpanProcessor]);
174
174
 
175
175
  if (spanProcessor) {
176
176
  await spanProcessor.forceFlush();
@@ -202,7 +202,6 @@ const SENTRY_TRACE_HEADER = 'sentry-trace';
202
202
  const SENTRY_BAGGAGE_HEADER = 'baggage';
203
203
 
204
204
  const SENTRY_TRACE_STATE_DSC = 'sentry.dsc';
205
- const SENTRY_TRACE_STATE_PARENT_SPAN_ID = 'sentry.parent_span_id';
206
205
  const SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING = 'sentry.sampled_not_recording';
207
206
  const SENTRY_TRACE_STATE_URL = 'sentry.url';
208
207
 
@@ -271,6 +270,46 @@ function isSentryRequestSpan(span) {
271
270
  return isSentryRequestUrl(httpUrl.toString(), getClient());
272
271
  }
273
272
 
273
+ function _optionalChain$5(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
274
+
275
+ /**
276
+ * OpenTelemetry only knows about SAMPLED or NONE decision,
277
+ * but for us it is important to differentiate between unset and unsampled.
278
+ *
279
+ * Both of these are identified as `traceFlags === TracegFlags.NONE`,
280
+ * but we additionally look at a special trace state to differentiate between them.
281
+ */
282
+ function getSamplingDecision(spanContext) {
283
+ const { traceFlags, traceState } = spanContext;
284
+
285
+ const sampledNotRecording = traceState ? traceState.get(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING) === '1' : false;
286
+
287
+ // If trace flag is `SAMPLED`, we interpret this as sampled
288
+ // If it is `NONE`, it could mean either it was sampled to be not recorder, or that it was not sampled at all
289
+ // For us this is an important difference, sow e look at the SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING
290
+ // to identify which it is
291
+ if (traceFlags === TraceFlags.SAMPLED) {
292
+ return true;
293
+ }
294
+
295
+ if (sampledNotRecording) {
296
+ return false;
297
+ }
298
+
299
+ // Fall back to DSC as a last resort, that may also contain `sampled`...
300
+ const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : undefined;
301
+ const dsc = dscString ? baggageHeaderToDynamicSamplingContext(dscString) : undefined;
302
+
303
+ if (_optionalChain$5([dsc, 'optionalAccess', _ => _.sampled]) === 'true') {
304
+ return true;
305
+ }
306
+ if (_optionalChain$5([dsc, 'optionalAccess', _2 => _2.sampled]) === 'false') {
307
+ return false;
308
+ }
309
+
310
+ return undefined;
311
+ }
312
+
274
313
  /**
275
314
  * Infer the op & description for a set of name, attributes and kind of a span.
276
315
  */
@@ -485,20 +524,31 @@ function getSanitizedUrl(
485
524
  */
486
525
  function enhanceDscWithOpenTelemetryRootSpanName(client) {
487
526
  client.on('createDsc', (dsc, rootSpan) => {
527
+ if (!rootSpan) {
528
+ return;
529
+ }
530
+
488
531
  // We want to overwrite the transaction on the DSC that is created by default in core
489
532
  // The reason for this is that we want to infer the span name, not use the initial one
490
533
  // Otherwise, we'll get names like "GET" instead of e.g. "GET /foo"
491
534
  // `parseSpanDescription` takes the attributes of the span into account for the name
492
535
  // This mutates the passed-in DSC
493
- if (rootSpan) {
494
- const jsonSpan = spanToJSON(rootSpan);
495
- const attributes = jsonSpan.data || {};
496
- const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
497
-
498
- const { description } = spanHasName(rootSpan) ? parseSpanDescription(rootSpan) : { description: undefined };
499
- if (source !== 'url' && description) {
500
- dsc.transaction = description;
501
- }
536
+
537
+ const jsonSpan = spanToJSON(rootSpan);
538
+ const attributes = jsonSpan.data || {};
539
+ const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
540
+
541
+ const { description } = spanHasName(rootSpan) ? parseSpanDescription(rootSpan) : { description: undefined };
542
+ if (source !== 'url' && description) {
543
+ dsc.transaction = description;
544
+ }
545
+
546
+ // Also ensure sampling decision is correctly inferred
547
+ // In core, we use `spanIsSampled`, which just looks at the trace flags
548
+ // but in OTEL, we use a slightly more complex logic to be able to differntiate between unsampled and deferred sampling
549
+ if (hasTracingEnabled()) {
550
+ const sampled = getSamplingDecision(rootSpan.spanContext());
551
+ dsc.sampled = sampled == undefined ? undefined : String(sampled);
502
552
  }
503
553
  });
504
554
  }
@@ -507,7 +557,6 @@ function enhanceDscWithOpenTelemetryRootSpanName(client) {
507
557
  * Generate a TraceState for the given data.
508
558
  */
509
559
  function makeTraceState({
510
- parentSpanId,
511
560
  dsc,
512
561
  sampled,
513
562
  }
@@ -516,11 +565,7 @@ function makeTraceState({
516
565
  // We store the DSC as OTEL trace state on the span context
517
566
  const dscString = dsc ? dynamicSamplingContextToSentryBaggageHeader(dsc) : undefined;
518
567
 
519
- // We _always_ set the parent span ID, even if it is empty
520
- // If we'd set this to 'undefined' we could not know if the trace state was set, but there was no parentSpanId,
521
- // vs the trace state was not set at all (in which case we want to do fallback handling)
522
- // If `''`, it should be considered "no parent"
523
- const traceStateBase = new TraceState().set(SENTRY_TRACE_STATE_PARENT_SPAN_ID, parentSpanId || '');
568
+ const traceStateBase = new TraceState();
524
569
 
525
570
  const traceStateWithDsc = dscString ? traceStateBase.set(SENTRY_TRACE_STATE_DSC, dscString) : traceStateBase;
526
571
 
@@ -535,10 +580,9 @@ function makeTraceState({
535
580
  *
536
581
  * @deprecated This function is deprecated and will be removed in the next major version.
537
582
  */
538
- function generateSpanContextForPropagationContext$1(propagationContext) {
583
+ function generateSpanContextForPropagationContext(propagationContext) {
539
584
  // We store the DSC as OTEL trace state on the span context
540
585
  const traceState = makeTraceState({
541
- parentSpanId: propagationContext.parentSpanId,
542
586
  dsc: propagationContext.dsc,
543
587
  sampled: propagationContext.sampled,
544
588
  });
@@ -569,46 +613,6 @@ function getActiveSpan() {
569
613
  */
570
614
  const DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);
571
615
 
572
- function _optionalChain$7(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
573
-
574
- /**
575
- * OpenTelemetry only knows about SAMPLED or NONE decision,
576
- * but for us it is important to differentiate between unset and unsampled.
577
- *
578
- * Both of these are identified as `traceFlags === TracegFlags.NONE`,
579
- * but we additionally look at a special trace state to differentiate between them.
580
- */
581
- function getSamplingDecision(spanContext) {
582
- const { traceFlags, traceState } = spanContext;
583
-
584
- const sampledNotRecording = traceState ? traceState.get(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING) === '1' : false;
585
-
586
- // If trace flag is `SAMPLED`, we interpret this as sampled
587
- // If it is `NONE`, it could mean either it was sampled to be not recorder, or that it was not sampled at all
588
- // For us this is an important difference, sow e look at the SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING
589
- // to identify which it is
590
- if (traceFlags === TraceFlags.SAMPLED) {
591
- return true;
592
- }
593
-
594
- if (sampledNotRecording) {
595
- return false;
596
- }
597
-
598
- // Fall back to DSC as a last resort, that may also contain `sampled`...
599
- const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : undefined;
600
- const dsc = dscString ? baggageHeaderToDynamicSamplingContext(dscString) : undefined;
601
-
602
- if (_optionalChain$7([dsc, 'optionalAccess', _ => _.sampled]) === 'true') {
603
- return true;
604
- }
605
- if (_optionalChain$7([dsc, 'optionalAccess', _2 => _2.sampled]) === 'false') {
606
- return false;
607
- }
608
-
609
- return undefined;
610
- }
611
-
612
616
  const setupElements = new Set();
613
617
 
614
618
  /** Get all the OpenTelemetry elements that have been set up. */
@@ -621,7 +625,7 @@ function setIsSetup(element) {
621
625
  setupElements.add(element);
622
626
  }
623
627
 
624
- function _optionalChain$6(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
628
+ function _optionalChain$4(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
625
629
 
626
630
  /** Get the Sentry propagation context from a span context. */
627
631
  function getPropagationContextFromSpan(span) {
@@ -633,8 +637,7 @@ function getPropagationContextFromSpan(span) {
633
637
  const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : undefined;
634
638
  const traceStateDsc = dscString ? baggageHeaderToDynamicSamplingContext(dscString) : undefined;
635
639
 
636
- const parentSpanId = traceState ? traceState.get(SENTRY_TRACE_STATE_PARENT_SPAN_ID) || undefined : undefined;
637
-
640
+ const parentSpanId = spanHasParentId(span) ? span.parentSpanId : undefined;
638
641
  const sampled = getSamplingDecision(spanContext);
639
642
 
640
643
  // No trace state? --> Take DSC from root span
@@ -675,7 +678,7 @@ class SentryPropagator extends W3CBaggagePropagator {
675
678
  const activeSpan = trace.getSpan(context);
676
679
  const url = activeSpan && getCurrentURL(activeSpan);
677
680
 
678
- const tracePropagationTargets = _optionalChain$6([getClient, 'call', _ => _(), 'optionalAccess', _2 => _2.getOptions, 'call', _3 => _3(), 'optionalAccess', _4 => _4.tracePropagationTargets]);
681
+ const tracePropagationTargets = _optionalChain$4([getClient, 'call', _ => _(), 'optionalAccess', _2 => _2.getOptions, 'call', _3 => _3(), 'optionalAccess', _4 => _4.tracePropagationTargets]);
679
682
  if (!shouldPropagateTraceForUrl(url, tracePropagationTargets, this._urlMatchesTargetsMap)) {
680
683
  DEBUG_BUILD &&
681
684
  logger.log(
@@ -730,20 +733,9 @@ class SentryPropagator extends W3CBaggagePropagator {
730
733
  : maybeSentryTraceHeader
731
734
  : undefined;
732
735
 
733
- const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);
734
-
735
736
  // Add remote parent span context
736
- const ctxWithSpanContext = getContextWithRemoteActiveSpan(context, { sentryTrace, baggage });
737
-
738
- // Also update the scope on the context (to be sure this is picked up everywhere)
739
- const scopes = getScopesFromContext(ctxWithSpanContext);
740
- const newScopes = {
741
- scope: scopes ? scopes.scope.clone() : getCurrentScope().clone(),
742
- isolationScope: scopes ? scopes.isolationScope : getIsolationScope(),
743
- };
744
- newScopes.scope.setPropagationContext(propagationContext);
745
-
746
- return setScopesOnContext(ctxWithSpanContext, newScopes);
737
+ // If there is no incoming trace, this will return the context as-is
738
+ return ensureScopesOnContext(getContextWithRemoteActiveSpan(context, { sentryTrace, baggage }));
747
739
  }
748
740
 
749
741
  /**
@@ -771,14 +763,14 @@ function shouldPropagateTraceForUrl(
771
763
  return true;
772
764
  }
773
765
 
774
- const cachedDecision = _optionalChain$6([decisionMap, 'optionalAccess', _5 => _5.get, 'call', _6 => _6(url)]);
766
+ const cachedDecision = _optionalChain$4([decisionMap, 'optionalAccess', _5 => _5.get, 'call', _6 => _6(url)]);
775
767
  if (cachedDecision !== undefined) {
776
768
  DEBUG_BUILD && !cachedDecision && logger.log(NOT_PROPAGATED_MESSAGE, url);
777
769
  return cachedDecision;
778
770
  }
779
771
 
780
772
  const decision = stringMatchesSomePattern(url, tracePropagationTargets);
781
- _optionalChain$6([decisionMap, 'optionalAccess', _7 => _7.set, 'call', _8 => _8(url, decision)]);
773
+ _optionalChain$4([decisionMap, 'optionalAccess', _7 => _7.set, 'call', _8 => _8(url, decision)]);
782
774
 
783
775
  DEBUG_BUILD && !decision && logger.log(NOT_PROPAGATED_MESSAGE, url);
784
776
  return decision;
@@ -791,13 +783,28 @@ function getInjectionData(context)
791
783
 
792
784
  {
793
785
  const span = trace.getSpan(context);
794
- const spanIsRemote = _optionalChain$6([span, 'optionalAccess', _9 => _9.spanContext, 'call', _10 => _10(), 'access', _11 => _11.isRemote]);
795
786
 
796
- // If we have a local span, we can just pick everything from it
797
- if (span && !spanIsRemote) {
787
+ // If we have a remote span, the spanId should be considered as the parentSpanId, not spanId itself
788
+ // Instead, we use a virtual (generated) spanId for propagation
789
+ if (span && span.spanContext().isRemote) {
798
790
  const spanContext = span.spanContext();
791
+ const dynamicSamplingContext = getDynamicSamplingContextFromSpan(span);
792
+
793
+ return {
794
+ dynamicSamplingContext,
795
+ traceId: spanContext.traceId,
796
+ // Because this is a remote span, we do not want to propagate this directly
797
+ // As otherwise things may be attached "directly" to an unrelated span
798
+ spanId: generateSpanId(),
799
+ sampled: getSamplingDecision(spanContext),
800
+ };
801
+ }
799
802
 
803
+ // If we have a local span, we just use this
804
+ if (span) {
805
+ const spanContext = span.spanContext();
800
806
  const dynamicSamplingContext = getDynamicSamplingContextFromSpan(span);
807
+
801
808
  return {
802
809
  dynamicSamplingContext,
803
810
  traceId: spanContext.traceId,
@@ -807,7 +814,8 @@ function getInjectionData(context)
807
814
  }
808
815
 
809
816
  // Else we try to use the propagation context from the scope
810
- const scope = _optionalChain$6([getScopesFromContext, 'call', _12 => _12(context), 'optionalAccess', _13 => _13.scope]) || getCurrentScope();
817
+ // The only scenario where this should happen is when we neither have a span, nor an incoming trace
818
+ const scope = _optionalChain$4([getScopesFromContext, 'call', _9 => _9(context), 'optionalAccess', _10 => _10.scope]) || getCurrentScope();
811
819
  const client = getClient();
812
820
 
813
821
  const propagationContext = scope.getPropagationContext();
@@ -828,7 +836,21 @@ function getContextWithRemoteActiveSpan(
828
836
  ) {
829
837
  const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);
830
838
 
831
- const spanContext = generateSpanContextForPropagationContext(propagationContext);
839
+ const { traceId, parentSpanId, sampled, dsc } = propagationContext;
840
+
841
+ // We only want to set the virtual span if we are continuing a concrete trace
842
+ // Otherwise, we ignore the incoming trace here, e.g. if we have no trace headers
843
+ if (!parentSpanId) {
844
+ return ctx;
845
+ }
846
+
847
+ const spanContext = generateRemoteSpanContext({
848
+ traceId,
849
+ spanId: parentSpanId,
850
+ sampled,
851
+ dsc,
852
+ });
853
+
832
854
  return trace.setSpanContext(ctx, spanContext);
833
855
  }
834
856
 
@@ -841,11 +863,24 @@ function continueTraceAsRemoteSpan(
841
863
  options,
842
864
  callback,
843
865
  ) {
844
- const ctxWithSpanContext = getContextWithRemoteActiveSpan(ctx, options);
866
+ const ctxWithSpanContext = ensureScopesOnContext(getContextWithRemoteActiveSpan(ctx, options));
845
867
 
846
868
  return context.with(ctxWithSpanContext, callback);
847
869
  }
848
870
 
871
+ function ensureScopesOnContext(ctx) {
872
+ // If there are no scopes yet on the context, ensure we have them
873
+ const scopes = getScopesFromContext(ctx);
874
+ const newScopes = {
875
+ // If we have no scope here, this is most likely either the root context or a context manually derived from it
876
+ // In this case, we want to fork the current scope, to ensure we do not pollute the root scope
877
+ scope: scopes ? scopes.scope : getCurrentScope().clone(),
878
+ isolationScope: scopes ? scopes.isolationScope : getIsolationScope(),
879
+ };
880
+
881
+ return setScopesOnContext(ctx, newScopes);
882
+ }
883
+
849
884
  /** Try to get the existing baggage header so we can merge this in. */
850
885
  function getExistingBaggage(carrier) {
851
886
  try {
@@ -869,13 +904,13 @@ function getCurrentURL(span) {
869
904
  const spanData = spanToJSON(span).data;
870
905
  // `ATTR_URL_FULL` is the new attribute, but we still support the old one, `SEMATTRS_HTTP_URL`, for now.
871
906
  // eslint-disable-next-line deprecation/deprecation
872
- const urlAttribute = _optionalChain$6([spanData, 'optionalAccess', _14 => _14[SEMATTRS_HTTP_URL]]) || _optionalChain$6([spanData, 'optionalAccess', _15 => _15[ATTR_URL_FULL]]);
907
+ const urlAttribute = _optionalChain$4([spanData, 'optionalAccess', _11 => _11[SEMATTRS_HTTP_URL]]) || _optionalChain$4([spanData, 'optionalAccess', _12 => _12[ATTR_URL_FULL]]);
873
908
  if (urlAttribute) {
874
909
  return urlAttribute;
875
910
  }
876
911
 
877
912
  // Also look at the traceState, which we may set in the sampler even for unsampled spans
878
- const urlTraceState = _optionalChain$6([span, 'access', _16 => _16.spanContext, 'call', _17 => _17(), 'access', _18 => _18.traceState, 'optionalAccess', _19 => _19.get, 'call', _20 => _20(SENTRY_TRACE_STATE_URL)]);
913
+ const urlTraceState = _optionalChain$4([span, 'access', _13 => _13.spanContext, 'call', _14 => _14(), 'access', _15 => _15.traceState, 'optionalAccess', _16 => _16.get, 'call', _17 => _17(SENTRY_TRACE_STATE_URL)]);
879
914
  if (urlTraceState) {
880
915
  return urlTraceState;
881
916
  }
@@ -883,28 +918,31 @@ function getCurrentURL(span) {
883
918
  return undefined;
884
919
  }
885
920
 
886
- // TODO: Adjust this behavior to avoid invalid spans
887
- function generateSpanContextForPropagationContext(propagationContext) {
921
+ function generateRemoteSpanContext({
922
+ spanId,
923
+ traceId,
924
+ sampled,
925
+ dsc,
926
+ }
927
+
928
+ ) {
888
929
  // We store the DSC as OTEL trace state on the span context
889
930
  const traceState = makeTraceState({
890
- parentSpanId: propagationContext.parentSpanId,
891
- dsc: propagationContext.dsc,
892
- sampled: propagationContext.sampled,
931
+ dsc,
932
+ sampled,
893
933
  });
894
934
 
895
935
  const spanContext = {
896
- traceId: propagationContext.traceId,
897
- spanId: propagationContext.parentSpanId || '',
936
+ traceId,
937
+ spanId,
898
938
  isRemote: true,
899
- traceFlags: propagationContext.sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,
939
+ traceFlags: sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,
900
940
  traceState,
901
941
  };
902
942
 
903
943
  return spanContext;
904
944
  }
905
945
 
906
- function _optionalChain$5(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
907
-
908
946
  /**
909
947
  * Wraps a function with a transaction/span and finishes the span after the function is done.
910
948
  * The created span is the active span and will be used as parent by other spans created inside the function
@@ -1061,40 +1099,11 @@ function ensureTimestampInMilliseconds(timestamp) {
1061
1099
 
1062
1100
  function getContext(scope, forceTransaction) {
1063
1101
  const ctx = getContextForScope(scope);
1064
- // Note: If the context is the ROOT_CONTEXT, no scope is attached
1065
- // Thus we will not use the propagation context in this case, which is desired
1066
- const actualScope = _optionalChain$5([getScopesFromContext, 'call', _ => _(ctx), 'optionalAccess', _2 => _2.scope]);
1067
1102
  const parentSpan = trace.getSpan(ctx);
1068
1103
 
1069
- // In the case that we have no parent span, we need to "simulate" one to ensure the propagation context is correct
1104
+ // In the case that we have no parent span, we start a new trace
1105
+ // Note that if we continue a trace, we'll always have a remote parent span here anyhow
1070
1106
  if (!parentSpan) {
1071
- const client = getClient();
1072
-
1073
- if (actualScope && client) {
1074
- const propagationContext = actualScope.getPropagationContext();
1075
-
1076
- // We store the DSC as OTEL trace state on the span context
1077
- const traceState = makeTraceState({
1078
- parentSpanId: propagationContext.parentSpanId,
1079
- // Not defined yet, we want to pick this up on-demand only
1080
- dsc: undefined,
1081
- sampled: propagationContext.sampled,
1082
- });
1083
-
1084
- const spanOptions = {
1085
- traceId: propagationContext.traceId,
1086
- // eslint-disable-next-line deprecation/deprecation
1087
- spanId: propagationContext.parentSpanId || propagationContext.spanId,
1088
- isRemote: true,
1089
- traceFlags: propagationContext.sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,
1090
- traceState,
1091
- };
1092
-
1093
- // Add remote parent span context,
1094
- return trace.setSpanContext(ctx, spanOptions);
1095
- }
1096
-
1097
- // if we have no scope or client, we just return the context as-is
1098
1107
  return ctx;
1099
1108
  }
1100
1109
 
@@ -1120,7 +1129,6 @@ function getContext(scope, forceTransaction) {
1120
1129
 
1121
1130
  const traceState = makeTraceState({
1122
1131
  dsc,
1123
- parentSpanId: spanId !== INVALID_SPANID ? spanId : undefined,
1124
1132
  sampled,
1125
1133
  });
1126
1134
 
@@ -1198,8 +1206,6 @@ function suppressTracing(callback) {
1198
1206
  return context.with(ctx, callback);
1199
1207
  }
1200
1208
 
1201
- function _optionalChain$4(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
1202
-
1203
1209
  /** Ensure the `trace` context is set on all events. */
1204
1210
  function setupEventContextTrace(client) {
1205
1211
  client.on('preprocessEvent', event => {
@@ -1210,25 +1216,9 @@ function setupEventContextTrace(client) {
1210
1216
  return;
1211
1217
  }
1212
1218
 
1213
- const spanContext = span.spanContext();
1214
-
1215
- // If we have a parent span id from trace state, use that ('' means no parent should be used)
1216
- // Else, pick the one from the span
1217
- const parentSpanIdFromTraceState = _optionalChain$4([spanContext, 'access', _ => _.traceState, 'optionalAccess', _2 => _2.get, 'call', _3 => _3(SENTRY_TRACE_STATE_PARENT_SPAN_ID)]);
1218
- const parent_span_id =
1219
- typeof parentSpanIdFromTraceState === 'string'
1220
- ? parentSpanIdFromTraceState || undefined
1221
- : spanHasParentId(span)
1222
- ? span.parentSpanId
1223
- : undefined;
1224
-
1225
1219
  // If event has already set `trace` context, use that one.
1226
1220
  event.contexts = {
1227
- trace: dropUndefinedKeys({
1228
- trace_id: spanContext.traceId,
1229
- span_id: spanContext.spanId,
1230
- parent_span_id,
1231
- }),
1221
+ trace: spanToTraceContext(span),
1232
1222
  ...event.contexts,
1233
1223
  };
1234
1224
 
@@ -1688,7 +1678,9 @@ class SentrySpanExporter {
1688
1678
  const remainingOpenSpanCount = finishedSpans.length - sentSpanCount;
1689
1679
 
1690
1680
  DEBUG_BUILD &&
1691
- logger.log(`SpanExporter exported ${sentSpanCount} spans, ${remainingOpenSpanCount} unsent spans remaining`);
1681
+ logger.log(
1682
+ `SpanExporter exported ${sentSpanCount} spans, ${remainingOpenSpanCount} spans are waiting for their parent spans to finish`,
1683
+ );
1692
1684
 
1693
1685
  sentSpans.forEach(span => {
1694
1686
  const bucketEntry = this._spansToBucketEntry.get(span);
@@ -1776,6 +1768,7 @@ function parseSpan(span) {
1776
1768
  return { origin, op, source };
1777
1769
  }
1778
1770
 
1771
+ /** Exported only for tests. */
1779
1772
  function createTransactionForOtelSpan(span) {
1780
1773
  const { op, description, data, origin = 'manual', source } = getSpanData(span);
1781
1774
  const capturedSpanScopes = getCapturedScopesOnSpan(span );
@@ -1793,15 +1786,12 @@ function createTransactionForOtelSpan(span) {
1793
1786
 
1794
1787
  const { traceId: trace_id, spanId: span_id } = span.spanContext();
1795
1788
 
1796
- const parentSpanIdFromTraceState = _optionalChain$2([span, 'access', _2 => _2.spanContext, 'call', _3 => _3(), 'access', _4 => _4.traceState, 'optionalAccess', _5 => _5.get, 'call', _6 => _6(SENTRY_TRACE_STATE_PARENT_SPAN_ID)]);
1797
-
1798
1789
  // If parentSpanIdFromTraceState is defined at all, we want it to take precedence
1799
1790
  // In that case, an empty string should be interpreted as "no parent span id",
1800
1791
  // even if `span.parentSpanId` is set
1801
1792
  // this is the case when we are starting a new trace, where we have a virtual span based on the propagationContext
1802
1793
  // We only want to continue the traceId in this case, but ignore the parent span
1803
- const parent_span_id =
1804
- typeof parentSpanIdFromTraceState === 'string' ? parentSpanIdFromTraceState || undefined : span.parentSpanId;
1794
+ const parent_span_id = span.parentSpanId;
1805
1795
 
1806
1796
  const status = mapStatus(span);
1807
1797
 
@@ -1815,12 +1805,16 @@ function createTransactionForOtelSpan(span) {
1815
1805
  status: getStatusMessage(status), // As per protocol, span status is allowed to be undefined
1816
1806
  });
1817
1807
 
1818
- const transactionEvent = {
1808
+ const statusCode = attributes[ATTR_HTTP_RESPONSE_STATUS_CODE];
1809
+ const responseContext = typeof statusCode === 'number' ? { response: { status_code: statusCode } } : undefined;
1810
+
1811
+ const transactionEvent = dropUndefinedKeys({
1819
1812
  contexts: {
1820
1813
  trace: traceContext,
1821
1814
  otel: {
1822
1815
  resource: span.resource.attributes,
1823
1816
  },
1817
+ ...responseContext,
1824
1818
  },
1825
1819
  spans: [],
1826
1820
  start_timestamp: spanTimeInputToSeconds(span.startTime),
@@ -1841,7 +1835,7 @@ function createTransactionForOtelSpan(span) {
1841
1835
  },
1842
1836
  }),
1843
1837
  _metrics_summary: getMetricSummaryJsonForSpan(span ),
1844
- };
1838
+ });
1845
1839
 
1846
1840
  return transactionEvent;
1847
1841
  }
@@ -2257,5 +2251,5 @@ function addOpenTelemetryInstrumentation(...instrumentations) {
2257
2251
  });
2258
2252
  }
2259
2253
 
2260
- export { SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION, SentryPropagator, SentrySampler, SentrySpanProcessor, addOpenTelemetryInstrumentation, continueTrace, enhanceDscWithOpenTelemetryRootSpanName, generateSpanContextForPropagationContext$1 as generateSpanContextForPropagationContext, getActiveSpan, getPropagationContextFromSpan, getRequestSpanData, getScopesFromContext, getSpanKind, getTraceContextForScope, isSentryRequestSpan, openTelemetrySetupCheck, setOpenTelemetryContextAsyncContextStrategy, setupEventContextTrace, shouldPropagateTraceForUrl, spanHasAttributes, spanHasEvents, spanHasKind, spanHasName, spanHasParentId, spanHasStatus, startInactiveSpan, startSpan, startSpanManual, suppressTracing, withActiveSpan, wrapClientClass, wrapContextManagerClass, wrapSamplingDecision };
2254
+ export { SEMANTIC_ATTRIBUTE_SENTRY_GRAPHQL_OPERATION, SentryPropagator, SentrySampler, SentrySpanProcessor, addOpenTelemetryInstrumentation, continueTrace, enhanceDscWithOpenTelemetryRootSpanName, generateSpanContextForPropagationContext, getActiveSpan, getPropagationContextFromSpan, getRequestSpanData, getScopesFromContext, getSpanKind, getTraceContextForScope, isSentryRequestSpan, openTelemetrySetupCheck, setOpenTelemetryContextAsyncContextStrategy, setupEventContextTrace, shouldPropagateTraceForUrl, spanHasAttributes, spanHasEvents, spanHasKind, spanHasName, spanHasParentId, spanHasStatus, startInactiveSpan, startSpan, startSpanManual, suppressTracing, withActiveSpan, wrapClientClass, wrapContextManagerClass, wrapSamplingDecision };
2261
2255
  //# sourceMappingURL=index.js.map