Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

1.4 KB
Raw Blame
/**
 * 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";
import { getProcessStore } from "@/shared/utils/processSingleton";

function getCorrelationStore(): AsyncLocalStorage<string | undefined> {
  return getProcessStore("correlationId.store", () => new AsyncLocalStorage<string | undefined>());
}

/**
 * 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 getCorrelationStore().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 getCorrelationStore().run(id, fn);
}