UNPKG

3.02 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.extractTraceContext = exports.traceContext = void 0;
4const async_hooks_1 = require("async_hooks");
5/* @internal */
6exports.traceContext = new async_hooks_1.AsyncLocalStorage();
7/**
8 * A regex to match the Cloud Trace header.
9 * - ([A-Fa-f0-9]{32}): The trace id, a 32 character hex value. (e.g. 4bf92f3577b34da6a3ce929d0e0e4736)
10 * - ([0-9]+): The parent span id, a 64 bit integer. (e.g. 00f067aa0ba902b7)
11 * - (?:;o=([0-3])): The trace mask, 1-3 denote it should be traced.
12 */
13const CLOUD_TRACE_REGEX = new RegExp("^(?<traceId>[A-Fa-f0-9]{32})/" + "(?<parentIdInt>[0-9]+)" + "(?:;o=(?<traceMask>[0-3]))?$");
14const CLOUD_TRACE_HEADER = "X-Cloud-Trace-Context";
15function matchCloudTraceHeader(carrier) {
16 let header = carrier === null || carrier === void 0 ? void 0 : carrier[CLOUD_TRACE_HEADER];
17 if (!header) {
18 // try lowercase header
19 header = carrier === null || carrier === void 0 ? void 0 : carrier[CLOUD_TRACE_HEADER.toLowerCase()];
20 }
21 if (header && typeof header === "string") {
22 const matches = CLOUD_TRACE_REGEX.exec(header);
23 if (matches && matches.groups) {
24 const { traceId, parentIdInt, traceMask } = matches.groups;
25 // Convert parentId from unsigned int to hex
26 const parentId = parseInt(parentIdInt);
27 if (isNaN(parentId)) {
28 // Ignore traces with invalid parentIds
29 return;
30 }
31 const sample = !!traceMask && traceMask !== "0";
32 return { traceId, parentId: parentId.toString(16), sample, version: "00" };
33 }
34 }
35}
36/**
37 * A regex to match the traceparent header.
38 * - ^([a-f0-9]{2}): The specification version (e.g. 00)
39 * - ([a-f0-9]{32}): The trace id, a 16-byte array. (e.g. 4bf92f3577b34da6a3ce929d0e0e4736)
40 * - ([a-f0-9]{16}): The parent span id, an 8-byte array. (e.g. 00f067aa0ba902b7)
41 * - ([a-f0-9]{2}: The sampled flag. (e.g. 00)
42 */
43const TRACEPARENT_REGEX = new RegExp("^(?<version>[a-f0-9]{2})-" +
44 "(?<traceId>[a-f0-9]{32})-" +
45 "(?<parentId>[a-f0-9]{16})-" +
46 "(?<flag>[a-f0-9]{2})$");
47const TRACEPARENT_HEADER = "traceparent";
48function matchTraceparentHeader(carrier) {
49 const header = carrier === null || carrier === void 0 ? void 0 : carrier[TRACEPARENT_HEADER];
50 if (header && typeof header === "string") {
51 const matches = TRACEPARENT_REGEX.exec(header);
52 if (matches && matches.groups) {
53 const { version, traceId, parentId, flag } = matches.groups;
54 const sample = flag === "01";
55 return { traceId, parentId, sample, version };
56 }
57 }
58}
59/**
60 * Extracts trace context from given carrier object, if any.
61 *
62 * Supports Cloud Trace and traceparent format.
63 *
64 * @param carrier
65 */
66function extractTraceContext(carrier) {
67 return matchCloudTraceHeader(carrier) || matchTraceparentHeader(carrier);
68}
69exports.extractTraceContext = extractTraceContext;