autotel
Version:
Write Once, Observe Anywhere
62 lines (59 loc) • 2.26 kB
JavaScript
;
var chunkHZ3FYBJG_cjs = require('./chunk-HZ3FYBJG.cjs');
var api = require('@opentelemetry/api');
var async_hooks = require('async_hooks');
var correlationStorage = new async_hooks.AsyncLocalStorage();
var CORRELATION_ID_BAGGAGE_KEY = "autotel.correlation_id";
function generateCorrelationId() {
const bytes = new Uint8Array(8);
crypto.getRandomValues(bytes);
return [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
}
function getCorrelationId() {
const storedId = correlationStorage.getStore()?.value;
if (storedId) {
return storedId;
}
const activeContext = api.context.active();
const baggage = api.propagation.getBaggage(activeContext);
const baggageEntry = baggage?.getEntry(CORRELATION_ID_BAGGAGE_KEY);
if (baggageEntry?.value) {
return baggageEntry.value;
}
const span = api.trace.getActiveSpan();
if (span) {
const spanContext = span.spanContext();
return spanContext.traceId.slice(0, 16);
}
return void 0;
}
function getOrCreateCorrelationId() {
return getCorrelationId() ?? generateCorrelationId();
}
function runWithCorrelationId(correlationId, fn) {
return correlationStorage.run({ value: correlationId }, fn);
}
function setCorrelationId(correlationId) {
chunkHZ3FYBJG_cjs.enterOrRun(correlationStorage, correlationId);
}
function setCorrelationIdInBaggage(correlationId) {
const activeContext = api.context.active();
let baggage = api.propagation.getBaggage(activeContext) ?? api.propagation.createBaggage();
baggage = baggage.setEntry(CORRELATION_ID_BAGGAGE_KEY, {
value: correlationId
});
return api.propagation.setBaggage(activeContext, baggage);
}
function getCorrelationStorage() {
return correlationStorage;
}
exports.CORRELATION_ID_BAGGAGE_KEY = CORRELATION_ID_BAGGAGE_KEY;
exports.generateCorrelationId = generateCorrelationId;
exports.getCorrelationId = getCorrelationId;
exports.getCorrelationStorage = getCorrelationStorage;
exports.getOrCreateCorrelationId = getOrCreateCorrelationId;
exports.runWithCorrelationId = runWithCorrelationId;
exports.setCorrelationId = setCorrelationId;
exports.setCorrelationIdInBaggage = setCorrelationIdInBaggage;
//# sourceMappingURL=chunk-JSNUWSBH.cjs.map
//# sourceMappingURL=chunk-JSNUWSBH.cjs.map