// FETCH THE WHOLE AUDIO OF GONE VIDEOS FROM THEIR COPIES, AS ONE PACED JOB // (release 31, lane C; the `fetch-copies` kind). // // find-copy's scope mode (publish/findCopy.ts findWholeCopies) found a copy of // each gone video — the Wayback Machine holding it, or an archive.org mirror // of it — and hands the list here. Each item goes through fetchCopyManaged // (ytdlp/fetchCopyManaged.ts) into its ORIGINAL record's `audio.`, one at // a time, and then: // // wayback.json / archiveorg.json the copy's provenance, through the // existing writers (lib/wayback-server.ts ensureWaybackProvenance — from // the URL alone; lib/archiveOrg-server.ts // ensureArchiveOrgProvenanceSidecar — the item's metadata, cached). // metadata.info.json is NOT touched: the record stays the original's. // copy-attempts.json a `fetched` attempt (what the video page's "Audio // from a copy" line reads), or a `failed` one when the copy failed at its // source (lib/copyAttempts-server.ts isSourceSideCopyFailure; also in // `failed`, so no find-copy picks that copy again). // // PACED: archive.org serves both kinds of copy, so the run is paced as the // `archiveorg` platform — its hold and cooldown asked before every fetch, a 429 // recorded against it and the run stopped, a success recorded clean — and // WHOLE_COPY_MIN_GAP_SECONDS lies between two fetches. A whole file is one // long request, never a burst. // // A JOB OF THIS KIND SPANS CHANNELS, so runManagedFunction's media guard has // no channel to ask; each channel's media reachability (it WRITES audio) is // asked here, once, before its first item. import path from "node:path"; import { readdir } from "node:fs/promises"; import type { Paths } from "../lib/paths"; import type { ChannelConfig } from "../lib/channelConfig"; import type { ClipCopy } from "../lib/clipWindow"; import type { JobProgress } from "../jobs/registry"; import { parseArchiveOrgUrl } from "../lib/archiveOrgId"; import { isXUrl } from "../lib/xJobRule"; import { parseWaybackUrl } from "../lib/wayback"; import { ensureWaybackProvenance } from "../lib/wayback-server"; import { ensureArchiveOrgProvenanceSidecar } from "../lib/archiveOrg-server"; import type { ArchiveOrgClient } from "../lib/archiveOrgClient"; import { assertChannelMediaReachable } from "../lib/channelMedia"; import { isSourceSideCopyFailure, recordCopyAttempt, recordFailedCopy, type CopyAttempt, type FailedCopy, } from "../lib/copyAttempts-server"; import { channelConfigPlatform } from "../lib/videoId"; import { resolveVideoDirId } from "../lib/videoDir-server.mjs"; import { heldPlatformRefusal, platformCooldownRemainingMs, recordDownloadBackoff, recordPlatformClean, } from "../jobs/downloadBackoff"; import { FetchWindowError } from "../ytdlp/fetchWindowManaged"; import { fetchCopyManaged, holdsMedia, type FetchCopyOpts, type FetchCopyResult } from "../ytdlp/fetchCopyManaged"; import { readChannelConfig } from "./channels"; import { jitterMs } from "../lib/jitter"; // The least time between two whole-copy fetches. export const WHOLE_COPY_MIN_GAP_SECONDS = 30; // The platform a copy's fetch is paced and backed off as. export const COPY_PLATFORM = "archiveorg"; export type FetchCopyItem = { slug: string; id: string; copy: ClipCopy; }; export type FetchCopiesFailure = { item: FetchCopyItem; class: string; message: string }; export type FetchCopiesResult = { fetched: (FetchCopyItem & { audioFile: string; bytes: number })[]; // Already holding audio or video when its turn came: nothing fetched. skipped: (FetchCopyItem & { why: string })[]; failed: FetchCopiesFailure[]; notAttempted: FetchCopyItem[]; stopped?: "rate-limit" | "cooldown" | "held" | "drain" | "cancel"; }; export type FetchCopiesDeps = { fetchCopy: (opts: FetchCopyOpts) => Promise; readChannelConfig: (paths: Paths, slug: string) => Promise; assertMediaReachable: (paths: Paths, slug: string) => Promise; sleep: (ms: number, signal?: AbortSignal) => Promise; cooldownRemainingMs: (platform: string, paths: Paths) => Promise; heldRefusal: (platform: string, paths: Paths) => Promise; recordBackoff: (platform: string, paths: Paths, failureClass: "rate_limit" | "network") => Promise; recordClean: (platform: string, paths: Paths) => Promise; recordFailedCopy: (videoDir: string, failed: FailedCopy) => Promise; recordCopyAttempt: (videoDir: string, attempt: CopyAttempt) => Promise; // The copy's provenance sidecar (wayback.json / archiveorg.json). writeProvenance: (videoDir: string, copy: ClipCopy, o: { onLog: (s: string) => void; signal: AbortSignal }) => Promise; now: () => Date; }; function abortableSleep(ms: number, signal?: AbortSignal): Promise { if (ms <= 0 || signal?.aborted) return Promise.resolve(); return new Promise((resolve) => { const onAbort = () => { clearTimeout(t); resolve(); }; const t = setTimeout(() => { signal?.removeEventListener("abort", onAbort); resolve(); }, ms); signal?.addEventListener("abort", onAbort, { once: true }); }); } // wayback.json from the capture URL (none when the URL names no capture // timestamp); archiveorg.json from the item (cached by the client). export async function writeCopyProvenance( videoDir: string, copy: ClipCopy, o: { onLog: (s: string) => void; signal: AbortSignal; client?: ArchiveOrgClient }, ): Promise { if (copy.from === "wayback") { await ensureWaybackProvenance(videoDir, copy.url, { onLog: o.onLog }); return; } const ref = parseArchiveOrgUrl(copy.url); if (ref) { await ensureArchiveOrgProvenanceSidecar(videoDir, ref, { onLog: o.onLog, signal: o.signal, ...(o.client ? { client: o.client } : {}), }); } } const DEFAULT_DEPS: FetchCopiesDeps = { fetchCopy: fetchCopyManaged, readChannelConfig, assertMediaReachable: (paths, slug) => assertChannelMediaReachable(paths, slug), sleep: abortableSleep, cooldownRemainingMs: (platform, paths) => platformCooldownRemainingMs(platform, paths), heldRefusal: (platform, paths) => heldPlatformRefusal(platform, "This batch", paths), recordBackoff: (platform, paths, cls) => recordDownloadBackoff(platform, paths, cls), recordClean: (platform, paths) => recordPlatformClean(platform, paths), recordFailedCopy, recordCopyAttempt, writeProvenance: writeCopyProvenance, now: () => new Date(), }; // What a copy attempt names of its copy: the archive.org item and file, the // Wayback capture's timestamp. export function copyAttemptFields(copy: ClipCopy): Pick { const out: Pick = { source: copy.from, url: copy.url }; if (copy.from === "archive.org") { const ref = parseArchiveOrgUrl(copy.url); if (ref?.identifier) out.identifier = ref.identifier; if (ref?.file) out.file = ref.file; } else { const ts = parseWaybackUrl(copy.url)?.captureTs; if (ts) out.captureTs = ts; } return out; } export const fetchCopyItemLabel = (item: FetchCopyItem) => `${item.slug}/${item.id} (${item.copy.from})`; export async function fetchCopies({ paths, items, gapMs, onLog, signal, drainSignal, setProgress, deps: depsOverride, }: { paths: Paths; items: FetchCopyItem[]; // The pause between two fetches; absent = WHOLE_COPY_MIN_GAP_SECONDS. gapMs?: number; onLog?: (line: string) => void; signal?: AbortSignal; drainSignal?: AbortSignal; setProgress?: (snap: JobProgress) => void; deps?: Partial; }): Promise { const deps: FetchCopiesDeps = { ...DEFAULT_DEPS, ...depsOverride }; const log = (line: string) => onLog?.(line.endsWith("\n") ? line : `${line}\n`); const fetchLog = (line: string) => onLog?.(line); const fetchSignal = signal ?? new AbortController().signal; // The floor between two fetches (stretched by pacing.jitter where it is // slept, below). const gap = gapMs ?? WHOLE_COPY_MIN_GAP_SECONDS * 1000; // One item per recording: the first ask wins. const seen = new Set(); const work = items.filter((i) => { const k = `${i.slug}\0${i.id}`; if (seen.has(k)) return false; seen.add(k); return true; }); const result: FetchCopiesResult = { fetched: [], skipped: [], failed: [], notAttempted: [] }; log(`Fetch copies: ${work.length} gone video(s), each one's whole audio from its copy.`); let done = 0; const progress = () => setProgress?.({ metric: "downloads", initial: 0, target: work.length, current: done }); progress(); const configs = new Map(); const reachable = new Map(); const fail = (item: FetchCopyItem, cls: string, message: string) => { result.failed.push({ item, class: cls, message }); log(` ✗ ${fetchCopyItemLabel(item)}: ${cls} — ${message}`); }; const interrupted = (): FetchCopiesResult["stopped"] | null => signal?.aborted ? "cancel" : drainSignal?.aborted ? "drain" : null; const stop = (why: NonNullable, from: number) => { result.stopped = why; result.notAttempted.push(...work.slice(from)); }; let networkAttempts = 0; for (let i = 0; i < work.length; i++) { const item = work[i]!; const why = interrupted(); if (why) { stop(why, i); break; } const label = fetchCopyItemLabel(item); // A COPY IS ARCHIVE.ORG'S (review 3 S5): this job passes X's queue rule // because it asks archive.org only (lib/xJobRule.ts xJobAsksX), so an // address of X's is never fetched here. if (isXUrl(item.copy.url)) { fail(item, "not-a-copy", "its address is X's: a copy is archive.org's (the Wayback Machine or an archive.org item), and nothing was asked of X"); done++; progress(); continue; } if (!configs.has(item.slug)) configs.set(item.slug, await deps.readChannelConfig(paths, item.slug).catch(() => null)); const config = configs.get(item.slug) ?? null; if (!config) { fail(item, "unknown-channel", `no channel "${item.slug}"`); done++; progress(); continue; } if (!reachable.has(item.slug)) { reachable.set( item.slug, await deps.assertMediaReachable(paths, item.slug).then( () => null, (e: unknown) => (e as Error).message, ), ); } const unreachable = reachable.get(item.slug); if (unreachable) { fail(item, "unreachable", unreachable); done++; progress(); continue; } const dirId = await resolveVideoDirId(paths.channelsDir, item.slug, item.id, { platform: channelConfigPlatform(config) }); const videoDir = path.join(paths.channelsDir, item.slug, "data", dirId); const entries = await readdir(videoDir).catch(() => null); if (!entries) { fail(item, "no-record", `no directory for ${item.id}`); done++; progress(); continue; } if (holdsMedia(entries)) { result.skipped.push({ ...item, why: "it already holds audio or video" }); log(` = ${label}: already holds audio or video; nothing fetched.`); done++; progress(); continue; } if (networkAttempts > 0 && gap > 0) { // The default floor stretched by up to pacing.jitter; a gap the caller // passed is waited exactly. const pause = gapMs === undefined ? jitterMs(gap) : gap; log(`Sleeping ${Math.round(pause / 1000)}s before the next copy...`); await deps.sleep(pause, signal); const after = interrupted(); if (after) { stop(after, i); break; } } const held = await deps.heldRefusal(COPY_PLATFORM, paths); if (held) { log(` ${label}: ${held} — stopping; the rest are left for a later run.`); stop("held", i); break; } const cooldownMs = await deps.cooldownRemainingMs(COPY_PLATFORM, paths); if (cooldownMs > 0) { log( ` ${label}: archive.org is in a rate-limit cooldown (${Math.ceil(cooldownMs / 1000)}s remaining) — ` + `stopping; the rest are left for a later run.`, ); stop("cooldown", i); break; } log(` ${label}: fetching ${item.copy.url}…`); networkAttempts++; try { const r = await deps.fetchCopy({ paths, channelConfig: config, videoDir, videoId: dirId, copy: item.copy, onLog: fetchLog, signal: fetchSignal, }); try { await deps.writeProvenance(videoDir, item.copy, { onLog: fetchLog, signal: fetchSignal }); } catch (e) { log(` ${label}: the copy's provenance was not written (${(e as Error).message}).`); } await deps .recordCopyAttempt(videoDir, { at: deps.now().toISOString(), outcome: "fetched", ...copyAttemptFields(item.copy), audioFile: r.audioFile, }) .catch((e: unknown) => log(` ${label}: copy-attempts.json not written (${(e as Error).message}).`)); result.fetched.push({ ...item, audioFile: r.audioFile, bytes: r.bytes }); const clean = await deps.recordClean(COPY_PLATFORM, paths).catch(() => null); if (clean) log(clean); } catch (e) { const message = (e as Error).message; const cls = e instanceof FetchWindowError ? e.failureClass : "unknown"; fail(item, cls, message); if (cls === "rate_limit") { await deps.recordBackoff(COPY_PLATFORM, paths, "rate_limit").catch(() => {}); log(` archive.org rate-limited this run — stopping; the rest are left for a later run.`); done++; progress(); stop("rate-limit", i + 1); break; } // A COPY THAT FAILED AT ITS SOURCE is recorded, as fetch-windows records // a window's: never picked again by find-copy (`failed`), and a terminal // attempt for the scope mode. Our own side (the extraction, a disk) is // not held against the copy. if (!fetchSignal.aborted && isSourceSideCopyFailure(cls, message)) { const at = deps.now().toISOString(); await deps.recordFailedCopy(videoDir, { ...item.copy, at, error: message }).catch(() => {}); await deps .recordCopyAttempt(videoDir, { at, outcome: "failed", ...copyAttemptFields(item.copy), error: message }) .catch(() => {}); log(` ${label}: the ${item.copy.from} copy failed at its source — find-copy will not pick it again.`); } } done++; progress(); } log( `Fetch copies: ${result.fetched.length} fetched, ${result.skipped.length} already held media, ` + `${result.failed.length} failed` + (result.notAttempted.length ? `, ${result.notAttempted.length} not attempted (stopped: ${result.stopped})` : "") + ".", ); return result; }