verae-middleware/src/debug/trace-context.js

39 lines
886 B
JavaScript

/**
* @fileoverview AsyncLocalStorage-backed trace context (no logger dependency).
* Split from trace.js to avoid circular imports with logger.js.
* @module debug/trace-context
*/
import { AsyncLocalStorage } from 'node:async_hooks';
import { randomBytes } from 'node:crypto';
/**
* @typedef {Object} TraceContext
* @property {string} traceId
* @property {string} [span]
*/
/** @type {AsyncLocalStorage<TraceContext>} */
export const traceStorage = new AsyncLocalStorage();
/**
* Generate a short opaque trace id (16 hex chars).
* @returns {string}
*/
export function generateTraceId() {
return randomBytes(8).toString('hex');
}
/**
* @returns {string|null}
*/
export function getTraceId() {
return traceStorage.getStore()?.traceId ?? null;
}
/**
* @returns {TraceContext|null}
*/
export function getTraceContext() {
return traceStorage.getStore() ?? null;
}