From f44d6a775f5da97c868458e095b526a05d8ff109 Mon Sep 17 00:00:00 2001 From: Francesco Novy Date: Thu, 30 Jan 2025 14:24:16 +0100 Subject: [PATCH] fix(node): Avoid setting `sentry-trace` header multiple times If, for whatever reason, `propagator.inject()` is called multiple times, we do not want to add multiple `sentry-trace` headers. In this case, the first one wins. --- packages/opentelemetry/src/propagator.ts | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/packages/opentelemetry/src/propagator.ts b/packages/opentelemetry/src/propagator.ts index f92331d7739f..c0a448e94e01 100644 --- a/packages/opentelemetry/src/propagator.ts +++ b/packages/opentelemetry/src/propagator.ts @@ -87,7 +87,9 @@ export class SentryPropagator extends W3CBaggagePropagator { } // We also want to avoid setting the default OTEL trace ID, if we get that for whatever reason - if (traceId && traceId !== INVALID_TRACEID) { + // If a sentry-trace header already exists, we do nothing + const existingSentryTrace = getExistingSentryTrace(carrier); + if (traceId && traceId !== INVALID_TRACEID && !existingSentryTrace) { setter.set(carrier, SENTRY_TRACE_HEADER, generateSentryTraceHeader(traceId, spanId, sampled)); } @@ -264,6 +266,16 @@ function getExistingBaggage(carrier: unknown): string | undefined { } } +/** Try to get the existing sentry-trace header. */ +function getExistingSentryTrace(carrier: unknown): string | undefined { + try { + const sentryTrace = (carrier as Record)[SENTRY_TRACE_HEADER]; + return Array.isArray(sentryTrace) ? sentryTrace.join(',') : sentryTrace; + } catch { + return undefined; + } +} + /** * It is pretty tricky to get access to the outgoing request URL of a request in the propagator. * As we only have access to the context of the span to be sent and the carrier (=headers),