export type ServiceHealthCategory = "core" | "integration"; export type ServiceHealthStatus = "operational" | "unavailable"; export type ServiceHealthProbe = { id: string; label: string; category: ServiceHealthCategory; check: () => Promise; }; export type ServiceHealthSnapshot = { checkedAt: string; services: { id: string; label: string; category: ServiceHealthCategory; status: ServiceHealthStatus; }[]; }; async function checkWithTimeout(check: () => Promise, timeoutMs: number) { let timeout: ReturnType | undefined; try { return await Promise.race([ check(), new Promise((resolve) => { timeout = setTimeout(() => resolve(false), timeoutMs); }), ]); } catch { return false; } finally { if (timeout) clearTimeout(timeout); } } export async function collectServiceHealth( probes: ServiceHealthProbe[], options: { timeoutMs?: number; now?: () => Date } = {}, ): Promise { const timeoutMs = options.timeoutMs ?? 5_000; const checkedAt = (options.now ?? (() => new Date()))().toISOString(); const services = await Promise.all( probes.map(async ({ id, label, category, check }) => ({ id, label, category, status: (await checkWithTimeout(check, timeoutMs)) ? ("operational" as const) : ("unavailable" as const), })), ); return { checkedAt, services }; } export function createCachedHealthReader( load: () => Promise, options: { ttlMs?: number; now?: () => number } = {}, ) { const ttlMs = options.ttlMs ?? 60_000; const now = options.now ?? Date.now; let cached: | { expiresAt: number; value: Promise } | undefined; return () => { const currentTime = now(); if (cached && currentTime < cached.expiresAt) return cached.value; const value = load(); cached = { expiresAt: currentTime + ttlMs, value }; void value.catch(() => { if (cached?.value === value) cached = undefined; }); return value; }; }