UNPKG

@opencensus/propagation-b3

Version:
90 lines 3.26 kB
"use strict"; /** * Copyright 2018, OpenCensus Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.B3Format = exports.NOT_SAMPLED_VALUE = exports.SAMPLED_VALUE = exports.X_B3_SAMPLED = exports.X_B3_PARENT_SPAN_ID = exports.X_B3_SPAN_ID = exports.X_B3_TRACE_ID = void 0; const crypto = require("crypto"); const uuid = require("uuid"); const validators_1 = require("./validators"); exports.X_B3_TRACE_ID = 'x-b3-traceid'; exports.X_B3_SPAN_ID = 'x-b3-spanid'; exports.X_B3_PARENT_SPAN_ID = 'x-b3-parentspanid'; exports.X_B3_SAMPLED = 'x-b3-sampled'; exports.SAMPLED_VALUE = 0x1; exports.NOT_SAMPLED_VALUE = 0x0; /** Propagates span context through B3 Format propagation. */ class B3Format { /** * Gets the trace context from a request headers. If there is no trace context * in the headers, null is returned. * @param getter */ extract(getter) { const traceId = this.parseHeader(getter.getHeader(exports.X_B3_TRACE_ID)); const spanId = this.parseHeader(getter.getHeader(exports.X_B3_SPAN_ID)); const opt = this.parseHeader(getter.getHeader(exports.X_B3_SAMPLED)); if (traceId && spanId) { return { traceId, spanId, options: isNaN(Number(opt)) ? exports.NOT_SAMPLED_VALUE : Number(opt), }; } return null; } /** * Adds a trace context in a request headers. * @param setter * @param spanContext */ inject(setter, spanContext) { if (!spanContext || !validators_1.isValidTraceId(spanContext.traceId) || !validators_1.isValidSpanId(spanContext.spanId)) { return; } setter.setHeader(exports.X_B3_TRACE_ID, spanContext.traceId); setter.setHeader(exports.X_B3_SPAN_ID, spanContext.spanId); if (((spanContext.options || exports.NOT_SAMPLED_VALUE) & exports.SAMPLED_VALUE) !== 0) { setter.setHeader(exports.X_B3_SAMPLED, `${exports.SAMPLED_VALUE}`); } else { setter.setHeader(exports.X_B3_SAMPLED, `${exports.NOT_SAMPLED_VALUE}`); } } /** * Generate SpanContexts */ generate() { return { traceId: uuid .v4() .split('-') .join(''), spanId: crypto.randomBytes(8).toString('hex'), options: exports.SAMPLED_VALUE, }; } /** Converts a headers type to a string. */ parseHeader(str) { if (Array.isArray(str)) { return str[0]; } return str; } } exports.B3Format = B3Format; //# sourceMappingURL=b3-format.js.map