Skip to content

Commit

Permalink
chore(http-instrumentation): reduce complexity of traceparent header …
Browse files Browse the repository at this point in the history
…parsing
  • Loading branch information
marcbachmann committed Jan 16, 2021
1 parent 471306f commit 8386bb9
Showing 1 changed file with 6 additions and 32 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,7 @@ export const TRACE_PARENT_HEADER = 'traceparent';
export const TRACE_STATE_HEADER = 'tracestate';

const VERSION = '00';
const VERSION_PART_COUNT = 4; // Version 00 only allows the specific 4 fields.

const VERSION_REGEX = /^(?!ff)[\da-f]{2}$/;
const TRACE_ID_REGEX = /^(?![0]{32})[\da-f]{32}$/;
const PARENT_ID_REGEX = /^(?![0]{16})[\da-f]{16}$/;
const FLAGS_REGEX = /^[\da-f]{2}$/;
const TRACE_PARENT_REGEX = /^\s?00-((?![0]{32})[\da-f]{32})-((?![0]{16})[\da-f]{16})-([\da-f]{2})\s?$/;

/**
* Parses information from the [traceparent] span tag and converts it into {@link SpanContext}
Expand All @@ -48,33 +43,12 @@ const FLAGS_REGEX = /^[\da-f]{2}$/;
* For more information see {@link https://www.w3.org/TR/trace-context/}
*/
export function parseTraceParent(traceParent: string): SpanContext | null {
const trimmed = traceParent.trim();
const traceParentParts = trimmed.split('-');

// Current version must be structured correctly.
// For future versions, we can grab just the parts we do support.
if (
traceParentParts[0] === VERSION &&
traceParentParts.length !== VERSION_PART_COUNT
) {
return null;
}

const [version, traceId, parentId, flags] = traceParentParts;
const isValidParent =
VERSION_REGEX.test(version) &&
TRACE_ID_REGEX.test(traceId) &&
PARENT_ID_REGEX.test(parentId) &&
FLAGS_REGEX.test(flags);

if (!isValidParent) {
return null;
}

const match = TRACE_PARENT_REGEX.exec(traceParent);
if (!match) return null;
return {
traceId: traceId,
spanId: parentId,
traceFlags: parseInt(flags, 16),
traceId: match[1],
spanId: match[2],
traceFlags: parseInt(match[3], 16),
};
}

Expand Down

0 comments on commit 8386bb9

Please sign in to comment.