// Per-key exec rate limiter. Sliding window + concurrency cap. // Prevents a single authenticated client from turning a container into an // exec-loop. Global rate limit in app.ts still applies on top of this. const WINDOW_MS = 60_000; const MAX_PER_WINDOW = 30; const MAX_CONCURRENT = 4; type Bucket = { count: number; resetAt: number; active: number }; const buckets = new Map(); setInterval(() => { const now = Date.now(); for (const [key, b] of buckets) { if (now > b.resetAt && b.active === 0) buckets.delete(key); } }, WINDOW_MS); export type ExecSlotResult = | { ok: true } | { ok: false; reason: string; retryAfterS?: number }; export function reserveExecSlot(key: string): ExecSlotResult { const now = Date.now(); let b = buckets.get(key); if (!b || now > b.resetAt) { b = { count: 0, resetAt: now + WINDOW_MS, active: 0 }; buckets.set(key, b); } if (b.active >= MAX_CONCURRENT) { return { ok: false, reason: `Too many concurrent execs (max ${MAX_CONCURRENT})` }; } if (b.count >= MAX_PER_WINDOW) { return { ok: false, reason: `Exec rate limit exceeded (${MAX_PER_WINDOW}/min)`, retryAfterS: Math.ceil((b.resetAt - now) / 1000), }; } b.count++; b.active++; return { ok: true }; } export function releaseExecSlot(key: string): void { const b = buckets.get(key); if (b && b.active > 0) b.active--; }