From d02175632aef15a739d5289ca994cab0ca0f0581 Mon Sep 17 00:00:00 2001 From: Giovanni Liva Date: Wed, 28 Apr 2021 14:21:26 +0200 Subject: [PATCH] Fix ParentBasedSampler --- .../src/trace/sampler/ParentBasedSampler.ts | 3 +- .../test/trace/ParentBasedSampler.test.ts | 36 +++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/packages/opentelemetry-core/src/trace/sampler/ParentBasedSampler.ts b/packages/opentelemetry-core/src/trace/sampler/ParentBasedSampler.ts index 4cd5c4f871..a20f9ba181 100644 --- a/packages/opentelemetry-core/src/trace/sampler/ParentBasedSampler.ts +++ b/packages/opentelemetry-core/src/trace/sampler/ParentBasedSampler.ts @@ -18,6 +18,7 @@ import { SpanAttributes, Context, getSpanContext, + isSpanContextValid, Link, Sampler, SamplingResult, @@ -69,7 +70,7 @@ export class ParentBasedSampler implements Sampler { ): SamplingResult { const parentContext = getSpanContext(context); - if (!parentContext) { + if (!parentContext || !isSpanContextValid(parentContext)) { return this._root.shouldSample( context, traceId, diff --git a/packages/opentelemetry-core/test/trace/ParentBasedSampler.test.ts b/packages/opentelemetry-core/test/trace/ParentBasedSampler.test.ts index e6c388ebe7..4394227de4 100644 --- a/packages/opentelemetry-core/test/trace/ParentBasedSampler.test.ts +++ b/packages/opentelemetry-core/test/trace/ParentBasedSampler.test.ts @@ -71,6 +71,24 @@ describe('ParentBasedSampler', () => { ); }); + it('should return api.SamplingDecision.RECORD_AND_SAMPLED for invalid parent spanContext while composited with AlwaysOnSampler', () => { + const sampler = new ParentBasedSampler({ root: new AlwaysOnSampler() }); + + assert.deepStrictEqual( + sampler.shouldSample( + setSpanContext(api.ROOT_CONTEXT, api.INVALID_SPAN_CONTEXT), + traceId, + spanName, + SpanKind.CLIENT, + {}, + [] + ), + { + decision: api.SamplingDecision.RECORD_AND_SAMPLED, + } + ); + }); + it('should return api.SamplingDecision.RECORD_AND_SAMPLED while composited with AlwaysOnSampler', () => { const sampler = new ParentBasedSampler({ root: new AlwaysOnSampler() }); @@ -112,6 +130,24 @@ describe('ParentBasedSampler', () => { ); }); + it('should return api.SamplingDecision.NOT_RECORD for invalid parent spanContext while composited with AlwaysOffSampler', () => { + const sampler = new ParentBasedSampler({ root: new AlwaysOffSampler() }); + + assert.deepStrictEqual( + sampler.shouldSample( + setSpanContext(api.ROOT_CONTEXT, api.INVALID_SPAN_CONTEXT), + traceId, + spanName, + SpanKind.CLIENT, + {}, + [] + ), + { + decision: api.SamplingDecision.NOT_RECORD, + } + ); + }); + it('should return api.SamplingDecision.RECORD_AND_SAMPLED while composited with AlwaysOffSampler', () => { const sampler = new ParentBasedSampler({ root: new AlwaysOffSampler() });