Files
OmniRoute/src/shared/middleware/correlationId.ts
Diego Rodrigues de Sa e Souza 78f09c8d9f Release v3.8.41 (#5327)
Release v3.8.41 — 52 commits since v3.8.40 (19 CHANGELOG bullets, 11 contributors).

All gating CI green: Unit×8, Coverage×8, Vitest, Package Artifact, Quality Ratchet, CodeQL, Lint, Docs Sync (Strict), Node 24/26 compat, E2E×9, Integration, Electron smoke.

Advisory checks overridden (main unprotected): PR Test Policy = test-masking heuristic on the cumulative 52-commit assert delta (legitimate dead-code-sweep removals + consolidations, reviewed per-PR); SonarCloud/SonarQube = new-code maintainability/coverage quality gate (CodeQL/Semgrep/Security/npm-audit/Dependabot all clean — not a security finding).
2026-06-29 16:51:03 -03:00

44 lines
1.2 KiB
TypeScript

/**
* Correlation ID Middleware — FASE-04 Observability
*
* Generates and propagates correlation IDs (X-Request-Id) across
* requests and responses for distributed tracing. Uses AsyncLocalStorage
* to make the correlation ID available in any downstream code.
*
* @module middleware/correlationId
*/
import { AsyncLocalStorage } from "node:async_hooks";
import crypto from "crypto";
const correlationStore = new AsyncLocalStorage();
/**
* Generate a unique correlation ID.
* @returns {string} UUID-like correlation ID
*/
function generateCorrelationId() {
return crypto.randomUUID();
}
/**
* Get the current correlation ID from async context.
* @returns {string|undefined}
*/
export function getCorrelationId() {
return correlationStore.getStore();
}
/**
* Run a function within a correlation context.
* If a correlationId is provided, it is used; otherwise a new one is generated.
*
* @param {string|null} correlationId - Optional existing correlation ID
* @param {Function} fn - Function to run in context
* @returns {*} Result of fn()
*/
export function runWithCorrelation(correlationId, fn) {
const id = correlationId || generateCorrelationId();
return correlationStore.run(id, fn);
}