Skip to content

Commit

Permalink
fix: left pad short b3 trace identifiers (#1021)
Browse files Browse the repository at this point in the history
  • Loading branch information
dyladan committed May 5, 2020
1 parent b1ea454 commit a5444dc
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import { getParentSpanContext, setExtractedSpanContext } from '../context';
export const X_B3_TRACE_ID = 'x-b3-traceid';
export const X_B3_SPAN_ID = 'x-b3-spanid';
export const X_B3_SAMPLED = 'x-b3-sampled';
const VALID_TRACEID_REGEX = /^[0-9a-f]{32}$/i;
const VALID_TRACEID_REGEX = /^([0-9a-f]{16}){1,2}$/i;
const VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i;
const INVALID_ID_REGEX = /^0+$/i;

Expand Down Expand Up @@ -72,16 +72,21 @@ export class B3Propagator implements HttpTextPropagator {
const traceIdHeader = getter(carrier, X_B3_TRACE_ID);
const spanIdHeader = getter(carrier, X_B3_SPAN_ID);
const sampledHeader = getter(carrier, X_B3_SAMPLED);
const traceId = Array.isArray(traceIdHeader)

const traceIdHeaderValue = Array.isArray(traceIdHeader)
? traceIdHeader[0]
: traceIdHeader;
const spanId = Array.isArray(spanIdHeader) ? spanIdHeader[0] : spanIdHeader;

const options = Array.isArray(sampledHeader)
? sampledHeader[0]
: sampledHeader;

if (typeof traceId !== 'string' || typeof spanId !== 'string')
if (typeof traceIdHeaderValue !== 'string' || typeof spanId !== 'string') {
return context;
}

const traceId = traceIdHeaderValue.padStart(32, '0');

if (isValidTraceId(traceId) && isValidSpanId(spanId)) {
return setExtractedSpanContext(context, {
Expand Down
16 changes: 16 additions & 0 deletions packages/opentelemetry-core/test/context/B3Propagator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,5 +289,21 @@ describe('B3Propagator', () => {
assert.ok(ctx2 === Context.ROOT_CONTEXT);
assert.ok(ctx3 === Context.ROOT_CONTEXT);
});

it('should left-pad 64 bit trace ids with 0', () => {
carrier[X_B3_TRACE_ID] = '8448eb211c80319c';
carrier[X_B3_SPAN_ID] = 'b7ad6b7169203331';
carrier[X_B3_SAMPLED] = '1';
const extractedSpanContext = getExtractedSpanContext(
b3Propagator.extract(Context.ROOT_CONTEXT, carrier, defaultGetter)
);

assert.deepStrictEqual(extractedSpanContext, {
spanId: 'b7ad6b7169203331',
traceId: '00000000000000008448eb211c80319c',
isRemote: true,
traceFlags: TraceFlags.SAMPLED,
});
});
});
});

0 comments on commit a5444dc

Please sign in to comment.