// In-memory TTL cache. Deliberately not SQLite: this box must deploy with no native build step, // and the only state worth keeping across a restart is nothing — a cache that survives restarts // is how a "1 hour" promise turns into yesterday's DNS answer. const store = new Map(); const MAX_ENTRIES = 5000; export function get(key) { const hit = store.get(key); if (!hit) return null; if (hit.expiresAt <= Date.now()) { store.delete(key); return null; } return hit.value; } export function set(key, value, ttlMs) { if (store.size >= MAX_ENTRIES) { // drop the oldest insertion first; Map preserves order const oldest = store.keys().next(); if (!oldest.done) store.delete(oldest.value); } store.set(key, { value, expiresAt: Date.now() + ttlMs }); return value; } export function drop(key) { store.delete(key); } export function clear() { store.clear(); } export function size() { return store.size; } /** * Cache the result of one check. * TTLs come from the honesty rule in AGENTS.md: a clean result is worth an hour, anything that * could be mid-fix by the visitor (a warning, an error, a blocked probe) is worth five minutes — * otherwise someone who just published a DNS change sees the old answer and concludes the tool * is broken. */ export const TTL_CLEAN_MS = 60 * 60 * 1000; export const TTL_DOUBT_MS = 5 * 60 * 1000; export function ttlFor(state) { return state === 'ok' ? TTL_CLEAN_MS : TTL_DOUBT_MS; } export async function cached(key, ttlMs, producer) { const hit = get(key); if (hit) return { ...hit, fromCache: true }; const value = await producer(); const ttl = typeof ttlMs === 'function' ? ttlMs(value) : ttlMs; set(key, value, ttl); return { ...value, fromCache: false }; }