// ponytail: pure state machine, zero pi deps, fully unit-testable. // Cooldown + round-robin rotation over a fixed member list. export type CooldownReason = "capacity" | "quota" | "network"; export interface CooldownConfig { capacity: number; // overloaded / 503 / 529 — transient quota: number; // 429 / RESOURCE_EXHAUSTED — standard recovery network: number; // network errors — don't blame the key (0 = no cooldown) } export const DEFAULT_COOLDOWN: CooldownConfig = { capacity: 30_000, quota: 60_000, network: 0, }; const RATE_LIMIT_PATTERNS = [ /429/, /resource_exhausted/i, /quota/i, /rate.?limit/i, /too many requests/i, /overloaded/i, /capacity/i, /usage.?limit/i, /limit.*reached/i, ]; export function isRateLimitError(msg: string): boolean { return RATE_LIMIT_PATTERNS.some((p) => p.test(msg)); } export function classifyError(msg: string): CooldownReason { if (/\b(503|529)\b|overloaded|high demand|capacity/i.test(msg)) return "capacity"; if (/network|timeout|econn|socket/i.test(msg)) return "network"; return "quota"; } export interface FailoverPool { members: string[]; cooldown: CooldownConfig; exhausted: Map; } export function createPool( members: string[], cooldown: CooldownConfig = DEFAULT_COOLDOWN, ): FailoverPool { return { members, cooldown, exhausted: new Map() }; } export function markExhausted( pool: FailoverPool, member: string, reason: CooldownReason, now: number, ): void { const cd = pool.cooldown[reason]; if (cd <= 0) return; // network: don't blame the member pool.exhausted.set(member, { reason, until: now + cd }); } export function isAvailable( pool: FailoverPool, member: string, now: number, hasAuth: boolean, ): boolean { if (!hasAuth) return false; const e = pool.exhausted.get(member); if (!e) return true; if (now >= e.until) { pool.exhausted.delete(member); // cooldown elapsed → member recovers return true; } return false; } // Round-robin from the member after `current`, first available wins. null if all down. export function pickNext( pool: FailoverPool, current: string | null, now: number, hasAuthFn: (m: string) => boolean, ): string | null { if (pool.members.length === 0) return null; const startIdx = current ? pool.members.indexOf(current) : -1; for (let i = 1; i <= pool.members.length; i++) { const idx = (startIdx + i) % pool.members.length; const m = pool.members[idx]; if (isAvailable(pool, m, now, hasAuthFn(m))) return m; } return null; }