// THE COPIES OF A GONE RECORDING THAT FAILED (release 29 review): a window // find-copy sent to fetch-windows from a copy (a Wayback capture, an // archive.org file) whose fetch failed. `data//copy-attempts.json`, so a // later find-copy does not pick the same copy again and falls through to the // next (Wayback → archive.org → the next mirror). Written by fetch-windows // (controller/fetchWindows.ts) on an item's failure; read by find-copy. // // AND EVERY WHOLE-COPY ATTEMPT (release 31, lane C): find-copy's scope mode // (`{slug | siteId, gone}`) looks for a copy of a gone video's WHOLE audio and // fetch-copies brings it home into the record. Each run's answer for the video // is appended to `attempts`: `fetched` (the audio is the copy's — the video // page's "Audio from a copy" line reads it), `none-found` (neither Wayback nor // archive.org holds it) or `failed` (the copy's fetch failed at its source). // The last two are TERMINAL: the scope mode skips a video whose newest // terminal attempt is younger than COPY_ATTEMPT_RETRY_DAYS, unless // `retryFailed`. A lookup that errored (a rate limit, archive.org down) is not // an attempt and is never recorded. // // SERVER-ONLY (node:fs). import { CLIP_COPY_SOURCES, coerceClipCopy, type ClipCopy } from "./clipWindow"; import { withJsonFileLock } from "./jsonFile-server"; import { sidecar, sidecarField } from "./sidecar-server"; export const COPY_ATTEMPTS_FILENAME = "copy-attempts.json"; export type FailedCopy = ClipCopy & { at: string; error: string }; export const COPY_ATTEMPT_OUTCOMES = ["fetched", "none-found", "failed"] as const; export type CopyAttemptOutcome = (typeof COPY_ATTEMPT_OUTCOMES)[number]; // One whole-copy attempt (release 31). `source`/`url` name the copy (absent // for none-found: every source was asked); an archive.org copy names its item // and file, a Wayback copy its capture's timestamp when the URL carries one. export type CopyAttempt = { at: string; outcome: CopyAttemptOutcome; source?: ClipCopy["from"]; url?: string; identifier?: string; file?: string; captureTs?: string; // The audio file a fetch wrote (`audio.`). audioFile?: string; // What was asked and found, in a phrase (none-found). detail?: string; error?: string; }; export type CopyAttempts = { failed: FailedCopy[]; attempts?: CopyAttempt[] }; // How long a terminal whole-copy attempt (none-found, failed) keeps a video // out of find-copy's scope mode: archives fill in slowly, and asking archive.org // about the same id every night is the scraper shape the clients exist to avoid. export const COPY_ATTEMPT_RETRY_DAYS = 30; // The newest few, one per URL; the newest few attempts. const KEEP = 20; const optStr = (v: unknown): string | undefined => (typeof v === "string" && v !== "" ? v : undefined); function coerceCopyAttempt(v: unknown): CopyAttempt | null { if (!v || typeof v !== "object" || Array.isArray(v)) return null; const r = v as Record; if (typeof r.at !== "string" || !(COPY_ATTEMPT_OUTCOMES as readonly unknown[]).includes(r.outcome)) return null; const out: CopyAttempt = { at: r.at, outcome: r.outcome as CopyAttemptOutcome }; if ((CLIP_COPY_SOURCES as readonly unknown[]).includes(r.source)) out.source = r.source as ClipCopy["from"]; const url = optStr(r.url); if (url && /^https?:\/\//.test(url)) out.url = url; for (const k of ["identifier", "file", "captureTs", "audioFile", "detail", "error"] as const) { const x = optStr(r[k]); if (x) out[k] = x; } return out; } export function coerceCopyAttempts(value: unknown): CopyAttempts | null { const v = value as { failed?: unknown; attempts?: unknown } | null; if (!v || typeof v !== "object") return null; if (!Array.isArray(v.failed) && !Array.isArray(v.attempts)) return null; const failed: FailedCopy[] = []; for (const f of Array.isArray(v.failed) ? v.failed : []) { const copy = coerceClipCopy(f); const r = f as { at?: unknown; error?: unknown }; if (copy && typeof r.at === "string") failed.push({ ...copy, at: r.at, error: typeof r.error === "string" ? r.error : "" }); } const out: CopyAttempts = { failed }; if (Array.isArray(v.attempts)) { out.attempts = v.attempts.map(coerceCopyAttempt).filter((a): a is CopyAttempt => a !== null); } return out; } export const copyAttemptsSidecar = sidecar(COPY_ATTEMPTS_FILENAME, sidecarField(coerceCopyAttempts)); // WHETHER A FAILED FETCH SAYS THE COPY ITSELF IS BAD (release 29 live fix). // Only a source-side failure is recorded against a copy: the file or page gone // or refused (404, 410, 403), the source unreachable, the video not archived. // Our own side — the format selector matching nothing ("Requested format is // not available"), ffmpeg, a disk — says nothing about the copy, and neither // does a failure nobody can place: those are never recorded, so the next run // tries the same copy again. export function isSourceSideCopyFailure(failureClass: string | undefined, message: string): boolean { if (/requested format is not available|requested formats are incompatible/i.test(message)) return false; if (failureClass === "per_video" || failureClass === "network") return true; return /http error (?:403|404|410)|404[: ]+not found|410[: ]+gone|not archived or indexed|unable to download webpage|name or service not known|could not resolve host|connection refused/i.test( message, ); } export async function loadCopyAttempts(videoDir: string): Promise { return copyAttemptsSidecar.load(videoDir).catch(() => null); } export async function readFailedCopies(videoDir: string): Promise { return (await loadCopyAttempts(videoDir))?.failed ?? []; } // Both writers read, change and write the file under its lock (fetch-windows // and fetch-copies may finish on one recording at once), and each keeps what // the other wrote. async function updateCopyAttempts(videoDir: string, fn: (prev: CopyAttempts) => CopyAttempts): Promise { await withJsonFileLock(copyAttemptsSidecar.path(videoDir), async () => { const prev = (await loadCopyAttempts(videoDir)) ?? { failed: [] }; await copyAttemptsSidecar.write(videoDir, fn(prev)); }); } export async function recordFailedCopy(videoDir: string, failed: FailedCopy): Promise { await updateCopyAttempts(videoDir, (prev) => ({ ...prev, failed: [...prev.failed.filter((f) => f.url !== failed.url), { ...failed, error: failed.error.slice(0, 400) }].slice(-KEEP), })); } // Append one whole-copy attempt (release 31), the newest KEEP kept. export async function recordCopyAttempt(videoDir: string, attempt: CopyAttempt): Promise { const a: CopyAttempt = { ...attempt, ...(attempt.error ? { error: attempt.error.slice(0, 400) } : {}), ...(attempt.detail ? { detail: attempt.detail.slice(0, 400) } : {}) }; await updateCopyAttempts(videoDir, (prev) => ({ ...prev, attempts: [...(prev.attempts ?? []), a].slice(-KEEP) })); } // The newest attempt that brought the copy's audio home, or null. export function latestFetchedCopy(c: CopyAttempts | null | undefined): CopyAttempt | null { return [...(c?.attempts ?? [])].reverse().find((a) => a.outcome === "fetched") ?? null; } // The newest attempt when it is TERMINAL (none-found, failed) and younger // than `days`, else null — what keeps a video out of find-copy's scope mode // for a while. export function recentTerminalAttempt( c: CopyAttempts | null | undefined, now: number = Date.now(), days: number = COPY_ATTEMPT_RETRY_DAYS, ): CopyAttempt | null { const last = c?.attempts?.at(-1); if (!last || last.outcome === "fetched") return null; const at = Date.parse(last.at); if (!Number.isFinite(at)) return null; return now - at < days * 86_400_000 ? last : null; }