Skip to content

Commit 8496fb2

Browse files
authored
Simplify and speed up trace context parsing (#708)
* chore: simplify and speed up trace context parsing
1 parent 104ce02 commit 8496fb2

File tree

1 file changed

+10
-27
lines changed

1 file changed

+10
-27
lines changed

packages/opentelemetry-core/src/context/propagation/HttpTraceContext.ts

Lines changed: 10 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -14,15 +14,12 @@
1414
* limitations under the License.
1515
*/
1616

17-
import { SpanContext, HttpTextFormat, TraceFlags } from '@opentelemetry/types';
17+
import { HttpTextFormat, SpanContext, TraceFlags } from '@opentelemetry/types';
1818
import { TraceState } from '../../trace/TraceState';
1919

2020
export const TRACE_PARENT_HEADER = 'traceparent';
2121
export const TRACE_STATE_HEADER = 'tracestate';
22-
const VALID_TRACE_PARENT_REGEX = /^[\da-f]{2}-[\da-f]{32}-[\da-f]{16}-[\da-f]{2}$/;
23-
const VALID_TRACEID_REGEX = /^[0-9a-f]{32}$/i;
24-
const VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i;
25-
const INVALID_ID_REGEX = /^0+$/i;
22+
const VALID_TRACE_PARENT_REGEX = /^00-([\da-f]{32})-([\da-f]{16})-([\da-f]{2})$/;
2623
const VERSION = '00';
2724

2825
/**
@@ -37,33 +34,19 @@ const VERSION = '00';
3734
*/
3835
export function parseTraceParent(traceParent: string): SpanContext | null {
3936
const match = traceParent.match(VALID_TRACE_PARENT_REGEX);
40-
if (!match) return null;
41-
const parts = traceParent.split('-');
42-
const [version, traceId, spanId, option] = parts;
43-
// tslint:disable-next-line:ban Needed to parse hexadecimal.
44-
const traceFlags = parseInt(option, 16);
45-
4637
if (
47-
!isValidVersion(version) ||
48-
!isValidTraceId(traceId) ||
49-
!isValidSpanId(spanId)
38+
!match ||
39+
match[1] === '00000000000000000000000000000000' ||
40+
match[2] === '0000000000000000'
5041
) {
5142
return null;
5243
}
5344

54-
return { traceId, spanId, traceFlags };
55-
}
56-
57-
function isValidVersion(version: string): boolean {
58-
return version === VERSION;
59-
}
60-
61-
function isValidTraceId(traceId: string): boolean {
62-
return VALID_TRACEID_REGEX.test(traceId) && !INVALID_ID_REGEX.test(traceId);
63-
}
64-
65-
function isValidSpanId(spanId: string): boolean {
66-
return VALID_SPANID_REGEX.test(spanId) && !INVALID_ID_REGEX.test(spanId);
45+
return {
46+
traceId: match[1],
47+
spanId: match[2],
48+
traceFlags: parseInt(match[3], 16),
49+
};
6750
}
6851

6952
/**

0 commit comments

Comments
 (0)