// STORED TEXT ON DISK — THE WRITE HALF: the one way to delete a declared name // (`removeStoredText`), the compressor (`compressStoredText`) and its checker // (`verifyStoredText`). The names and the rules are lib/storedText.ts; the // read path is lib/storedText-server.ts. // // THE ONE WAY TO DELETE A DECLARED NAME. A deleter that removed only the plain // `transcript.live_chat.json` would RESURRECT an older stored // `transcript.live_chat.json.zst` beside it — the one failure here that is // silent and wrong. So every deleter of a declared name calls // `removeStoredText`, which removes both forms, each through // `removeMediaFile` (a tier link's bytes go too). The stored form goes FIRST: // a process killed between the two leaves the plain file — the truth — never // the older stored copy alone. // // lib/, so no controller import (architecture.test.ts). SERVER-ONLY. import path from "node:path"; import { createHash } from "node:crypto"; import { createReadStream, readFileSync, type Stats } from "node:fs"; import { link, lstat, lutimes, open, readdir, readFile, readlink, rename, rm, stat, statfs, symlink, utimes, writeFile, } from "node:fs/promises"; import { Transform, Writable } from "node:stream"; import { pipeline } from "node:stream/promises"; import { MEDIA_LINK_NAME, TIER_RELOCATION_MARKER, removeMediaFile, renameMediaFile, tierMediaFile, } from "./mediaTier-server"; import { keptChatCaptureName } from "./mediaTier"; import { onDrive, stalledLocationForPath } from "./storageHealth"; import { LIVE_RECORDING_FILENAME } from "./liveCapture"; import { isStoredCaptionName, isStoredTextName, plainNameOf, storedNameOf } from "./storedText"; import { parseVtt } from "./vtt"; import { unpinAfterPickDeleted } from "./transcriptPin-server"; import { StoredTextCorruptError, createStoredTextCompressor, createStoredTextDecompressor, frameContentSize, } from "./storedText-server"; // Remove `name` in both forms (any name: for one that is not declared, its // `.zst` sibling is not this module's and is removed only if it is there — // nothing else ever writes one) AND every leftover of a stopped run on it — a // temp, and above all a set-aside original (`..retire-…`), which is a // whole copy: left behind, the next compress run would find the name free and // could bring the deleted file back (REVIEW-1 F2, captions lane). Under the // file's lock, so no run of ours is between its steps while the file goes; // a run that holds it is waited for (a few seconds), then this throws and // nothing is removed. Missing is not an error. // // A REFUSAL, NEVER A THROW, when it cannot take the lock (REVIEW-2 N2): a run // that holds it past the wait, or a disk so full the lock's few bytes do not // fit. Then NOTHING is removed and `{refused}` says why; the caller reports it. export type RemoveStoredTextOutcome = { removed: true } | { refused: string }; export async function removeStoredText(videoDir: string, name: string): Promise { for (let attempt = 0; ; attempt++) { let done: boolean; try { done = await withFileLock(videoDir, name, false, async () => { await removeMediaFile(videoDir, storedNameOf(name)); await removeMediaFile(videoDir, name); await removeLeftoversOf(videoDir, name); return true; }); } catch (err) { if (err instanceof LockUnavailableError) return { refused: `${name} not deleted: ${err.message}` }; throw err; } if (done) return { removed: true }; if (attempt >= 40) { return { refused: `${name} not deleted: it is being compressed or restored right now — try again in a moment` }; } await new Promise((r) => setTimeout(r, 250)); } } // Every leftover of a run on `name` in the video dir — temps and set-asides, // whoever named them — each through removeMediaFile (a set-aside may be a // tier link: its bytes go too). Only for a deleter: the file is being removed // on purpose, so a copy of it must not survive to be adopted later. async function removeLeftoversOf(videoDir: string, name: string): Promise { const re = leftoverRes(name); for (const e of await readdir(videoDir).catch(() => [] as string[])) { if (re.temp.test(e) || re.retire.test(e)) await removeMediaFile(videoDir, e); } } // ── THE COMPRESSOR ────────────────────────────────────────────────────────── // // `compressStoredText(videoDir, name)` puts ONE declared file into its stored // form, where its bytes are (never across disks): for a tier link // `data// -> ../../media//` the work happens in // `media//` and the stored form gets a tier link of its own; for a real // file, in `data//`. No `mkdir` anywhere: the work dir holds the file, so // a destination on an unmounted drive is never materialised. // // 1. S (the bytes) is streamed through sha256 and zstd (level 9, checksum, // the size pledged) into a temp T opened `wx`; T is fsynced. // 2. T is streamed back through the decompressor: sha256 and length must // equal S's, and S must be unchanged (inode, size, mtime) — else T goes. // 3. T is given S's times (numeric seconds) and renamed to Z (`.zst`); // the dir is fsynced. Z ONLY EVER APPEARS BY THE RENAME OF A VERIFIED, // FSYNCED T: a partial stored file can only be a temp, never Z. // 4. Tiered: Z's link is placed (made beside, renamed in) with the plain // link's own times — what an `lstat` of the name answered before. // 5. P (the plain name) is set aside (`..retire-`), checked to be // the very file of step 1, and removed through `removeMediaFile`. A // writer that replaced P meanwhile is put back: outcome `changed`. // 6. A real Z on a channel with a media tier is tiered by the hook. // // A RUN AFTER A KILL AT ANY STEP finishes or undoes it: a dead run's temp is // discarded; a Z beside P is verified against P before P goes; a retired P // whose name is free is renamed back (and then verified like any P); a // dangling P beside a whole Z is removed. BOTH FORMS PRESENT WITH DIFFERENT // CONTENT is refused and reported — nothing is touched, and readers keep // reading the plain one. // // A LEFTOVER IS DEAD unless the process that named it is running NOW: its // name carries the pid and that process's START TOKEN (boot id + start time, // `processStartToken`), so a pid reused by a later process — an editor // container that comes back with the same pid — does not keep a dead run's // set-aside alive. A leftover named with THIS process's pid is dead too: the // per-file lock below means no run of ours is on this file at this moment. // // A WRITER THAT REPLACED P DURING A RUN (`changed`): the new P is the truth // and is read; the stored form beside it holds the earlier content and is // KEPT. Two captures with different content are never settled by deleting // one (REVIEW-2 R1): the pair is `both-differ`, for a person. export type CompressSkipReason = | "not-declared" | "relocating" // the channel's media is moving (its marker stands) | "partial" // a `.part…` beside it: a capture or download in progress | "recording" // the video's live-recording.json says `recording` (or cannot be read) | "busy" // a job is running for this video, or this file is being compressed | "recent" // written within the quiet period | "unreachable" // on a media drive that is not mounted or not answering | "dangling" // a plain link whose bytes are gone, and no stored form | "foreign-link" // a link that does not point into this channel's media/ | "not-a-file" | "low-space" // the disk that holds it is too full for the temp | "both-differ" // both forms present, different content: refused | "stored-corrupt" // a stored form that does not decode | "retired-kept"; // a set-aside original that is neither the stored content nor free to go back export type CompressOutcome = | { status: "compressed"; before: number; after: number; tiered: boolean } | { status: "already"; after: number } | { status: "absent" } | { status: "changed" } | { status: "skipped"; reason: CompressSkipReason; detail?: string }; // A test's kill point: `crashAt` throws a CompressKill there, and NOTHING // after it runs — no cleanup, no rollback — which is what a SIGKILL leaves. export type CompressKillPoint = | "compressing" // T partly written | "written" // T whole and fsynced, not verified | "verified" // T verified, not renamed | "placed" // Z in place (tiered: no link yet) | "linked" // Z's tier link placed | "retired" // P set aside, not removed // The restore (`restoreStoredText`), in its order: | "restoring" // R (the plain temp) partly written | "restore-written" // R whole and fsynced, not verified | "restore-verified" // R verified against a fresh decode of Z, not placed | "restore-placed" // P in place (tiered: in media//, no link yet) | "restore-linked"; // P's tier link placed; Z not yet removed export class CompressKill extends Error { constructor(readonly point: CompressKillPoint) { super(`killed at ${point}`); this.name = "CompressKill"; } } export type CompressOptions = { // Leave a file younger than this alone (the migration: 10 min). 0 = none. quietMs?: number; now?: () => number; // A job is running for this video (the editor's registry). isBusy?: () => boolean; // Paced reads: awaited before each chunk read moves on. throttle?: (bytes: number) => Promise; // Free space the disk must keep beyond the temp (default 2 GiB). reserveBytes?: number; // The pid and start token temps are named for (tests: a dead pid, to stand // for a kill). pid?: number; token?: string; crashAt?: (point: CompressKillPoint) => void; signal?: AbortSignal; onLog?: (line: string) => void; }; type Ident = { dev: number; ino: number; size: number; mtimeMs: number }; const identOf = (s: Stats): Ident => ({ dev: s.dev, ino: s.ino, size: s.size, mtimeMs: s.mtimeMs }); const sameIdent = (a: Ident, b: Ident) => a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs; function errCode(err: unknown): string | undefined { return (err as NodeJS.ErrnoException | null)?.code; } function processAlive(pid: number): boolean { try { process.kill(pid, 0); return true; } catch (err) { return errCode(err) === "EPERM"; } } // ── WHO NAMED A LEFTOVER, AND IS IT STILL RUNNING ─────────────────────────── // // A process's START TOKEN: the kernel's boot id (8 hex) and the process's // start time in clock ticks since boot (`/proc//stat` field 22), base // 36. Two processes that ever had the same pid on this machine have different // tokens. Where there is no /proc, this process's token is its time origin and // another's is unknown (null). function bootIdPrefix(): string { try { return readFileSync("/proc/sys/kernel/random/boot_id", "utf8").replace(/[^0-9a-f]/g, "").slice(0, 8); } catch { return ""; } } export function processStartToken(pid: number = process.pid): string | null { try { const s = readFileSync(`/proc/${pid}/stat`, "utf8"); // After the command's ")" the fields start at field 3; field 22 is the // start time. const ticks = s.slice(s.lastIndexOf(")") + 2).split(" ")[19]; if (ticks && /^\d+$/.test(ticks)) return `${bootIdPrefix()}${Number(ticks).toString(36)}`; } catch { /* no /proc, or the process is gone */ } return pid === process.pid ? `t${Math.floor(performance.timeOrigin).toString(36)}` : null; } let ownToken: string | undefined; function selfToken(): string { return (ownToken ??= processStartToken(process.pid) ?? "t0"); } // A leftover's suffix: `--` (a name from before the token, // `-`, is still read). const LEFTOVER_SUFFIX = "-(\\d+)(?:-([0-9a-z]+))?"; type Owner = { pid: number; token?: string }; // Is the run that named this leftover running now? Never this process's own // (`self`): the per-file lock means none of ours is on the file. Another pid: // alive AND (when the name carries a token) the same process start. function ownerRunning(owner: Owner, self: number): boolean { if (owner.pid === self) return false; if (!processAlive(owner.pid)) return false; if (owner.token === undefined) return true; // a pid-only name: cannot tell, so alive const now = processStartToken(owner.pid); return now === null || now === owner.token; } function ownerOf(m: RegExpExecArray | null): Owner | null { if (!m) return null; return { pid: Number(m[1]), ...(m[2] ? { token: m[2] } : {}) }; } const lstatOrNull = (p: string) => lstat(p).catch(() => null); async function fsyncDir(dir: string): Promise { const d = await open(dir, "r"); try { await d.sync(); } finally { await d.close(); } } function escapeRe(s: string): string { return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } // A paced read: each chunk waits on the throttle before it moves on. function paced(throttle?: (bytes: number) => Promise): Transform { return new Transform({ transform(chunk: Buffer, _enc, cb) { if (!throttle) return cb(null, chunk); throttle(chunk.length).then( () => cb(null, chunk), (err: Error) => cb(err), ); }, }); } type Digest = { sha: string; bytes: number }; function digestSink(): { sink: Writable; result: () => Digest } { const h = createHash("sha256"); let n = 0; const sink = new Writable({ write(chunk: Buffer, _enc, cb) { h.update(chunk); n += chunk.length; cb(); }, }); return { sink, result: () => ({ sha: h.digest("hex"), bytes: n }) }; } async function headContentSize(file: string): Promise { const fh = await open(file, "r"); try { const head = Buffer.alloc(18); const { bytesRead } = await fh.read(head, 0, 18, 0); return frameContentSize(head.subarray(0, bytesRead)); } finally { await fh.close(); } } // sha256 and length of a file's bytes — `decode`: of its stored content, the // frame's checksum checked by zstd and the length against the header's // content size (which a truncated frame would not reach). async function digestOf( file: string, opts: { decode?: boolean; throttle?: (bytes: number) => Promise } = {}, ): Promise { const { sink, result } = digestSink(); if (!opts.decode) { await pipeline(createReadStream(file), paced(opts.throttle), sink); return result(); } const want = await headContentSize(file); if (want === null) throw new StoredTextCorruptError(file, "no content size in the frame header"); try { await pipeline(createReadStream(file), paced(opts.throttle), createStoredTextDecompressor(), sink); } catch (err) { if (errCode(err) === "ENOENT") throw err; throw new StoredTextCorruptError(file, (err as Error).message); } const d = result(); if (d.bytes !== want) throw new StoredTextCorruptError(file, `decoded ${d.bytes} bytes, header says ${want}`); return d; } // What is at one name in the video dir. type Entry = | { kind: "none" } | { kind: "real"; path: string; l: Stats } | { kind: "link"; path: string; l: Stats; target: string; inMedia: boolean } | { kind: "other"; path: string; l: Stats }; async function entryAt(videoDir: string, name: string): Promise { const p = path.join(videoDir, name); const l = await lstatOrNull(p); if (!l) return { kind: "none" }; if (l.isSymbolicLink()) { let target = ""; try { target = path.resolve(videoDir, await readlink(p)); } catch { /* unreadable: not in media */ } const mediaRoot = path.join(path.dirname(path.dirname(videoDir)), MEDIA_LINK_NAME); return { kind: "link", path: p, l, target, inMedia: !!target && path.dirname(path.dirname(target)) === mediaRoot, }; } if (l.isFile()) return { kind: "real", path: p, l }; return { kind: "other", path: p, l }; } // Whether the channel's media tier answers: a real `media/` (the corpus disk), // or a link to a drive that is mounted and not stalled. "none": no `media`. async function mediaReachable(channelDir: string): Promise<"yes" | "no" | "none"> { const root = path.join(channelDir, MEDIA_LINK_NAME); const l = await lstatOrNull(root); if (!l) return "none"; if (!l.isSymbolicLink()) return l.isDirectory() ? "yes" : "no"; let target: string; try { target = path.resolve(channelDir, await readlink(root)); } catch { return "no"; } if (stalledLocationForPath(target)) return "no"; try { return (await onDrive(target, () => stat(root))).isDirectory() ? "yes" : "no"; } catch { return "no"; } } // A live recording of this video in progress, by its own record — or a record // that cannot be read, which is no proof there is none. async function recordingNow(videoDir: string): Promise { let raw: string; try { raw = await readFile(path.join(videoDir, LIVE_RECORDING_FILENAME), "utf8"); } catch (err) { return errCode(err) !== "ENOENT"; } try { return (JSON.parse(raw) as { status?: unknown })?.status === "recording"; } catch { return true; } } // Where the stored form's bytes are when they are on disk: the name in the // video dir as a real file, or the file its link resolves to. async function storedPathOf(videoDir: string, name: string): Promise { const z = await entryAt(videoDir, storedNameOf(name)); if (z.kind === "real") return z.path; if (z.kind === "link" && z.target && (await stat(z.target).then((st) => st.isFile(), () => false))) { return z.target; } return null; } // ONE RUN PER FILE AT A TIME — the compressor, the restore, the re-fetch's // set-aside and the files card's delete — in two layers: // // - IN THIS PROCESS, a set kept on `globalThis` (Next loads a module once // per bundle layer; a route and a server action must share it — the // storageHealth.ts pattern). Because of it, a leftover named with this // process's pid is never a run in progress. // - ACROSS PROCESSES, a lock file in the video dir, `.stored-text.lock` // (REVIEW-2 R3), made by a hard link of a temp that names its owner (pid // and start token), so it appears whole or not at all. A second process // honours it: held by a run that is running now, the run answers "busy"; // held by a process that is gone (or this pid from an earlier start), it // is stale and is taken over. Two editors on one corpus are an operator's // mistake; this makes them wait for each other instead of interleaving. const g = globalThis as { __archilyzerStoredTextActive?: Set }; const active: Set = (g.__archilyzerStoredTextActive ??= new Set()); export const STORED_TEXT_DIR_LOCK = ".stored-text.lock"; // Is the run that holds a dir lock running now? This process: only when the // token is this start's (another of its runs holds the dir). function lockHolderRunning(owner: Owner): boolean { if (owner.pid === process.pid) return owner.token === selfToken(); return ownerRunning(owner, process.pid); } // The dir lock, or null when a live run holds it. Returns its release. // The dir lock could not be made at all — a full disk (ENOSPC), a read-only // one. Nothing was done; a deleter answers it as a refusal (REVIEW-2 N2). export class LockUnavailableError extends Error { constructor(videoDir: string, cause: Error) { super(`the stored-text lock cannot be made in ${path.basename(videoDir)} (${(cause as NodeJS.ErrnoException).code ?? cause.message})`); this.name = "LockUnavailableError"; } } async function takeDirLock(videoDir: string): Promise<(() => Promise) | null> { const lock = path.join(videoDir, STORED_TEXT_DIR_LOCK); const me = { pid: process.pid, token: selfToken() }; const tmp = path.join(videoDir, `${STORED_TEXT_DIR_LOCK}.${me.pid}-${me.token}-${Math.random().toString(36).slice(2, 8)}`); try { // Inside the try whose `finally` removes it: on a FULL disk `wx` creates // the file and then fails to write it, and the empty temp must not stay // behind, one per file visited (REVIEW-2 N2). try { await writeFile(tmp, JSON.stringify(me), { flag: "wx" }); } catch (err) { // No video dir: nothing to lock and nothing to do. if (errCode(err) === "ENOENT") return async () => {}; throw new LockUnavailableError(videoDir, err as Error); } for (let attempt = 0; attempt < 3; attempt++) { try { await link(tmp, lock); const ino = (await lstat(lock)).ino; return async () => { const l = await lstatOrNull(lock); if (l && l.ino === ino) await rm(lock, { force: true }); }; } catch (err) { if (errCode(err) !== "EEXIST") throw err; } const held = await lstatOrNull(lock); if (!held) continue; let owner: Owner | null = null; try { const o = JSON.parse(await readFile(lock, "utf8")) as { pid?: unknown; token?: unknown }; if (typeof o.pid === "number") owner = { pid: o.pid, ...(typeof o.token === "string" ? { token: o.token } : {}) }; } catch { /* unreadable: no owner to honour */ } if (owner && lockHolderRunning(owner)) return null; // Stale: moved aside, and removed only if it is the very file judged — // another process's fresh lock that took its place goes back. const aside = path.join(videoDir, `${STORED_TEXT_DIR_LOCK}.stale-${me.pid}-${me.token}`); await rename(lock, aside).catch(() => {}); const a = await lstatOrNull(aside); if (a && a.ino !== held.ino) { await link(aside, lock).catch(() => {}); await rm(aside, { force: true }); return null; } await rm(aside, { force: true }); } return null; } finally { await rm(tmp, { force: true }); } } async function withFileLock(videoDir: string, name: string, busy: T, fn: () => Promise): Promise { const key = path.resolve(videoDir, name); if (active.has(key)) return busy; active.add(key); try { const release = await takeDirLock(videoDir); if (!release) return busy; try { return await fn(); } finally { await release(); } } finally { active.delete(key); } } export async function compressStoredText( videoDir: string, name: string, opts: CompressOptions = {}, ): Promise { if (!isStoredTextName(name)) return { status: "skipped", reason: "not-declared" }; return withFileLock(videoDir, name, { status: "skipped", reason: "busy", detail: "being compressed" } as CompressOutcome, () => compressOne(videoDir, name, opts), ); } // The leftovers a run of the compressor or the restore leaves in a dir, by // name: temps (never a copy) and the compressor's set-aside original. function leftoverRes(name: string) { const stored = storedNameOf(name); return { // `.X.zst.compressing-…`, `.X.zst.stlink-…`, `.X.restoring-…`, `.X.stlink-…` // — never the tier hook's own `.X.tierlink-` (REVIEW-2 N2). temp: new RegExp( `^\\.(?:${escapeRe(stored)}\\.(?:compressing|stlink)|${escapeRe(name)}\\.(?:restoring|stlink))${LEFTOVER_SUFFIX}$`, ), retire: new RegExp(`^\\.${escapeRe(name)}\\.retire${LEFTOVER_SUFFIX}$`), }; } // Does this listing hold a leftover of a run on `name`? (What the job's // survey visits even when neither form is there.) export function hasStoredTextLeftover(entries: readonly string[], name: string): boolean { const re = leftoverRes(name); return entries.some((e) => re.temp.test(e) || re.retire.test(e)); } // The declared names a listing holds a stopped run's leftover FOR — a caption // killed after its original was set aside has neither form under its name, // only `.transcript.en.vtt.retire--`, and the job's survey must // still visit it (`compress-text` captions, which finds names by listing). export function storedTextLeftoverNames(entries: readonly string[]): string[] { const out = new Set(); for (const e of entries) { const m = /^\.(.+?)(?:\.zst)?\.(?:compressing|stlink|restoring|retire)-\d+(?:-[0-9a-z]+)?$/.exec(e); if (!m || !isStoredTextName(m[1])) continue; if (hasStoredTextLeftover([e], m[1])) out.add(m[1]); } return [...out].sort(); } type RunCtx = { pid: number; token: string; log: (line: string) => void; reachable: () => Promise<"yes" | "no" | "none">; }; function runCtx(videoDir: string, opts: CompressOptions): RunCtx { const channelDir = path.dirname(path.dirname(videoDir)); let reach: "yes" | "no" | "none" | undefined; return { pid: opts.pid ?? process.pid, token: opts.token ?? selfToken(), log: opts.onLog ?? (() => {}), reachable: async () => (reach ??= await mediaReachable(channelDir)), }; } // Dead runs' temps in `dir` removed — scratch, never a copy. async function removeDeadTemps(dir: string, name: string, ctx: RunCtx): Promise<"ok" | "live"> { const re = leftoverRes(name); let live = false; for (const e of await readdir(dir).catch(() => [] as string[])) { const owner = ownerOf(re.temp.exec(e)); if (!owner) continue; if (ownerRunning(owner, ctx.pid)) live = true; else await rm(path.join(dir, e), { force: true }); } return live ? "live" : "ok"; } // REPAIR, BEFORE ANY RUN ON A FILE (the compressor's and the restore's): a dead // run's leftovers in the video dir, each finished or undone. A live one of // another process: "busy". Null: carry on. async function repairLeftovers( videoDir: string, name: string, entries: readonly string[], ctx: RunCtx, ): Promise { const skip = (reason: CompressSkipReason, detail?: string): CompressOutcome => ({ status: "skipped", reason, ...(detail ? { detail } : {}), }); if ((await removeDeadTemps(videoDir, name, ctx)) === "live") return skip("busy", "another process is on this file"); const re = leftoverRes(name); for (const e of entries) { const owner = ownerOf(re.retire.exec(e)); if (!owner) continue; if (ownerRunning(owner, ctx.pid)) return skip("busy", "another process is on this file"); const r = await entryAt(videoDir, e); if (r.kind === "none") continue; if (r.kind === "link" && (await ctx.reachable()) !== "yes") return skip("unreachable"); const p = await entryAt(videoDir, name); if (p.kind === "none") { // The original was set aside and not removed. It is ADOPTED — the file // again, verified like any plain file — ONLY when it is plainly an // interrupted run's of this compressor (its name carries the run's pid // AND start token, and that process is gone: checked above) AND no // deletion happened since: the stored form the run made BEFORE it set // the original aside is still here. Every deleter removes both forms and // the set-aside together, so a set-aside with no stored form beside it // means the file was deleted some other way: it is NOT brought back but // kept, listed for a person (REVIEW-1 F2, captions lane). const z = await entryAt(videoDir, storedNameOf(name)); if (owner.token === undefined || z.kind === "none") { ctx.log( ` ${e} kept for a person: ${owner.token === undefined ? "a set-aside named before runs carried a start token" : `no ${storedNameOf(name)} beside it — deleted since?`}`, ); return skip("retired-kept", `${e}: not adopted (${owner.token === undefined ? "no start token" : "no stored form"})`); } await rename(path.join(videoDir, e), path.join(videoDir, name)); ctx.log(` restored ${e} as ${name}`); continue; } if (r.kind === "link" && p.kind === "link" && r.target !== "" && r.target === p.target) { // A second name for the plain file's own bytes (a newer file tiered // over the same target): only the name goes, never the bytes. await rm(path.join(videoDir, e)); continue; } // Removed only when it is the stored content exactly; otherwise kept for // a person, with the file left as it is. const z = await storedPathOf(videoDir, name); let removable = false; if (z) { try { const [rd, zd] = await Promise.all([digestOf(path.join(videoDir, e)), digestOf(z, { decode: true })]); removable = rd.sha === zd.sha && rd.bytes === zd.bytes; } catch { removable = false; } } if (!removable) return skip("retired-kept", e); await removeMediaFile(videoDir, e); } return null; } // A plain file in media// with no link to it, beside a stored form's // bytes there: what a restore killed between placing and linking leaves. // Removed when it is the stored content exactly (a copy; the stored form // stays whole), else kept for a person. async function leftoverPlainInMedia( videoDir: string, name: string, zTarget: string, ctx: RunCtx, ): Promise { const mediaDir = path.dirname(zTarget); if ((await removeDeadTemps(mediaDir, name, ctx)) === "live") { return { status: "skipped", reason: "busy", detail: "another process is on this file" }; } const beside = path.join(mediaDir, name); if (!(await lstatOrNull(beside))?.isFile()) return null; const [bd, zd] = await Promise.all([ digestOf(beside).catch(() => null), digestOf(zTarget, { decode: true }).catch(() => null), ]); if (bd && zd && bd.sha === zd.sha && bd.bytes === zd.bytes) { await rm(beside); ctx.log(` removed an unlinked copy of ${name} in media/ (a restore that was stopped)`); return null; } return { status: "skipped", reason: "retired-kept", detail: `media/${path.basename(mediaDir)}/${name}` }; } async function compressOne(videoDir: string, name: string, opts: CompressOptions): Promise { const ctx = runCtx(videoDir, opts); const { pid, token, log, reachable } = ctx; const crash = (p: CompressKillPoint) => opts.crashAt?.(p); const stored = storedNameOf(name); const channelDir = path.dirname(path.dirname(videoDir)); const skip = (reason: CompressSkipReason, detail?: string): CompressOutcome => ({ status: "skipped", reason, ...(detail ? { detail } : {}), }); // ── refusals: nothing is touched ────────────────────────────────────────── if (await lstatOrNull(path.join(channelDir, TIER_RELOCATION_MARKER))) return skip("relocating"); const entries = await readdir(videoDir).catch(() => [] as string[]); if (entries.some((e) => e.startsWith(`${name}.part`))) return skip("partial"); if (await recordingNow(videoDir)) return skip("recording"); if (opts.isBusy?.()) return skip("busy"); // ── repair: a dead run's leftovers in the video dir ─────────────────────── const repaired = await repairLeftovers(videoDir, name, entries, ctx); if (repaired) return repaired; // ── the plain file ──────────────────────────────────────────────────────── const p = await entryAt(videoDir, name); const zEntry = await entryAt(videoDir, stored); if (zEntry.kind === "other") return skip("not-a-file", stored); if (p.kind === "none") { if (zEntry.kind === "none") return { status: "absent" }; if (zEntry.kind === "link" && zEntry.inMedia) { if ((await reachable()) !== "yes") return skip("unreachable"); // A restore killed after it placed the plain bytes in media// and // before their link: a copy of the stored content, which is kept. const left = await leftoverPlainInMedia(videoDir, name, zEntry.target, ctx); if (left) return left; } if (zEntry.kind === "real") await tierMediaFile(videoDir, stored, { onLog: log }); const z = await storedPathOf(videoDir, name); return { status: "already", after: z ? ((await stat(z).catch(() => null))?.size ?? 0) : 0 }; } if (p.kind === "other") return skip("not-a-file"); if (p.kind === "link" && !p.inMedia) return skip("foreign-link"); if ((p.kind === "link" || zEntry.kind === "link") && (await reachable()) !== "yes") { return skip("unreachable"); } let s: Stats; try { s = await stat(p.path); } catch (err) { if (p.kind !== "link" || (errCode(err) !== "ENOENT" && errCode(err) !== "ENOTDIR")) { return skip("unreachable", (err as Error).message); } // A plain link whose bytes are gone, on a media tier that answers (an // interrupted removal): with a whole stored form beside it, only the link // is left to remove. const z = await storedPathOf(videoDir, name); if (!z) return skip("dangling"); try { await digestOf(z, { decode: true, throttle: opts.throttle }); } catch (e) { return skip("stored-corrupt", (e as Error).message); } await removeMediaFile(videoDir, name); return { status: "already", after: (await stat(z)).size }; } if (!s.isFile()) return skip("not-a-file"); const now = opts.now ?? Date.now; // The later of mtime and ctime: a backdated mtime (`touch -d`, a copy // that kept its times) is no proof the file is not being written. if (opts.quietMs && now() - Math.max(s.mtimeMs, s.ctimeMs) < opts.quietMs) return skip("recent"); const tiered = p.kind === "link"; const workDir = tiered ? path.dirname(p.target) : videoDir; const bytesPath = tiered ? p.target : p.path; const first = identOf(s); if (workDir !== videoDir && (await removeDeadTemps(workDir, name, ctx)) === "live") { return skip("busy", "another process is on this file"); } // ── the stored form: already there (a run killed after it landed), or made ─ let zKind: "none" | "real" | "link" = zEntry.kind; let zPath = await storedPathOf(videoDir, name); if (zKind === "link" && !zPath) { // A stored link whose bytes are gone, on a tier that answers: no copy. await removeMediaFile(videoDir, stored); zKind = "none"; } if (zKind === "none" && tiered) { // Placed but not yet linked: the bytes beside the plain file's. const beside = path.join(workDir, stored); if ((await lstatOrNull(beside))?.isFile()) zPath = beside; } // The stored file's identity once it is verified (or made): what the // last look before the original goes compares with. let zIdent: Ident | null = null; if (zPath) { let zd: Digest; try { zd = await digestOf(zPath, { decode: true, throttle: opts.throttle }); } catch (e) { return skip("stored-corrupt", (e as Error).message); } const sd = await digestOf(bytesPath, { throttle: opts.throttle }); if (zd.sha !== sd.sha || zd.bytes !== sd.bytes) { // Recorded, so the job's survey does not count the pair as work on every // run (REVIEW-1 N2): it waits for a person until either form changes. await recordBothDiffer(videoDir, name).catch(() => {}); return skip("both-differ", `${name} (${sd.bytes} bytes) and ${stored} (${zd.bytes} bytes) differ`); } // The same content: given the plain file's times, exactly. await utimes(zPath, s.atimeMs / 1000, s.mtimeMs / 1000); zIdent = identOf(await stat(zPath)); } else { const free = await statfs(workDir).then( (f) => f.bavail * f.bsize, () => Infinity, ); if (free < s.size * 0.3 + (opts.reserveBytes ?? 2 * 1024 ** 3)) return skip("low-space"); const made = await makeStored(bytesPath, workDir, stored, s, first, `${pid}-${token}`, opts); if (made !== "ok") return made; zPath = path.join(workDir, stored); zIdent = identOf(await stat(zPath)); crash("placed"); } // ── its tier link ───────────────────────────────────────────────────────── if (tiered && zKind === "none") { const tmpLink = path.join(videoDir, `.${stored}.stlink-${pid}-${token}`); await rm(tmpLink, { force: true }); await symlink(path.relative(videoDir, zPath), tmpLink); // The PLAIN LINK's times: what an `lstat` of the name answered. await lutimes(tmpLink, p.l.atimeMs / 1000, p.l.mtimeMs / 1000); await rename(tmpLink, path.join(videoDir, stored)); await fsyncDir(videoDir); crash("linked"); } else if (tiered && zKind === "link") { await lutimes(path.join(videoDir, stored), p.l.atimeMs / 1000, p.l.mtimeMs / 1000); } // ── the original goes: set aside, checked, removed ─────────────────────── // A move of this channel's media that began meanwhile (the tier hook's // rule): the original stays — the stored form beside it is the same // content, and the next run finishes. if (await lstatOrNull(path.join(channelDir, TIER_RELOCATION_MARKER))) return skip("relocating"); const retired = `.${name}.retire-${pid}-${token}`; const retiredPath = path.join(videoDir, retired); try { await rename(p.path, retiredPath); } catch (err) { if (errCode(err) !== "ENOENT") throw err; // The original was removed since its last look. Every in-app deleter // holds this file's lock, so what removed it is OUTSIDE the lock — // yt-dlp's own overwrite in a re-download, which deletes the plain file // and fetches after. The verified stored copy is KEPT (REVIEW-2 N3): if // that fetch fails (a 429, a video gone) it is the caption; a new plain // file landing later is `same` or `both-differ`, both safe. log(` ${name} was removed while it was being compressed: the verified stored copy is kept`); return { status: "changed" }; } crash("retired"); const nowL = await lstatOrNull(retiredPath); const nowS = await stat(retiredPath).catch(() => null); if (!(nowL && nowS && nowL.ino === p.l.ino && sameIdent(identOf(nowS), first))) { // A writer replaced the file after it was read: it is the truth again. let kept = false; if (!(await lstatOrNull(p.path))) { await rename(retiredPath, p.path); } else { // An even newer file is already under the name: what was set aside is // a second name for its bytes (only the name goes), or the stored // content (it goes), or neither — kept, for a person. const r = await entryAt(videoDir, retired); const q = await entryAt(videoDir, name); if (r.kind === "link" && q.kind === "link" && r.target !== "" && r.target === q.target) { await rm(retiredPath); } else { const zd = await digestOf(zPath, { decode: true }).catch(() => null); const rd = await digestOf(retiredPath).catch(() => null); if (zd && rd && zd.sha === rd.sha && zd.bytes === rd.bytes) await removeMediaFile(videoDir, retired); else { kept = true; log(` kept ${retired} beside the newer ${name}: it is neither`); } } } // TWO DIFFERENT CAPTURES ARE NEVER SETTLED BY DELETING ONE (REVIEW-2 // R1): the new file under the name is what readers read; the stored form // beside it holds the content it replaced and is KEPT — the pair is // `both-differ` for a person (the files card deletes one named form). void kept; log(` ${name} changed while it was being compressed: the new file is kept and read; the stored copy of the earlier content is kept beside it (both-differ, for a person)`); return { status: "changed" }; } // THE STORED FORM, LOOKED AT AGAIN right before the original goes (REVIEW-2 // R3): still a regular file, and the very one verified (another process's // run could have replaced or removed it). Otherwise the original goes back. const zNow = await stat(path.join(videoDir, stored)).catch(() => null); if (!zNow || !zNow.isFile() || !zIdent || zNow.ino !== zIdent.ino || zNow.size !== zIdent.size || zNow.dev !== zIdent.dev) { if (!(await lstatOrNull(p.path))) await rename(retiredPath, p.path); log(` ${stored} is not the file that was verified any more: ${name} is left as it was`); return { status: "changed" }; } await removeMediaFile(videoDir, retired); await fsyncDir(videoDir); // A writer that landed a new file under the name after the original was // set aside: it is the truth, and the stored copy (the earlier content) is // kept beside it — `changed`, both-differ for a person (REVIEW-2 R1). if (await wholePlainAt(videoDir, name)) { log(` ${name} was written again while it was being compressed: the new file is kept and read; the stored copy of the earlier content is kept beside it`); return { status: "changed" }; } // ── a real stored file on a channel with a media tier: the hook ─────────── let nowTiered = tiered && zKind !== "real"; if (!nowTiered) nowTiered = (await tierMediaFile(videoDir, stored, { onLog: log })) === "tiered"; const after = (await stat(path.join(videoDir, stored)).catch(() => null))?.size ?? 0; return { status: "compressed", before: s.size, after, tiered: nowTiered }; } class ChangedError extends Error {} // A plain file under the name that opens as a regular file (through its link). async function wholePlainAt(videoDir: string, name: string): Promise { return stat(path.join(videoDir, name)).then((st) => st.isFile(), () => false); } // Steps 1–3: S → T (verified) → Z. "ok", or the outcome that stops the file. async function makeStored( bytesPath: string, workDir: string, stored: string, s: Stats, first: Ident, owner: string, // `-` opts: CompressOptions, ): Promise<"ok" | CompressOutcome> { const tmp = path.join(workDir, `.${stored}.compressing-${owner}`); const crash = (p: CompressKillPoint) => opts.crashAt?.(p); try { const fh = await open(tmp, "wx"); let written: Digest; try { const h = createHash("sha256"); let n = 0; let chunks = 0; const tap = new Transform({ transform(chunk: Buffer, _enc, cb) { const go = () => { h.update(chunk); n += chunk.length; cb(null, chunk); }; if (!opts.throttle) return go(); opts.throttle(chunk.length).then(go, (err: Error) => cb(err)); }, }); const sink = new Writable({ write(chunk: Buffer, _enc, cb) { fh.write(chunk).then( () => { chunks += 1; try { if (chunks === 1) crash("compressing"); cb(); } catch (err) { cb(err as Error); } }, (err: Error) => cb(err), ); }, }); await pipeline( createReadStream(bytesPath), tap, createStoredTextCompressor(s.size), sink, ...(opts.signal ? [{ signal: opts.signal }] : []), ); await fh.sync(); written = { sha: h.digest("hex"), bytes: n }; } finally { await fh.close().catch(() => {}); } crash("written"); if (written.bytes !== s.size) throw new ChangedError(); const back = await digestOf(tmp, { decode: true }); if (back.sha !== written.sha || back.bytes !== written.bytes) { throw new Error(`the stored copy of ${path.basename(bytesPath)} did not read back the same`); } if (!sameIdent(identOf(await stat(bytesPath)), first)) throw new ChangedError(); crash("verified"); await utimes(tmp, s.atimeMs / 1000, s.mtimeMs / 1000); await rename(tmp, path.join(workDir, stored)); await fsyncDir(workDir); return "ok"; } catch (err) { if (err instanceof CompressKill) throw err; await rm(tmp, { force: true }).catch(() => {}); if (err instanceof ChangedError) return { status: "changed" }; // A writer meanwhile (zstd refuses a source whose size moved off the // pledge) is a change, not a failure. const again = await stat(bytesPath).catch(() => null); if (!again || !sameIdent(identOf(again), first)) return { status: "changed" }; throw err; } } // ── THE CHECK ─────────────────────────────────────────────────────────────── // `compress-text {verify: true}`: every stored file decoded in full (its // checksum, its length), and against the plain file when both are present. // Writes nothing. export type VerifyOutcome = | { status: "ok"; bytes: number } | { status: "plain-only" } | { status: "absent" } | { status: "unreachable" } | { status: "corrupt"; detail: string } | { status: "differs" }; export async function verifyStoredText( videoDir: string, name: string, opts: { throttle?: (bytes: number) => Promise } = {}, ): Promise { const zEntry = await entryAt(videoDir, storedNameOf(name)); const plainHere = !!(await lstatOrNull(path.join(videoDir, name))); if (zEntry.kind === "none") return { status: plainHere ? "plain-only" : "absent" }; const z = await storedPathOf(videoDir, name); if (!z) return { status: "unreachable" }; let zd: Digest; try { zd = await digestOf(z, { decode: true, throttle: opts.throttle }); } catch (err) { return { status: "corrupt", detail: (err as Error).message }; } if (plainHere) { const pd = await digestOf(path.join(videoDir, name), { throttle: opts.throttle }).catch(() => null); if (pd && (pd.sha !== zd.sha || pd.bytes !== zd.bytes)) return { status: "differs" }; } return { status: "ok", bytes: zd.bytes }; } // ── THE RESTORE ───────────────────────────────────────────────────────────── // // `restoreStoredText(videoDir, name)` puts ONE stored file back into its plain // form — the compressor in reverse, for a rollback (OPERATING.md: restore // BEFORE reverting or running an older checkout, which cannot read a `.zst`). // Where the bytes are, never across disks, no `mkdir`: // // 1. Z is decoded into a temp R (`..restoring--`, `wx`, // in the dir that holds Z's bytes) through sha256; R is fsynced, and its // length must be the frame header's content size. // 2. R is read back from disk through sha256 and must equal a FRESH decode // of Z (a second read of Z, not the first stream), and Z must be // unchanged (inode, size, mtime). // 3. R is given Z's times (numeric seconds: Z carries the original's) and // linked to P with no clobber (`link`: a P that appeared meanwhile is // never replaced), R's name removed, the dir fsynced. // 4. Tiered: P's link is placed with Z's link's own times (the name's // `lstat` answers what it did), no clobber, the dir fsynced. // 5. Z goes, through `removeMediaFile` (its link and its bytes). // // A kill at any step leaves Z whole and untouched until step 5, and from step // 3 on a whole P beside it with the same content; the next run (a restore, or // a compress) finishes from either. Plain beside stored with the same content // is finished by removing Z; with different content it is refused. export type RestoreOutcome = | { status: "restored"; before: number; after: number; tiered: boolean } | { status: "already" } // the plain form only | { status: "absent" } | { status: "changed" } | { status: "skipped"; reason: CompressSkipReason; detail?: string }; export async function restoreStoredText( videoDir: string, name: string, opts: CompressOptions = {}, ): Promise { if (!isStoredTextName(name)) return { status: "skipped", reason: "not-declared" }; return withFileLock(videoDir, name, { status: "skipped", reason: "busy", detail: "being compressed or restored" } as RestoreOutcome, () => restoreOne(videoDir, name, opts), ); } async function restoreOne(videoDir: string, name: string, opts: CompressOptions): Promise { const ctx = runCtx(videoDir, opts); const { pid, token, log, reachable } = ctx; const crash = (p: CompressKillPoint) => opts.crashAt?.(p); const stored = storedNameOf(name); const channelDir = path.dirname(path.dirname(videoDir)); const skip = (reason: CompressSkipReason, detail?: string): RestoreOutcome => ({ status: "skipped", reason, ...(detail ? { detail } : {}), }); if (await lstatOrNull(path.join(channelDir, TIER_RELOCATION_MARKER))) return skip("relocating"); const entries = await readdir(videoDir).catch(() => [] as string[]); if (entries.some((e) => e.startsWith(`${name}.part`))) return skip("partial"); if (await recordingNow(videoDir)) return skip("recording"); if (opts.isBusy?.()) return skip("busy"); const repaired = await repairLeftovers(videoDir, name, entries, ctx); if (repaired) return repaired as RestoreOutcome; const z = await entryAt(videoDir, stored); let p = await entryAt(videoDir, name); if (z.kind === "none") return p.kind === "none" ? { status: "absent" } : { status: "already" }; if (z.kind === "other") return skip("not-a-file", stored); if (z.kind === "link" && !z.inMedia) return skip("foreign-link", stored); if (p.kind === "other") return skip("not-a-file"); if ((z.kind === "link" || p.kind === "link") && (await reachable()) !== "yes") return skip("unreachable"); const zPath = await storedPathOf(videoDir, name); // A plain link whose bytes are gone (a compress stopped inside the // original's removal): with a whole stored form, the link goes and the // restore proceeds. if (p.kind === "link" && !(await stat(p.path).then((st) => st.isFile(), () => false))) { if (!zPath) return skip("dangling"); try { await digestOf(zPath, { decode: true }); } catch (e) { return skip("stored-corrupt", (e as Error).message); } await removeMediaFile(videoDir, name); p = { kind: "none" }; } if (!zPath) { // A stored link whose bytes are gone: with a plain file, only the link. if (p.kind === "none") return skip("dangling", stored); await removeMediaFile(videoDir, stored); return { status: "already" }; } let zd: Digest; try { zd = await digestOf(zPath, { decode: true, throttle: opts.throttle }); } catch (e) { return skip("stored-corrupt", (e as Error).message); } const zStat = await stat(zPath); const zFirst = identOf(zStat); const tiered = z.kind === "link"; const workDir = tiered ? path.dirname(zPath) : videoDir; // ── both forms: the plain one is a whole copy, or it is not ─────────────── if (p.kind !== "none") { const pd = await digestOf(p.path, { throttle: opts.throttle }).catch(() => null); if (!pd || pd.sha !== zd.sha || pd.bytes !== zd.bytes) { return skip("both-differ", `${name} and ${stored} differ`); } if (await lstatOrNull(path.join(channelDir, TIER_RELOCATION_MARKER))) return skip("relocating"); if (!(await plainStillWhole(videoDir, name, zd, null))) { log(` ${name} is not a whole copy of ${stored} any more: the stored file is kept`); return { status: "changed" }; } await removeMediaFile(videoDir, stored); await fsyncDir(videoDir); return { status: "restored", before: zStat.size, after: zd.bytes, tiered: p.kind === "link" }; } if (tiered && (await removeDeadTemps(workDir, name, ctx)) === "live") { return skip("busy", "another process is on this file"); } const placed = path.join(workDir, name); const besideL = tiered ? await lstatOrNull(placed) : null; if (besideL && !besideL.isFile()) return skip("not-a-file", `media/${path.basename(workDir)}/${name}`); if (besideL) { // Placed by a run that was stopped before its link: verified, then linked. const bd = await digestOf(placed, { throttle: opts.throttle }).catch(() => null); if (!bd || bd.sha !== zd.sha || bd.bytes !== zd.bytes) { return skip("both-differ", `media/${path.basename(workDir)}/${name} and ${stored} differ`); } } else { const free = await statfs(workDir).then( (f) => f.bavail * f.bsize, () => Infinity, ); if (free < zd.bytes + (opts.reserveBytes ?? 2 * 1024 ** 3)) return skip("low-space"); const made = await makePlain(zPath, workDir, name, zStat, zFirst, zd, `${pid}-${token}`, opts); if (made !== "ok") return made; crash("restore-placed"); } // ── its tier link ───────────────────────────────────────────────────────── if (tiered) { const tmpLink = path.join(videoDir, `.${name}.stlink-${pid}-${token}`); await rm(tmpLink, { force: true }); await symlink(path.relative(videoDir, placed), tmpLink); await lutimes(tmpLink, z.l.atimeMs / 1000, z.l.mtimeMs / 1000); try { // No clobber: a link to the symlink itself, then the temp name goes. await link(tmpLink, path.join(videoDir, name)); } catch (err) { await rm(tmpLink, { force: true }); if (errCode(err) !== "EEXIST") throw err; // A writer put a plain file here meanwhile: it is the truth. The copy // this run placed goes — unless the new name resolves to it (the tier // hook moved the writer's bytes over that same target, REVIEW-2 N3); // the stored form is the next run's to settle. const [nowName, nowPlaced] = await Promise.all([ stat(path.join(videoDir, name)).catch(() => null), stat(placed).catch(() => null), ]); if (!(nowName && nowPlaced && nowName.ino === nowPlaced.ino && nowName.dev === nowPlaced.dev)) { await rm(placed, { force: true }); } log(` ${name} appeared while it was being restored: the new file is kept`); return { status: "changed" }; } await rm(tmpLink, { force: true }); await fsyncDir(videoDir); crash("restore-linked"); } // ── the stored form goes ────────────────────────────────────────────────── if (await lstatOrNull(path.join(channelDir, TIER_RELOCATION_MARKER))) return skip("relocating"); // THE PLAIN FILE, LOOKED AT AGAIN right before (REVIEW-2 R3): there, a // regular file (through the expected link), its size and hash those of a // fresh decode. Otherwise the stored form stays. if (!(await plainStillWhole(videoDir, name, zd, tiered ? placed : null))) { log(` ${name} is not a whole copy of ${stored} any more: the stored file is kept`); return { status: "changed" }; } await removeMediaFile(videoDir, stored); await fsyncDir(videoDir); // A real plain file on a channel with a media tier: the hook, as the // compressor does for its output (REVIEW-2 N6). const nowTiered = tiered || (await tierMediaFile(videoDir, name, { onLog: log })) === "tiered"; return { status: "restored", before: zStat.size, after: zd.bytes, tiered: nowTiered }; } // Is the plain file here a whole copy of the stored content `zd`? A regular // file (a link must resolve to `expected` when given), of its size, with its // hash. Read in full: this is the last look before a stored copy goes. async function plainStillWhole(videoDir: string, name: string, zd: Digest, expected: string | null): Promise { const file = path.join(videoDir, name); const st = await stat(file).catch(() => null); if (!st || !st.isFile() || st.size !== zd.bytes) return false; if (expected) { const ex = await stat(expected).catch(() => null); if (!ex || ex.ino !== st.ino || ex.dev !== st.dev) return false; } const d = await digestOf(file).catch(() => null); return !!d && d.sha === zd.sha && d.bytes === zd.bytes; } // Steps 1–3 of the restore: Z → R (verified) → P. "ok", or the outcome that // stops the file. async function makePlain( zPath: string, workDir: string, name: string, zStat: Stats, zFirst: Ident, zd: Digest, owner: string, opts: CompressOptions, ): Promise<"ok" | RestoreOutcome> { const tmp = path.join(workDir, `.${name}.restoring-${owner}`); const crash = (p: CompressKillPoint) => opts.crashAt?.(p); try { const fh = await open(tmp, "wx"); const { sink: hashSink, result } = digestSink(); try { let chunks = 0; const sink = new Writable({ write(chunk: Buffer, _enc, cb) { fh.write(chunk).then( () => { hashSink.write(chunk); chunks += 1; try { if (chunks === 1) crash("restoring"); cb(); } catch (err) { cb(err as Error); } }, (err: Error) => cb(err), ); }, }); await pipeline( createReadStream(zPath), paced(opts.throttle), createStoredTextDecompressor(), sink, ...(opts.signal ? [{ signal: opts.signal }] : []), ); await fh.sync(); } finally { await fh.close().catch(() => {}); } const written = result(); crash("restore-written"); if (written.bytes !== zd.bytes || written.sha !== zd.sha) { throw new Error(`the plain copy of ${name} did not decode the same as before`); } // R from disk against a FRESH decode of Z. const [back, fresh] = await Promise.all([ digestOf(tmp, { throttle: opts.throttle }), digestOf(zPath, { decode: true, throttle: opts.throttle }), ]); if (back.sha !== fresh.sha || back.bytes !== fresh.bytes || back.sha !== zd.sha) { throw new Error(`the plain copy of ${name} did not read back the same as its stored form`); } if (!sameIdent(identOf(await stat(zPath)), zFirst)) throw new ChangedError(); crash("restore-verified"); await utimes(tmp, zStat.atimeMs / 1000, zStat.mtimeMs / 1000); try { await link(tmp, path.join(workDir, name)); } catch (err) { if (errCode(err) === "EEXIST") throw new ChangedError(); throw err; } await rm(tmp, { force: true }); await fsyncDir(workDir); return "ok"; } catch (err) { if (err instanceof CompressKill) throw err; await rm(tmp, { force: true }).catch(() => {}); if (err instanceof ChangedError) return { status: "changed" }; if (err instanceof StoredTextCorruptError) { return { status: "skipped", reason: "stored-corrupt", detail: err.message }; } throw err; } } // ── A DELIBERATE RE-FETCH OVER A STORED CAPTURE: THE EARLIER ONE IS KEPT ── // // No pass fetches a declared file that is on disk in either form (the // chat-only pass is skipped, the caption passes leave the chat out of // `--sub-langs`, fetch-chat normalizes what is here). The one pass that does // is a DELIBERATE re-fetch — `fetch-chat {replace: true}` over a chat stored // compressed. NOTHING EVER REMOVES A CAPTURE BECAUSE A DIFFERENT ONE ARRIVED // (REVIEW-2 R1): a platform's replay is often shorter than the live capture, // and the capture cannot be fetched again. So: // // 1. before the pass, the stored form is RENAMED to a kept name, // `chat-capture-kept..json.zst` (lib/mediaTier.ts — no reader // of the chat sees it; it travels with the video as media), through // `renameMediaFile` (a tier link's bytes are renamed beside themselves); // 2. the pass runs; yt-dlp writes the plain name; // 3. the caller measures both and decides: a new replay with messages is the // chat, and the earlier capture stays kept; nothing landed, a `.part`, a // failed pass — the kept capture goes back under the stored name // (`putBackKeptCapture`); an EMPTY replay is itself kept under a kept // name (`keepPlainAsCapture`: compressed, verified, then its plain name // removed) and the earlier capture goes back. // // Nothing removes a kept capture automatically. `compress-text`'s dry run // lists them ("earlier captures kept"); a person deletes one on the files card. export type KeepOutcome = { kept: string } | { kept: null } | "busy"; // A kept name free in both places it could be (data// and, for a tier // link, beside its bytes in media//). async function freeKeptName(videoDir: string, besideDir: string | null, at: Date): Promise { for (let n = 0; ; n++) { const k = keptChatCaptureName(at, n); const here = await lstatOrNull(path.join(videoDir, k)); const there = besideDir ? await lstatOrNull(path.join(besideDir, k)) : null; if (!here && !there) return k; } } // Step 1: the stored form renamed to a kept name. `{kept: null}`: no stored // form here (nothing to keep). export async function setAsideStoredText(videoDir: string, name: string, at: Date = new Date()): Promise { if (!isStoredTextName(name)) return { kept: null }; return withFileLock(videoDir, name, "busy", async () => { const z = await entryAt(videoDir, storedNameOf(name)); if (z.kind === "none") return { kept: null }; const kept = await freeKeptName(videoDir, z.kind === "link" && z.inMedia ? path.dirname(z.target) : null, at); await renameMediaFile(videoDir, storedNameOf(name), kept); await fsyncDir(videoDir); return { kept }; }); } // The kept capture back under the stored name — only when neither form of the // name is here (it never replaces anything). False: left where it is. export async function putBackKeptCapture(videoDir: string, name: string, kept: string): Promise { return withFileLock(videoDir, name, "busy", async () => { if ((await lstatOrNull(path.join(videoDir, name))) || (await lstatOrNull(path.join(videoDir, storedNameOf(name))))) { return false; } const k = await entryAt(videoDir, kept); if (k.kind === "none") return false; if (k.kind === "link" && k.inMedia && (await lstatOrNull(path.join(path.dirname(k.target), storedNameOf(name))))) { return false; } await renameMediaFile(videoDir, kept, storedNameOf(name)); await fsyncDir(videoDir); return true; }); } // The plain file kept as a capture: compressed beside its bytes into a kept // name (written, fsynced, decoded back and hashed against it), linked when it // is tiered, and only then its plain name removed through removeMediaFile. export async function keepPlainAsCapture( videoDir: string, name: string, at: Date = new Date(), opts: CompressOptions = {}, ): Promise { return withFileLock(videoDir, name, "busy", async () => { const p = await entryAt(videoDir, name); if (p.kind !== "real" && !(p.kind === "link" && p.inMedia)) return { kept: null }; const tiered = p.kind === "link"; const bytesPath = tiered ? p.target : p.path; const workDir = path.dirname(bytesPath); const s = await stat(bytesPath); const kept = await freeKeptName(videoDir, tiered ? workDir : null, at); const ctx = runCtx(videoDir, opts); const made = await makeStored(bytesPath, workDir, kept, s, identOf(s), `${ctx.pid}-${ctx.token}`, opts); if (made !== "ok") return { kept: null }; if (tiered) { const tmpLink = path.join(videoDir, `.${kept}.stlink-${ctx.pid}-${ctx.token}`); await rm(tmpLink, { force: true }); await symlink(path.relative(videoDir, path.join(workDir, kept)), tmpLink); await rename(tmpLink, path.join(videoDir, kept)); await fsyncDir(videoDir); } await removeMediaFile(videoDir, name); await fsyncDir(videoDir); return { kept }; }); } // ── BOTH FORMS DIFFER: RECORDED ONCE, FOR A PERSON (REVIEW-1 N2) ─────────── // // A pair the compressor refused (`both-differ`) is written to the CHANNEL's // `.stored-text-differs.json` (beside its config — the video dir is left // exactly as it was) with each form's identity (inode, size, mtime). While both // forms are exactly those files, the job's survey counts the pair as WAITING // FOR A PERSON — listed by the dry run, never work, never refused again. Any // change to either form (a person settles it on the files card, a writer // lands a new one) makes the entry stale and the pair is work again. A record, // not a lock: nothing is kept from being read or deleted by it. Written only // by the compress-text job, one per channel at a time. export const STORED_TEXT_DIFFERS_FILENAME = ".stored-text-differs.json"; type FormIdent = { ino: number; size: number; mtimeMs: number }; type DiffersRecord = Record; const channelDirOf = (videoDir: string) => path.dirname(path.dirname(videoDir)); const differsKey = (videoDir: string, name: string) => `${path.basename(videoDir)}/${name}`; async function formIdents(videoDir: string, name: string): Promise<{ plain: FormIdent; stored: FormIdent } | null> { const [p, z] = await Promise.all([lstatOrNull(path.join(videoDir, name)), lstatOrNull(path.join(videoDir, storedNameOf(name)))]); if (!p || !z) return null; const id = (st: Stats): FormIdent => ({ ino: st.ino, size: st.size, mtimeMs: st.mtimeMs }); return { plain: id(p), stored: id(z) }; } // The channel's record (one read per survey). export async function readStoredTextDiffers(channelDir: string): Promise { try { const v = JSON.parse(await readFile(path.join(channelDir, STORED_TEXT_DIFFERS_FILENAME), "utf8")) as unknown; return v && typeof v === "object" && !Array.isArray(v) ? (v as DiffersRecord) : {}; } catch { return {}; } } async function recordBothDiffer(videoDir: string, name: string): Promise { const ids = await formIdents(videoDir, name); if (!ids) return; const channelDir = channelDirOf(videoDir); const rec = await readStoredTextDiffers(channelDir); rec[differsKey(videoDir, name)] = { ...ids, at: new Date().toISOString() }; const file = path.join(channelDir, STORED_TEXT_DIFFERS_FILENAME); const tmp = `${file}.${process.pid}-${selfToken()}`; await writeFile(tmp, JSON.stringify(rec, null, 1)); await rename(tmp, file); } // Is this pair the one recorded as differing — both forms the very files // that were compared? (The survey's question; a stat each, no content read.) export async function bothDifferRecorded(record: DiffersRecord, videoDir: string, name: string): Promise { const rec = record[differsKey(videoDir, name)]; if (!rec) return false; const ids = await formIdents(videoDir, name); const same = (a: FormIdent, b: FormIdent) => a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs; return !!ids && same(ids.plain, rec.plain) && same(ids.stored, rec.stored); } // ── A RE-DOWNLOAD OVER A STORED CAPTION (REVIEW-1 F1 of the captions lane) ── // // A managed re-download of a youtube-handling video fetches its captions // again (AGENTS.md: "YouTube's subtitles are fetched again first, as on any // re-download"): yt-dlp, run without `--no-overwrites`, replaces a plain // caption it finds. Over a track stored compressed it finds none, and lands // a new plain file beside the stored one. Main's rule is kept — the new // caption becomes the track — with one guarantee the overwrite never had: // the stored copy goes only AFTER the new file is whole and is a caption. // Per track that was stored-only before the pass: // // - nothing landed, or a `.part` of it (a fetch that did not finish): the // stored track is untouched (a video that is gone returns nothing); // - a whole new file with the SAME content: the new plain file goes, the // stored form stays — no churn, its mtime unchanged, the index sees // nothing; // - a whole new file with OTHER content that parses to at least one cue: it // is the track (as an overwrite was on main), and only then the stored // form is removed; // - an empty file, or one with no cue: dropped, the stored track untouched; // - a stored form that does not decode: both kept, for a person. // // Each outcome is a line in the job log. // A test's seam: called after the new plain file and its dir are fsynced and // before the stored copy is removed (the order is what REVIEW-2 N1 asks). let syncedForTest: ((videoDir: string, name: string) => Promise | void) | undefined; export function setRefetchSyncedHookForTest(fn: typeof syncedForTest): void { syncedForTest = fn; } export type RefetchedCaptionOutcome = { track: string; name: string; status: "nothing-landed" | "partial" | "same" | "replaced" | "dropped-empty" | "kept-both" | "busy" | "no-stored"; detail?: string; }; export async function settleRefetchedCaptions( videoDir: string, storedTracks: readonly string[], onLog: (line: string) => void = () => {}, ): Promise { const out: RefetchedCaptionOutcome[] = []; for (const track of storedTracks) { const name = `transcript.${track}.vtt`; if (!isStoredCaptionName(name)) continue; const r = await withFileLock( videoDir, name, { track, name, status: "busy" }, () => settleOne(videoDir, track, name), ); out.push(r); const say: Record = { "nothing-landed": "nothing was fetched; the stored track is kept", partial: "the fetch did not finish (a .part); the stored track is kept", same: "fetched again with the same content; the stored track is kept (the new copy dropped)", replaced: "fetched again with new content; the new track replaces the stored one", "dropped-empty": "fetched again with no cues; dropped, the stored track is kept", "kept-both": "fetched again; the stored track could not be read, so both are kept for a person", busy: "being compressed or restored right now; left as it is", "no-stored": "no stored form any more; left as it is", }; onLog(`Captions ${name}: ${say[r.status]}${r.detail ? ` (${r.detail})` : ""}.\n`); } return out; } async function settleOne(videoDir: string, track: string, name: string): Promise { const base = { track, name }; const entries = await readdir(videoDir).catch(() => [] as string[]); if (entries.some((e) => e.startsWith(`${name}.part`))) return { ...base, status: "partial" }; const plain = await entryAt(videoDir, name); if (plain.kind === "none") return { ...base, status: "nothing-landed" }; const z = await storedPathOf(videoDir, name); if (!z) return { ...base, status: "no-stored" }; let fresh: Buffer; try { fresh = await readFile(path.join(videoDir, name)); } catch (err) { return { ...base, status: "kept-both", detail: `the new file does not open: ${(err as Error).message}` }; } let zd: Digest; try { zd = await digestOf(z, { decode: true }); } catch (err) { return { ...base, status: "kept-both", detail: (err as Error).message }; } const fd = { sha: createHash("sha256").update(fresh).digest("hex"), bytes: fresh.length }; if (fd.sha === zd.sha && fd.bytes === zd.bytes) { await removeMediaFile(videoDir, name); await fsyncDir(videoDir); return { ...base, status: "same" }; } let cues = 0; try { cues = fresh.length > 0 ? parseVtt(fresh.toString("utf8")).length : 0; } catch { cues = 0; } if (cues === 0) { await removeMediaFile(videoDir, name); await fsyncDir(videoDir); return { ...base, status: "dropped-empty", detail: `${fresh.length} bytes` }; } // The new track is whole (yt-dlp has exited; no `.part`) and a caption: it // is the track, as an overwrite was on main. Its data and its name are made // DURABLE first — yt-dlp never fsyncs, and a power cut after the stored // copy's removal must not leave a zero-length caption (REVIEW-2 N1). Only // then the stored one goes. const fh = await open(path.join(videoDir, name), "r"); try { await fh.sync(); } finally { await fh.close(); } await fsyncDir(videoDir); await syncedForTest?.(videoDir, name); await removeMediaFile(videoDir, storedNameOf(name)); await fsyncDir(videoDir); return { ...base, status: "replaced", detail: `${cues} cues, ${fresh.length} bytes` }; } // ── THE FILES CARD'S DELETE OF ONE NAMED FORM ─────────────────────────────── // // A person deleting `X` or `X.zst` on the files card asked for ONE file: only // that one goes, through `removeMediaFile` — never the other form (REVIEW-2 // R2). When the other is there too, the answer says so and whether it holds // the same content (readers still see the chat) or different content (it is // what readers read now, or still). export type RemoveFormOutcome = { removed: string[]; kept?: { name: string; same: "same" | "differs" | "unreadable" }; // The plain transcript.en.vtt (a "Set as transcript" pick) went beside a // stored one of other content: the pin went too (transcriptPin-server.ts). unpinned?: boolean; }; export async function removeStoredTextForm( videoDir: string, filename: string, ): Promise { const plain = plainNameOf(filename) ?? filename; if (!isStoredTextName(plain)) { await removeMediaFile(videoDir, filename); return { removed: [filename] }; } try { return await removeStoredTextFormLocked(videoDir, filename, plain); } catch (err) { // No lock could be made (a full disk): nothing was removed (REVIEW-2 N2). if (err instanceof LockUnavailableError) return { refused: `${filename} not deleted: ${err.message}` }; throw err; } } async function removeStoredTextFormLocked(videoDir: string, filename: string, plain: string): Promise { return withFileLock(videoDir, plain, "busy", async () => { const other = filename === plain ? storedNameOf(plain) : plain; // A stopped run's leftovers on the name go with any form deleted: a // set-aside original left behind could be adopted by the next run and // bring the deleted file back (REVIEW-1 F2, captions lane). if (!(await lstatOrNull(path.join(videoDir, other)))) { await removeMediaFile(videoDir, filename); await removeLeftoversOf(videoDir, plain); return { removed: [filename] }; } const z = await storedPathOf(videoDir, plain); const [pd, zd] = await Promise.all([ digestOf(path.join(videoDir, plain)).catch(() => null), z ? digestOf(z, { decode: true }).catch(() => null) : Promise.resolve(null), ]); const same = !pd || !zd ? "unreadable" : pd.sha === zd.sha && pd.bytes === zd.bytes ? "same" : "differs"; await removeMediaFile(videoDir, filename); await removeLeftoversOf(videoDir, plain); await fsyncDir(videoDir); // The pick deleted, YouTube's own stored `en` beside it: the pin goes too, // or it would rank that very track first (REVIEW-1 N1, captions lane). const unpinned = filename === "transcript.en.vtt" && same === "differs" ? await unpinAfterPickDeleted(videoDir) : false; return { removed: [filename], kept: { name: other, same }, ...(unpinned ? { unpinned: true } : {}) }; }); }