/** Batched request logging into ClickHouse `api_requests` (never fatal, never awaited on the request path). */ import { chInsert } from "@dci/db/clickhouse"; interface Req { ts: string; route: string; status: number; duration_ms: number; cached: number } const buffer: Req[] = []; let timer: NodeJS.Timeout | null = null; let disabled = process.env.DCI_API_CH_LOG === "0"; const FLUSH_MS = 5_000; const MAX = 2_000; export function recordRequest(route: string, status: number, durationMs: number, cached: boolean): void { if (disabled) return; if (buffer.length >= MAX) buffer.splice(0, buffer.length - MAX + 1); buffer.push({ ts: new Date().toISOString().replace("T", " ").slice(0, 19), route, status, duration_ms: Math.max(0, Math.round(durationMs)), cached: cached ? 1 : 0 }); if (!timer) timer = setTimeout(() => { timer = null; void flushRequests(); }, FLUSH_MS); } export async function flushRequests(): Promise { if (!buffer.length) return; const rows = buffer.splice(0, buffer.length); try { await chInsert("api_requests", rows as unknown as Record[]); } catch { /* chInsert already swallows in optional mode; belt and braces */ } } export function stopTelemetry(): void { if (timer) clearTimeout(timer); timer = null; disabled = true; }