import path from "node:path"; import type { Paths } from "../lib/paths"; import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../lib/jsonFile-server"; // THE OFF-QUEUE WAIT OF A RATE-LIMITED CLEAN'S RETRY (lane clean-unverified, // review 1 F4–F6, operator rulings 4 and 5). // // A checked Clean audio the source rate-limited ends deferred and asks for ONE // retry, not before `notBefore`. That wait used to happen inside a queued job: // it held the channel's queue (every other cleanup, diarize backfill, attach // media… and "Clean without checking" itself waited behind it) and, being only // in memory and in a queued job's spec, a restart either lost it or re-ran it // at once as a fresh request with two more retries. // // Now the wait is a RECORD and a TIMER, and holds no queue and no job slot: // - the record is durable, `/clean-retries.json`: one entry per // scheduled retry, with its attempt, its chain's original job, and its // not-before time — so a chain never exceeds 2 retries and never runs // earlier than its not-before, whatever restarts happen; // - a timer in this process fires at not-before. If the platform's cooldown // is still running then (it is re-read), the record moves to the // cooldown's end and the timer is re-armed — at most MAX_REARMS times, // then the retry is queued anyway and meets the cooldown as a rate limit; // - only then is the retry QUEUED, as a `clean-audio-retry` job on the // channel's queue, which re-asserts every guard as any job does (and the // sweep again immediately before it removes anything); // - the boot arms every record again (an idle boot does not, and keeps them). // A retry that a restart caught queued is re-armed from its record (the // boot pass closes its stale meta: the kind is `rescheduledOnBoot`); one a // restart caught RUNNING is re-armed once, then dropped. // CANCEL reaches it three ways: `cancelCleanRetries` by the deferred job's id // (/jobs' and `pnpm ops job {"verb":"cancel"}`'s Cancel of that job, through // cancelJobAction), the channel's Cleanup stage ("Cancel retry"), and any // new clean of the channel a person starts, which supersedes it. A record // cancelled while its job is queued cancels that job too. export type ScheduledCleanRetry = { // This retry's own id: `.retry`. id: string; slug: string; // 1-based; at most CLEAN_RATE_LIMIT_MAX_RETRIES (cleanAudioJob.ts). attempt: number; // The ORIGINAL request's job id (the chain's). of: string; // The job that ended deferred and asked for this retry. deferredJobId: string; // The platform key the rate limit was recorded under (its cooldown). platform: string; // Never queued before this (epoch ms). notBefore: number; scheduledAt: number; // scheduled: waiting off-queue. enqueued: its job is in the channel queue. // running: its job started (removed when the job ends). state: "scheduled" | "enqueued" | "running"; jobId?: string; // Times the timer moved later for a platform cooldown still running. rearms?: number; // Times a restart caught it running and it was re-armed. restarts?: number; // HELD (review 2 F3): times its time came while the channel's media was not // reachable (a relocation in flight, a drive away) or its job was refused, // and why the last time — so the Cleanup stage can say so. holds?: number; heldReason?: string; // Set when it was held MAX_HOLDS times in a row: it no longer fires, and // the Cleanup stage says why until a person dismisses it (Cancel retry) or a // new clean replaces it. Never dropped silently. gaveUp?: string; }; type StoreFile = { version: 1; retries: ScheduledCleanRetry[] }; export const CLEAN_RETRIES_FILENAME = "clean-retries.json"; export const MAX_REARMS = 8; // A retry whose channel's media is held when its time comes waits HOLD_PAUSE_MS // and tries again, at most MAX_HOLDS times: 96 × 15 min = 24 hours. A media // move of a large channel takes hours, and a drive coming back after a reboot // minutes, so a day covers both; a drive away longer than that is not a pause, // and a retry a day late is no longer the clean that was asked for — it gives // up visibly instead. export const HOLD_PAUSE_MS = 15 * 60_000; export const MAX_HOLDS = 96; // setTimeout's ceiling (~24.8 days); a longer wait is re-armed when it fires. const MAX_TIMER_MS = 2 ** 31 - 1; export function cleanRetriesFile(paths: Pick): string { return path.join(paths.jobsDir, CLEAN_RETRIES_FILENAME); } function isEntry(v: unknown): v is ScheduledCleanRetry { const e = v as Partial | null; return ( !!e && typeof e.id === "string" && typeof e.slug === "string" && typeof e.attempt === "number" && typeof e.of === "string" && typeof e.notBefore === "number" && (e.state === "scheduled" || e.state === "enqueued" || e.state === "running") ); } export async function readCleanRetries(paths: Pick): Promise { const r = await readJsonFile(cleanRetriesFile(paths)); if (!r.ok) return []; const list = (r.value as Partial | null)?.retries; return Array.isArray(list) ? list.filter(isEntry) : []; } // Read-modify-write under the file's lock; `fn` returns the new list, or // `list: null` when nothing changed (no write: a clean with no retry // scheduled writes nothing). async function update( paths: Pick, fn: (list: ScheduledCleanRetry[]) => { list: ScheduledCleanRetry[] | null; out: T }, ): Promise { const file = cleanRetriesFile(paths); return withJsonFileLock(file, async () => { const { list, out } = fn(await readCleanRetries(paths)); if (list) await writeJsonAtomic(file, { version: 1, retries: list } satisfies StoreFile, { mkdir: true }); return out; }); } export type CleanRetryDeps = { now?: () => number; // The timer's callback answers the fire's promise (a test awaits it). setTimer?: (fn: () => Promise, ms: number) => unknown; clearTimer?: (handle: unknown) => void; cooldownRemainingMs: (platform: string) => Promise; // Queue the retry's job on the channel's queue. enqueue: (entry: ScheduledCleanRetry) => Promise<{ ok: true; jobId: string } | { ok: false; error: string }>; // Cancel a queued job (the registry's cancel). cancelJob?: (jobId: string) => boolean; // Why the channel's media cannot be touched now (a relocation marker, an // unreachable drive), or null — asked when the timer fires, before queueing. mediaHold?: (slug: string) => Promise; log?: (m: string) => void; }; // The timers of this process, keyed by retry id; on globalThis like the // registry, so a reloaded module does not arm a second timer for one record. type TimerState = { timers: Map }; declare global { // eslint-disable-next-line no-var var __yttCleanRetryTimers__: TimerState | undefined; } function timers(): Map { return (globalThis.__yttCleanRetryTimers__ ??= { timers: new Map() }).timers; } function clearTimerFor(id: string, deps: CleanRetryDeps): void { const t = timers().get(id); if (t !== undefined) (deps.clearTimer ?? ((h) => clearTimeout(h as ReturnType)))(t); timers().delete(id); } function arm(paths: Pick, entry: ScheduledCleanRetry, deps: CleanRetryDeps): void { clearTimerFor(entry.id, deps); if (entry.gaveUp) return; const now = (deps.now ?? Date.now)(); const ms = Math.min(MAX_TIMER_MS, Math.max(0, entry.notBefore - now)); const set = deps.setTimer ?? ((fn: () => Promise, d: number) => setTimeout(() => void fn(), d)); const handle = set(() => { timers().delete(entry.id); return fireCleanRetry(paths, entry.id, deps).catch((err) => deps.log?.(`[clean-retry] ${entry.id}: ${(err as Error).message}`), ); }, ms); timers().set(entry.id, handle); } // Schedule a retry: write its record, arm its timer. A channel has at most one // scheduled retry: a record already there for the slug is superseded. export async function scheduleCleanRetry( paths: Pick, req: Omit, deps: CleanRetryDeps, ): Promise { const entry: ScheduledCleanRetry = { ...req, id: `${req.of}.retry${req.attempt}`, state: "scheduled", scheduledAt: (deps.now ?? Date.now)(), }; const superseded = await update(paths, (list) => ({ list: [...list.filter((e) => e.slug !== req.slug), entry], out: list.filter((e) => e.slug === req.slug), })); for (const old of superseded) { clearTimerFor(old.id, deps); if (old.state === "enqueued" && old.jobId) deps.cancelJob?.(old.jobId); } arm(paths, entry, deps); return entry; } // The timer fired: queue the retry, or move it to the end of a cooldown that // is still running. A record cancelled meanwhile is simply not there. export async function fireCleanRetry( paths: Pick, id: string, deps: CleanRetryDeps, ): Promise<"enqueued" | "rearmed" | "gone" | "early" | "held" | "gave-up"> { const now = (deps.now ?? Date.now)(); const entry = (await readCleanRetries(paths)).find((e) => e.id === id); if (!entry || entry.state !== "scheduled" || entry.gaveUp) return "gone"; // Never before its time (a long wait is armed in setTimeout-sized steps). if (now < entry.notBefore) { arm(paths, entry, deps); return "early"; } const cooldown = await deps.cooldownRemainingMs(entry.platform).catch(() => 0); if (cooldown > 0 && (entry.rearms ?? 0) < MAX_REARMS) { const moved = await update(paths, (list) => { const e = list.find((x) => x.id === id && x.state === "scheduled"); if (!e) return { list: null, out: null }; e.notBefore = now + cooldown; e.rearms = (e.rearms ?? 0) + 1; return { list, out: { ...e } }; }); if (!moved) return "gone"; deps.log?.(`[clean-retry] ${id}: ${entry.platform} is still cooling down; moved to ${new Date(moved.notBefore).toISOString()}.`); arm(paths, moved, deps); return "rearmed"; } // THE MEDIA HELD (review 2 F3): a relocation in flight or a drive away when // its time comes DEFERS the retry, same attempt; so does a refused enqueue // (the job's own media guard). Never a silent drop. const held = await (deps.mediaHold?.(entry.slug) ?? Promise.resolve(null)).catch((err) => (err as Error).message); const res = held ? ({ ok: false as const, error: held }) : await deps.enqueue(entry).catch((err) => ({ ok: false as const, error: (err as Error).message })); if (!res.ok) { const after = await update(paths, (list) => { const e = list.find((x) => x.id === id && x.state === "scheduled"); if (!e) return { list: null, out: null }; e.holds = (e.holds ?? 0) + 1; e.heldReason = res.error; if (e.holds >= MAX_HOLDS) { e.gaveUp = `Gave up after ${e.holds} tries over ${Math.round((MAX_HOLDS * HOLD_PAUSE_MS) / 3_600_000)} h: ${res.error}. ` + "Nothing was asked or cleaned; run Clean audio again once the channel's media is back."; } else { e.notBefore = now + HOLD_PAUSE_MS; } return { list, out: { ...e } }; }); if (!after) return "gone"; if (after.gaveUp) { deps.log?.(`[clean-retry] ${id}: ${after.gaveUp}`); return "gave-up"; } deps.log?.(`[clean-retry] ${id}: held (${res.error}); tries again at ${new Date(after.notBefore).toISOString()}.`); arm(paths, after, deps); return "held"; } const kept = await update(paths, (list) => { const e = list.find((x) => x.id === id); if (!e) return { list: null, out: false }; // A Start that raced ahead of this write has already moved it on. if (e.state === "scheduled") { e.state = "enqueued"; e.jobId = res.jobId; delete e.heldReason; } return { list, out: true }; }); // Cancelled between the enqueue and this write: cancel the job too. if (!kept) deps.cancelJob?.(res.jobId); return "enqueued"; } // The retry's job started: mark it running. Null = the record is gone (it was // cancelled or superseded) and the job must not run. export async function startCleanRetry( paths: Pick, id: string, jobId: string, ): Promise { return update(paths, (list) => { const e = list.find((x) => x.id === id); if (!e) return { list: null, out: null }; e.state = "running"; e.jobId = jobId; return { list, out: { ...e } }; }); } // The retry's job ended, however it ended: its record goes. export async function finishCleanRetry(paths: Pick, id: string): Promise { await update(paths, (list) => ({ list: list.some((e) => e.id === id) ? list.filter((e) => e.id !== id) : null, out: null })); } // Cancel scheduled retries: by the slug, by a retry's own id, by the job that // ended deferred, or by the chain's original job. A record whose job is // queued cancels that job too; a RUNNING retry is the job's own Cancel's. export async function cancelCleanRetries( paths: Pick, match: { slug?: string; id?: string }, deps: Pick, ): Promise { const hit = (e: ScheduledCleanRetry) => e.state !== "running" && ((match.slug !== undefined && e.slug === match.slug) || (match.id !== undefined && (e.id === match.id || e.deferredJobId === match.id || e.of === match.id || e.jobId === match.id))); const removed = await update(paths, (list) => { const out = list.filter(hit); return { list: out.length ? list.filter((e) => !hit(e)) : null, out }; }); for (const e of removed) { clearTimerFor(e.id, deps as CleanRetryDeps); if (e.state === "enqueued" && e.jobId) deps.cancelJob?.(e.jobId); } return removed; } // THE BOOT: arm every record again. A retry a restart caught queued is // scheduled again (its time has passed, so it is queued at once — never // earlier than its not-before). One caught running is re-armed once; a second // time it is dropped, so a retry that takes the server down cannot loop. export async function armCleanRetriesAtBoot( paths: Pick, deps: CleanRetryDeps, ): Promise<{ armed: string[]; dropped: string[] }> { const out = await update(paths, (list) => { const armed: ScheduledCleanRetry[] = []; const dropped: string[] = []; const next: ScheduledCleanRetry[] = []; for (const e of list) { if (e.gaveUp) { next.push(e); // kept for the Cleanup stage to say why; never fired continue; } if (e.state === "running") { if ((e.restarts ?? 0) >= 1) { dropped.push(e.id); continue; } e.restarts = (e.restarts ?? 0) + 1; } e.state = "scheduled"; delete e.jobId; next.push(e); armed.push({ ...e }); } return { list: list.length ? next : null, out: { armed, dropped } }; }); for (const e of out.armed) arm(paths, e, deps); for (const id of out.dropped) { deps.log?.(`[clean-retry] ${id}: a restart interrupted it twice while it ran; dropped (run Clean audio again).`); } return { armed: out.armed.map((e) => e.id), dropped: out.dropped }; } // For tests: forget every timer of this process (clearing each). export function resetCleanRetryTimers(deps: Pick = {}): void { for (const id of [...timers().keys()]) clearTimerFor(id, deps as CleanRetryDeps); }