From 8eda5a8f5df9da1473617b77a2c1af11fdf151af Mon Sep 17 00:00:00 2001 From: Bastian Krol Date: Mon, 4 Jul 2022 16:22:39 +0200 Subject: [PATCH] fix(propagator-ot-trace): read sampled flag correctly from span context The way the sampled flag is currently read from the span context will break when more flags are introduced. This is mentioned explicitly in the [specification](https://www.w3.org/TR/trace-context/#trace-flags). --- .../src/OTTracePropagator.ts | 4 +++- .../test/OTTracePropagator.test.ts | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/propagators/opentelemetry-propagator-ot-trace/src/OTTracePropagator.ts b/propagators/opentelemetry-propagator-ot-trace/src/OTTracePropagator.ts index d1c001684c..056e9868e4 100644 --- a/propagators/opentelemetry-propagator-ot-trace/src/OTTracePropagator.ts +++ b/propagators/opentelemetry-propagator-ot-trace/src/OTTracePropagator.ts @@ -72,7 +72,9 @@ export class OTTracePropagator implements TextMapPropagator { setter.set( carrier, OT_SAMPLED_HEADER, - spanContext.traceFlags === TraceFlags.SAMPLED ? 'true' : 'false' + (spanContext.traceFlags & TraceFlags.SAMPLED) === TraceFlags.SAMPLED + ? 'true' + : 'false' ); const baggage = propagation.getBaggage(context); diff --git a/propagators/opentelemetry-propagator-ot-trace/test/OTTracePropagator.test.ts b/propagators/opentelemetry-propagator-ot-trace/test/OTTracePropagator.test.ts index 62ce5e3bde..d07b3d3eb2 100644 --- a/propagators/opentelemetry-propagator-ot-trace/test/OTTracePropagator.test.ts +++ b/propagators/opentelemetry-propagator-ot-trace/test/OTTracePropagator.test.ts @@ -78,6 +78,25 @@ describe('OTTracePropagator', () => { assert.strictEqual(carrier[OT_SAMPLED_HEADER], 'true'); }); + it('correctly reads the sampled flag even if other flags are set', () => { + const spanContext: SpanContext = { + traceId: '80f198ee56343ba864fe8b2a57d3eff7', + spanId: 'e457b5a2e4d86bd1', + // 81 = 1000 0001, so this sets the sampled flag (rightmost bit) and one other flag (leftmost bit, semantics unspecified at the time of writing) + traceFlags: 81, + }; + + propagator.inject( + trace.setSpan(ROOT_CONTEXT, trace.wrapSpanContext(spanContext)), + carrier, + defaultTextMapSetter + ); + + assert.strictEqual(carrier[OT_TRACE_ID_HEADER], '64fe8b2a57d3eff7'); + assert.strictEqual(carrier[OT_SPAN_ID_HEADER], 'e457b5a2e4d86bd1'); + assert.strictEqual(carrier[OT_SAMPLED_HEADER], 'true'); + }); + it('injects context with unspecified trace flags', () => { const spanContext: SpanContext = { traceId: '80f198ee56343ba864fe8b2a57d3eff7',