// THE BYTE ACCOUNTING A RESUME IN PLACE RESTS ON (DESIGN-4 1). // // A separate-streams from-start recording runs yt-dlp with `--keep-fragments`: // every fragment it appends to a stream file `` stays on disk as // `-Frag` (downloader/fragment.py: the fragment is written, appended, // THEN the `.ytdl` index is rewritten, and only then — without the flag — is // the fragment file removed). So after any stop the stream file's size is // exactly the sum of Frag1..Frag, the index the `.ytdl` holds — measured // on the installed yt-dlp, fMP4 and WebM alike (LOG.md, DESIGN-4). // // The editor deletes the fragments it has verified, a minute at a time, after // writing (and fsyncing) a checkpoint `.frags.json` {index, bytes}: the // stream file's first `bytes` are fragments 1..index. The equation is then // // size() == checkpoint.bytes + Σ size(Frag), n = checkpoint.index+1 .. index // // with every such Frag present. A resume appends only to a file for which it // holds. The one repair: a stop inside (or just after) the append of fragment // index+1 leaves the file LONGER by a prefix of that fragment (the state not // yet rewritten); when the excess is byte for byte the start of the kept // Frag, the file is truncated back to the equation — the only // destructive write of the design, logged with both lengths. Anything else // (shorter: a crash lost unflushed data; an excess that is not that prefix; a // missing Frag; no checkpoint for a file that holds bytes; an unreadable // state) is no resume in place: a fresh from-start part records instead. import { closeSync, fsyncSync, openSync } from "node:fs"; import { open, readFile, readdir, rename, rm, stat, truncate } from "node:fs/promises"; import path from "node:path"; export type FragCheckpoint = { index: number; bytes: number }; export const checkpointName = (stream: string) => `${stream}.frags.json`; const FRAG_RE = /-Frag(\d+)$/; export async function readYtdlIndex(file: string): Promise { const raw = await readFile(`${file}.ytdl`, "utf8").catch((e: NodeJS.ErrnoException) => (e.code === "ENOENT" ? "absent" : null)); if (raw === "absent" || raw === null) return raw; try { const idx = (JSON.parse(raw) as { downloader?: { current_fragment?: { index?: unknown } } }).downloader?.current_fragment?.index; return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null; } catch { return null; } } async function readCheckpoint(file: string): Promise { const raw = await readFile(checkpointName(file), "utf8").catch(() => null); if (raw === null) return null; try { const c = JSON.parse(raw) as FragCheckpoint; return Number.isInteger(c.index) && c.index >= 0 && Number.isInteger(c.bytes) && c.bytes >= 0 ? c : "corrupt"; } catch { return "corrupt"; } } const sizeOf = (f: string) => stat(f).then((s) => s.size, () => null); // The kept fragment numbers of stream file `name` in `names` (a listing). export function fragNumbers(name: string, names: readonly string[]): number[] { const out: number[] = []; for (const n of names) { if (!n.startsWith(`${name}-Frag`)) continue; const m = FRAG_RE.exec(n); if (m) out.push(Number(m[1])); } return out.sort((a, b) => a - b); } export type StreamAccount = | { ok: true; index: number; size: number; expected: number; checkpoint: FragCheckpoint; kept: number[] } | { ok: false; why: string; index?: number; size?: number; expected?: number; excess?: number; next?: number }; // The equation for one stream file, read only. export async function accountStream(dir: string, name: string, names?: readonly string[]): Promise { const file = path.join(dir, name); const listing = names ?? (await readdir(dir).catch(() => [] as string[])); const size = await sizeOf(file); if (size === null) return { ok: false, why: `${name} is gone` }; const idx = await readYtdlIndex(file); if (idx === null) return { ok: false, why: `${name}.ytdl does not read` }; if (idx === "absent") return size === 0 ? { ok: true, index: 0, size, expected: 0, checkpoint: { index: 0, bytes: 0 }, kept: [] } : { ok: false, why: `${name} has no .ytdl state` }; const cp = await readCheckpoint(file); if (cp === "corrupt") return { ok: false, why: `${checkpointName(name)} does not read` }; const checkpoint = cp ?? { index: 0, bytes: 0 }; if (checkpoint.index > idx) return { ok: false, why: `its checkpoint (${checkpoint.index}) is past its state (${idx})`, index: idx, size }; const kept = fragNumbers(name, listing); const have = new Set(kept); let expected = checkpoint.bytes; for (let n = checkpoint.index + 1; n <= idx; n++) { if (!have.has(n)) return { ok: false, why: `fragment ${n} of ${name} is not kept (no byte accounting for it)`, index: idx, size }; const fs = (await sizeOf(path.join(dir, `${name}-Frag${n}`))) ?? 0; // REVIEW-6 6: an empty kept fragment is no proof (a crash can leave the // state flushed and the fragment and the append not). if (fs === 0) return { ok: false, why: `fragment ${n} of ${name} is empty`, index: idx, size }; expected += fs; } if (size === expected) { // ... and the file ENDS with the last fragment's bytes. if (idx > checkpoint.index) { const last = await readFile(path.join(dir, `${name}-Frag${idx}`)); const tail = Buffer.alloc(last.length); const fh = await open(file, "r"); try { await fh.read(tail, 0, last.length, size - last.length); } finally { await fh.close(); } if (!tail.equals(last)) return { ok: false, why: `${name} does not end with its fragment ${idx}`, index: idx, size }; } return { ok: true, index: idx, size, expected, checkpoint, kept }; } if (size < expected) return { ok: false, why: `${name} is ${size} bytes, its fragments ${expected}: bytes the state counts are not in the file`, index: idx, size, expected }; return { ok: false, why: `${name} is ${size} bytes, ${size - expected} more than its fragments 1..${idx}`, index: idx, size, expected, excess: size - expected, next: idx + 1 }; } export type Reconciled = { ok: true; truncated?: { from: number; to: number } } | { ok: false; why: string }; // The equation, and the one repair. `apply` false: what it would do. export async function reconcileStream(dir: string, name: string, apply: boolean, say: (s: string) => void = () => {}): Promise { const a = await accountStream(dir, name); if (a.ok) return { ok: true }; if (a.excess === undefined || a.expected === undefined || a.size === undefined) return { ok: false, why: a.why }; const next = path.join(dir, `${name}-Frag${a.next}`); const frag = await readFile(next).catch(() => null); if (!frag) return { ok: false, why: `${a.why}, and fragment ${a.next} is not kept: the excess cannot be proven a torn append` }; if (a.excess > frag.length) return { ok: false, why: `${a.why}, more than fragment ${a.next} (${frag.length} bytes)` }; const tail = Buffer.alloc(a.excess); const fh = await open(path.join(dir, name), "r"); try { await fh.read(tail, 0, a.excess, a.expected); } finally { await fh.close(); } if (!tail.equals(frag.subarray(0, a.excess))) return { ok: false, why: `${a.why}, and the excess is not the start of fragment ${a.next}` }; if (apply) { await truncate(path.join(dir, name), a.expected); say(`${name}: truncated from ${a.size} to ${a.expected} bytes — its last ${a.excess} bytes were the first ${a.excess} of fragment ${a.next} (a stop inside its append); fragment ${a.next} is fetched again.`); } return { ok: true, truncated: { from: a.size, to: a.expected } }; } // A checkpoint written so a crash leaves the old one or the new one, whole: // a temp file, fsynced, renamed over, the directory fsynced. export async function writeCheckpointDurable(dir: string, name: string, cp: FragCheckpoint): Promise { const final = path.join(dir, checkpointName(name)); const tmp = `${final}.tmp`; const fh = await open(tmp, "w"); try { await fh.writeFile(JSON.stringify(cp)); await fh.sync(); } finally { await fh.close(); } await rename(tmp, final); const d = openSync(dir, "r"); try { fsyncSync(d); } finally { closeSync(d); } } export type Pruned = { pruned: number; index: number } | { pruned: 0; why: string }; // THE WATCHDOG'S PRUNE: on a stable read (the index the same before and after // the size), when the equation holds, the checkpoint moves to the index — // written and fsynced FIRST — and only then are the fragments it covers // deleted (and any older one a crash left). A crash between the two leaves // fragments the next accounting ignores (they are at or below the checkpoint). export async function pruneStream(dir: string, name: string, deps: { remove?: (f: string) => Promise } = {}): Promise { const file = path.join(dir, name); const before = await readYtdlIndex(file); const a = await accountStream(dir, name); const after = await readYtdlIndex(file); if (typeof before !== "number" || before !== after) return { pruned: 0, why: "the state moved during the read" }; if (!a.ok) return { pruned: 0, why: a.why }; if (a.index > a.checkpoint.index) await writeCheckpointDurable(dir, name, { index: a.index, bytes: a.size }); const remove = deps.remove ?? ((f: string) => rm(f, { force: true })); let pruned = 0; for (const n of a.kept) { if (n > a.index) continue; await remove(path.join(dir, `${name}-Frag${n}`)); pruned++; } return { pruned, index: a.index }; } // Short of disk (DESIGN-4: the recording goes on, resumability goes): every // kept fragment up to the state's index is deleted, without accounting. export async function dropFragments(dir: string, name: string): Promise { const file = path.join(dir, name); // REVIEW-6 11: read twice (yt-dlp rewrites it); no index, nothing dropped — // never the fragment being downloaded. let idx = await readYtdlIndex(file); if (typeof idx !== "number") { await new Promise((r) => setTimeout(r, 50)); idx = await readYtdlIndex(file); } if (typeof idx !== "number") return 0; const names = await readdir(dir).catch(() => [] as string[]); let n = 0; for (const k of fragNumbers(name, names)) { if (k > idx) continue; await rm(path.join(dir, `${name}-Frag${k}`), { force: true }); n++; } return n; } // REVIEW-6 2: BEFORE EVERY RESUME, every kept fragment past the state's // index goes. Under --no-part a complete `-Frag` gets a Range request // past its end on the resume: 416, "Giving up", exit 3, nothing recorded // (measured, LOG REVIEW-6). A partial one would be resumed by Range — it goes // too; it costs a re-download, the whole one costs the resume. export async function dropFragmentsAbove(dir: string, name: string, index: number): Promise { const names = await readdir(dir).catch(() => [] as string[]); const gone: number[] = []; for (const k of fragNumbers(name, names)) { if (k <= index) continue; await rm(path.join(dir, `${name}-Frag${k}`), { force: true }); gone.push(k); } return gone; } // REVIEW-6 3: does the stream file hold exactly its kept fragments 1..N, in // order, every one non-empty? (Before the fragments are removed: they may be // the only whole copy.) null: no fragments kept to compare with. export async function streamEqualsFragments(dir: string, name: string): Promise<{ ok: true; fragments: number } | { ok: false; why: string } | null> { const names = await readdir(dir).catch(() => [] as string[]); const kept = fragNumbers(name, names); if (!kept.length) return null; if (kept[0] !== 1 || kept[kept.length - 1] !== kept.length) return { ok: false, why: `${name}: its kept fragments are not 1..${kept.length} without a gap` }; const file = path.join(dir, name); const size = (await stat(file).catch(() => null))?.size ?? 0; let off = 0; const fh = await open(file, "r").catch(() => null); if (!fh) return { ok: false, why: `${name} does not open` }; try { for (const n of kept) { const frag = await readFile(path.join(dir, `${name}-Frag${n}`)); if (!frag.length) return { ok: false, why: `${name}: fragment ${n} is empty` }; const here = Buffer.alloc(frag.length); const { bytesRead } = await fh.read(here, 0, frag.length, off); if (bytesRead !== frag.length || !here.equals(frag)) return { ok: false, why: `${name}: its bytes at ${off} are not fragment ${n}` }; off += frag.length; } } finally { await fh.close(); } if (off !== size) return { ok: false, why: `${name} is ${size} bytes, its ${kept.length} fragments ${off}` }; return { ok: true, fragments: kept.length }; } // Fragment numbers missing between kept ones (a skip leaves no Frag file). export function fragmentGaps(kept: readonly number[], from: number): number[] { const out: number[] = []; let want = from; for (const n of kept) { while (want < n) out.push(want++); want = n + 1; } return out; }