spb/datacenterindex
Public
HTML 53.9%
TypeScript 44.5%
JavaScript 0.6%
SQL 0.5%
1/** Batched request logging into ClickHouse `api_requests` (never fatal, never awaited on the request path). */2import { chInsert } from "@dci/db/clickhouse";34interface Req { ts: string; route: string; status: number; duration_ms: number; cached: number }56const buffer: Req[] = [];7let timer: NodeJS.Timeout | null = null;8let disabled = process.env.DCI_API_CH_LOG === "0";9const FLUSH_MS = 5_000;10const MAX = 2_000;1112export function recordRequest(route: string, status: number, durationMs: number, cached: boolean): void {13 if (disabled) return;14 if (buffer.length >= MAX) buffer.splice(0, buffer.length - MAX + 1);15 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 });16 if (!timer) timer = setTimeout(() => { timer = null; void flushRequests(); }, FLUSH_MS);17}1819export async function flushRequests(): Promise<void> {20 if (!buffer.length) return;21 const rows = buffer.splice(0, buffer.length);22 try {23 await chInsert("api_requests", rows as unknown as Record<string, unknown>[]);24 } catch {25 /* chInsert already swallows in optional mode; belt and braces */26 }27}2829export function stopTelemetry(): void {30 if (timer) clearTimeout(timer);31 timer = null;32 disabled = true;33}34