// COMPRESS TEXT — the migration that puts existing big text files into their // stored form (lib/storedText.ts), one file at a time, through the compressor // in lib/storedText-write-server.ts (write beside, fsync, read back and hash, // then the original removed through removeMediaFile). `pnpm ops compress-text` // posts it. Two KINDS: // // live-chat the raw live-chat replay, `transcript.live_chat.json` → `.zst` // (lane text-compress, slice 2) — mostly on the media drive; // captions every caption track, `transcript..vtt` → `.zst` (lane // text-compress-captions, slice 5) — on the CORPUS disk, real // files in `data//` (the classifier never tiers one; a link, // if one were there, is handled as the chat's are). // // `kinds` defaults to the live chat alone: captions are compressed only when a // person names them. Both named: the live chat first, then the captions. // // SAFE BY CONSTRUCTION, RESUMABLE BY RE-WALKING. Every file is "already", // "compressed", skipped with a reason, or repaired by the compressor's crash // rules; a re-run continues. `limit` counts files compressed this run. // // PACED, NEVER COMPETING: before each file it waits while render mode holds // the machine; the reads go through a token bucket (40 MB/s, 8 MB/s while a // live recording runs — the caller says which); a file written within the // quiet period (10 min), one with a `.part` beside it, one whose video is // recording or has a job running, one on a drive that does not answer, is // left alone and counted. // // `dryRun` WRITES NOTHING AND READS NO CONTENT: per channel and per kind, the // plain files and their bytes, the stored files and their logical bytes (from // the frame headers — 18 bytes each), the estimate after (labelled an // estimate, at the ratio measured on a sample) and the free space of the disks // they are on. For captions it also counts the en / en-orig PAIRS OF EQUAL // SIZE (by the logical size): each is compressed as it is — never deduped — // and the count says how much of the caption bytes are the pair twice. // `verify` decodes every stored file in full and writes nothing. // // THE WALK VISITS EVERY FILE A RUN MAY HAVE TO FINISH: one whose plain form is // there (a dangling tier link too — an interrupted removal), or whose stored // form is (the restore), or a stopped run's leftover for it (a temp, a // set-aside original) — so "the next run finishes it" is true through the job, // not only of the compressor. // // TWO FORMS WITH DIFFERENT CONTENT — a plain caption a re-fetch or "Set as // transcript" landed beside an older stored one — ARE REFUSED AND BOTH KEPT, // and listed (`both-differ`, with the file): nothing removes a stored copy // because a different one arrived. A video deleted on its platform cannot give // its captions again. // // `restore: true` IS THE ROLLBACK: every stored file of the named kinds put // back into its plain form (lib/storedText-write-server.ts restoreStoredText — // decoded beside, fsynced, read back against a fresh decode, the same times, // and only then the stored file removed). With `dryRun` it answers the stored // files, the bytes they will take, and the free space. Run it BEFORE reverting // or running an older checkout (OPERATING.md). import path from "node:path"; import { open, readdir, stat, statfs } from "node:fs/promises"; import type { Paths } from "../lib/paths"; import { LIVE_CHAT_FILENAME, ORIG_VTT_FILENAME, VTT_FILENAME } from "../lib/videoStatus"; import { isStoredCaptionName, logicalEntries, storedFormsIn, storedNameOf } from "../lib/storedText"; import { isKeptChatCapture } from "../lib/mediaTier"; import { frameContentSize } from "../lib/storedText-server"; import { compressStoredText, hasStoredTextLeftover, bothDifferRecorded, readStoredTextDiffers, restoreStoredText, storedTextLeftoverNames, verifyStoredText, type CompressOutcome, type CompressSkipReason, type RestoreOutcome, } from "../lib/storedText-write-server"; import { inspectChannelMedia } from "../lib/channelMedia"; import { onDrive } from "../lib/storageHealth"; import { readChannelConfig, listChannelSlugs } from "./channels"; export const COMPRESS_TEXT_KINDS = ["live-chat", "captions"] as const; export type CompressTextKind = (typeof COMPRESS_TEXT_KINDS)[number]; export const DEFAULT_COMPRESS_TEXT_KINDS: readonly CompressTextKind[] = ["live-chat"]; export function isCompressTextKind(k: unknown): k is CompressTextKind { return typeof k === "string" && (COMPRESS_TEXT_KINDS as readonly string[]).includes(k); } // Measured on samples (lane text-compress design §1): a raw chat at level 9 // is ~5 % of its size, a caption track ~20 %. Estimates, and every line that // uses one says so. export const CHAT_RATIO_ESTIMATE = 0.05; export const CAPTION_RATIO_ESTIMATE = 0.2; const RATIO: Record = { "live-chat": CHAT_RATIO_ESTIMATE, captions: CAPTION_RATIO_ESTIMATE }; const NOUN: Record = { "live-chat": "raw chat(s)", captions: "caption file(s)" }; export const COMPRESS_QUIET_MS = 10 * 60_000; export const COMPRESS_RATE_BYTES = 40 * 1024 * 1024; export const COMPRESS_RATE_RECORDING_BYTES = 8 * 1024 * 1024; export type CompressTextOptions = { paths: Paths; // Default: every channel. slugs?: string[]; // Default: the live chat alone (DEFAULT_COMPRESS_TEXT_KINDS). kinds?: readonly CompressTextKind[]; dryRun?: boolean; verify?: boolean; // The rollback: stored → plain (with `dryRun`: the plan). restore?: boolean; limit?: number; quietMs?: number; onLog: (line: string) => void; signal?: AbortSignal; drainSignal?: AbortSignal; // A job is running for this video (the editor's registry). isBusy?: (slug: string, id: string) => boolean; // The read rate now, bytes/s (the editor: slower while a recording runs). rate?: () => number; // Waits while render mode holds the machine; null when the wait was ended // by the signal (lib/renderHold.ts waitWhileRenderHeld, injected). waitForRender?: () => Promise; sleep?: (ms: number, signal?: AbortSignal) => Promise; now?: () => number; // Tests: the compressor's options passed through (a kill point, a pid). compressOpts?: Parameters[2]; }; // One kind's figures for one channel (the same fields as the channel line). export type KindLine = { plainFiles: number; plainBytes: number; storedFiles: number; storedLogicalBytes: number; storedBytes: number; // The files a run in this mode visits (a compress: the plain form or a // stopped run's leftover; a restore: the stored form or a leftover). pending: number; // Both forms with different content, recorded and unchanged since: waiting // for a person (the files card), not work — each listed once. differs?: { id: string; name: string }[]; // Captions only: dirs whose `transcript.en.vtt` and `transcript.en-orig.vtt` // are both here, in either form, with the same LOGICAL size (on samples of // this corpus every such pair was byte-identical). Compressed each as it // is; the count is for a person deciding on a dedupe. pairsEqualSize?: number; pairsEqualSizeBytes?: number; estimateAfterBytes?: number; compressed?: number; restored?: number; bytesBefore?: number; bytesAfter?: number; already?: number; changed?: number; skipped?: Partial>; failed?: { id: string; name: string; error: string }[]; // Files left with BOTH forms of different content (or a stored form that // does not decode): kept, both, for a person — listed. refused?: { id: string; name: string; reason: CompressSkipReason; detail?: string }[]; verified?: number; problems?: { id: string; name: string; status: string; detail?: string }[]; }; export type ChannelLine = { slug: string; // Why the channel was not walked, when it was not. refused?: string; // The totals over the kinds asked (with the live chat alone, exactly its // figures, as before captions were a kind). plainFiles: number; plainBytes: number; storedFiles: number; storedLogicalBytes: number; storedBytes: number; pending?: number; // Earlier chat captures kept by a re-fetch (`chat-capture-kept.*.json.zst`, // lib/mediaTier.ts): never removed automatically — counted so a person sees // them. keptCaptures?: number; keptCaptureBytes?: number; // Dry run only: what the plain files would take at the estimated ratio // (a restore's dry run: the stored files' logical bytes — exact). estimateAfterBytes?: number; // Dry run only: free space now on the disk(s) holding this channel's files. free?: { corpus?: number; media?: number }; // A real run. compressed?: number; bytesBefore?: number; bytesAfter?: number; already?: number; changed?: number; skipped?: Partial>; failed?: { id: string; error: string; name?: string }[]; // A restore. restored?: number; // Verify. verified?: number; problems?: { id: string; status: string; detail?: string; name?: string }[]; // Per kind asked. byKind?: Partial>; }; export type CompressTextResult = { dryRun: boolean; verify: boolean; restore: boolean; kinds: CompressTextKind[]; channels: ChannelLine[]; stopped?: "drained" | "cancelled" | "limit"; lines: string[]; }; // A file with work for a run: `size` is the plain file's (0 when it does not // open — a dangling link, or only a leftover). type Candidate = { id: string; videoDir: string; name: string; size: number }; type Stored = { id: string; videoDir: string; name: string; bytes: number; logical: number }; function fmtBytes(n: number): string { if (n >= 1024 ** 3) return `${(n / 1024 ** 3).toFixed(2)} GB`; if (n >= 1024 ** 2) return `${(n / 1024 ** 2).toFixed(1)} MB`; if (n >= 1024) return `${(n / 1024).toFixed(1)} KB`; return `${n} B`; } // A token bucket over bytes: each call waits until its bytes fit the rate. export function byteThrottle( rate: () => number, sleep: (ms: number, signal?: AbortSignal) => Promise, now: () => number = Date.now, signal?: AbortSignal, ): (bytes: number) => Promise { let nextFree = 0; return async (bytes: number) => { const r = rate(); if (!(r > 0) || !Number.isFinite(r)) return; const t = now(); const start = Math.max(t, nextFree); nextFree = start + (bytes / r) * 1000; const wait = start - t; if (wait > 1) await sleep(wait, signal); }; } const defaultSleep = (ms: number, signal?: AbortSignal) => new Promise((resolve) => { const t = setTimeout(resolve, ms); signal?.addEventListener("abort", () => { clearTimeout(t); resolve(); }, { once: true }); }); async function storedLogicalSize(file: string): Promise { try { 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(); } } catch { return null; } } // The declared names of one kind in one dir's PHYSICAL listing: either form, // or a stopped run's leftover for it. function namesOfKind(kind: CompressTextKind, entries: readonly string[]): string[] { if (kind === "live-chat") return [LIVE_CHAT_FILENAME]; const names = new Set(logicalEntries(entries).filter(isStoredCaptionName)); for (const n of storedTextLeftoverNames(entries)) if (isStoredCaptionName(n)) names.add(n); return [...names].sort(); } type KindSurvey = { plain: Candidate[]; stored: Stored[]; // Every file a compress run visits: the plain form, present at all (a // dangling link included), or a stopped run's leftover. work: Candidate[]; // Every file a restore visits: the stored form, or a leftover. restoreWork: Candidate[]; // Both forms present and recorded as differing, unchanged since: waiting // for a person — never work (REVIEW-1 N2). differs: Candidate[]; pairsEqualSize: number; pairsEqualSizeBytes: number; }; // One channel's files of the kinds asked, by what is on disk. Sizes are // `stat`s (through a tier link, under the drive's watchdog); no content is // read beyond a stored file's 18-byte frame header. async function surveyChannel( channelDir: string, drive: string | undefined, kinds: readonly CompressTextKind[], ): Promise<{ byKind: Partial>; kept: { files: number; bytes: number } }> { const dataDir = path.join(channelDir, "data"); const ids = (await readdir(dataDir).catch(() => [] as string[])).sort(); const byKind: Partial> = {}; for (const k of kinds) { byKind[k] = { plain: [], stored: [], work: [], restoreWork: [], differs: [], pairsEqualSize: 0, pairsEqualSizeBytes: 0 }; } const kept = { files: 0, bytes: 0 }; const differs = await readStoredTextDiffers(channelDir); const sizeOfMedia = (p: string) => (drive ? onDrive(drive, () => stat(p)) : stat(p)).then((s) => s.size, () => null); const logicalOfMedia = (p: string) => (drive ? onDrive(drive, () => storedLogicalSize(p)) : storedLogicalSize(p)).catch(() => null); for (const id of ids) { const videoDir = path.join(dataDir, id); const entries = await readdir(videoDir).catch(() => null); if (!entries) continue; if (kinds.includes("live-chat")) { for (const k of entries.filter(isKeptChatCapture)) { kept.files += 1; kept.bytes += (await sizeOfMedia(path.join(videoDir, k))) ?? 0; } } for (const kind of kinds) { const s = byKind[kind]!; // Captions are on the corpus disk (never tiered): stat them directly, // never under the media drive's watchdog (REVIEW-1 N4). const sizeOf = kind === "live-chat" ? sizeOfMedia : (p: string) => stat(p).then((st) => st.size, () => null); const logicalOf = kind === "live-chat" ? logicalOfMedia : (p: string) => storedLogicalSize(p); const logicalSize: Record = {}; for (const name of namesOfKind(kind, entries)) { const forms = storedFormsIn(entries, name); const leftover = hasStoredTextLeftover(entries, name); let size: number | null = null; if (forms === "plain" || forms === "both") { size = await sizeOf(path.join(videoDir, name)); if (size !== null) s.plain.push({ id, videoDir, name, size }); logicalSize[name] = size; } const waiting = forms === "both" && !leftover && (await bothDifferRecorded(differs, videoDir, name)); if (waiting) s.differs.push({ id, videoDir, name, size: size ?? 0 }); else if (forms === "plain" || forms === "both" || leftover) s.work.push({ id, videoDir, name, size: size ?? 0 }); if (forms === "zst" || forms === "both" || leftover) s.restoreWork.push({ id, videoDir, name, size: 0 }); if (forms === "zst" || forms === "both") { const zp = path.join(videoDir, storedNameOf(name)); const bytes = await sizeOf(zp); const logical = bytes === null ? null : await logicalOf(zp); if (bytes !== null) s.stored.push({ id, videoDir, name, bytes, logical: logical ?? 0 }); // The plain form, when it is here, is the truth (lib/storedText.ts). if (forms === "zst") logicalSize[name] = logical; } } if (kind === "captions") { const en = logicalSize[VTT_FILENAME]; const orig = logicalSize[ORIG_VTT_FILENAME]; if (typeof en === "number" && en === orig) { s.pairsEqualSize += 1; s.pairsEqualSizeBytes += en; } } } } // Smallest first: the early files are the cheap ones (a dir to repair, 0). const bySize = (a: Candidate, b: Candidate) => a.size - b.size || (a.id < b.id ? -1 : a.id > b.id ? 1 : a.name < b.name ? -1 : a.name > b.name ? 1 : 0); for (const s of Object.values(byKind)) { s!.plain.sort(bySize); s!.work.sort(bySize); } return { byKind, kept }; } function emptyKindLine(s: KindSurvey, restore: boolean): KindLine { return { differs: s.differs.map((d) => ({ id: d.id, name: d.name })), plainFiles: s.plain.length, plainBytes: s.plain.reduce((a, c) => a + c.size, 0), storedFiles: s.stored.length, storedBytes: s.stored.reduce((a, c) => a + c.bytes, 0), storedLogicalBytes: s.stored.reduce((a, c) => a + c.logical, 0), pending: (restore ? s.restoreWork : s.work).length, }; } const sum = (lines: KindLine[], f: (l: KindLine) => number | undefined) => lines.reduce((a, l) => a + (f(l) ?? 0), 0); function mergeSkipped(into: Partial>, from: Partial> | undefined) { for (const [r, n] of Object.entries(from ?? {})) { into[r as CompressSkipReason] = (into[r as CompressSkipReason] ?? 0) + (n ?? 0); } } export async function compressText(opts: CompressTextOptions): Promise { const dryRun = opts.dryRun === true; const restore = opts.restore === true; const verify = !dryRun && !restore && opts.verify === true; // In the walk's order: the live chat first (the media drive), then captions. const asked = opts.kinds && opts.kinds.length > 0 ? opts.kinds : DEFAULT_COMPRESS_TEXT_KINDS; const kinds = COMPRESS_TEXT_KINDS.filter((k) => asked.includes(k)); const lines: string[] = []; const say = (line: string) => { lines.push(line); opts.onLog(`${line}\n`); }; const sleep = opts.sleep ?? defaultSleep; const now = opts.now ?? Date.now; const throttle = byteThrottle(opts.rate ?? (() => COMPRESS_RATE_BYTES), sleep, now, opts.signal); const slugs = opts.slugs ?? (await listChannelSlugs(opts.paths)).sort(); const channels: ChannelLine[] = []; // Files compressed (or restored) this run: what `limit` counts. let doneThisRun = 0; let stopped: CompressTextResult["stopped"]; const label = (k: CompressTextKind) => (kinds.length > 1 ? ` [${k}]` : ""); for (const slug of slugs) { if (stopped) break; const channelDir = path.join(opts.paths.channelsDir, slug); const line: ChannelLine = { slug, plainFiles: 0, plainBytes: 0, storedFiles: 0, storedLogicalBytes: 0, storedBytes: 0, }; channels.push(line); const config = await readChannelConfig(opts.paths, slug).catch(() => null); if (!config) { line.refused = "no config.json"; continue; } const media = await inspectChannelMedia(opts.paths, slug, config, { fresh: true }); if (media.status !== "ok" && media.status !== "in-place") { line.refused = media.detail ?? media.status; say(`${slug}: left alone — ${line.refused}`); continue; } const drive = media.status === "ok" ? media.target : undefined; const { byKind: survey, kept } = await surveyChannel(channelDir, drive, kinds); if (kinds.includes("live-chat")) { line.keptCaptures = kept.files; line.keptCaptureBytes = kept.bytes; } const keptText = kept.files ? `; earlier captures kept: ${kept.files} (${fmtBytes(kept.bytes)})` : ""; const kl: Partial> = {}; for (const k of kinds) kl[k] = emptyKindLine(survey[k]!, restore); line.byKind = kl; const all = kinds.map((k) => kl[k]!); line.plainFiles = sum(all, (l) => l.plainFiles); line.plainBytes = sum(all, (l) => l.plainBytes); line.storedFiles = sum(all, (l) => l.storedFiles); line.storedBytes = sum(all, (l) => l.storedBytes); line.storedLogicalBytes = sum(all, (l) => l.storedLogicalBytes); line.pending = sum(all, (l) => l.pending); if (kinds.includes("captions")) { kl.captions!.pairsEqualSize = survey.captions!.pairsEqualSize; kl.captions!.pairsEqualSizeBytes = survey.captions!.pairsEqualSizeBytes; } const freeOf = (p: string) => statfs(p).then((f) => f.bavail * f.bsize, () => undefined); const freeLine = async () => { line.free = { corpus: await freeOf(path.join(channelDir, "data")), ...(drive ? { media: await onDrive(drive, () => freeOf(drive)).catch(() => undefined) } : {}), }; }; // Which disk a kind's files are on: the chat on the media drive when the // channel has one, captions on the corpus disk (never tiered). const freeText = (k: CompressTextKind) => k === "live-chat" && drive ? `free on the media drive ${fmtBytes(line.free?.media ?? 0)}` : `free on the corpus disk ${fmtBytes(line.free?.corpus ?? 0)}`; const differsText = (k: CompressTextKind) => { const d = kl[k]!.differs ?? []; return d.length ? `; both forms differ, waiting for a person (settle on the files card): ${d.length} — ` + `${d.slice(0, 10).map((x) => `${x.id}/${x.name}`).join(", ")}${d.length > 10 ? `, … ${d.length - 10} more` : ""}` : ""; }; const pairsText = (k: CompressTextKind) => { const c = kl[k]!; return k === "captions" && c.pairsEqualSize ? `; en / en-orig pairs of equal size: ${c.pairsEqualSize} (${fmtBytes(c.pairsEqualSizeBytes ?? 0)} each side — compressed each as it is, not deduped)` : ""; }; if (dryRun && restore) { // Exact, from the frame headers: what the plain files will take again. line.estimateAfterBytes = line.storedLogicalBytes; await freeLine(); for (const k of kinds) { const c = kl[k]!; c.estimateAfterBytes = c.storedLogicalBytes; if (c.storedFiles + (k === "live-chat" ? kept.files : 0) > 0) { say( `${slug}${label(k)}: ${c.storedFiles} stored ${k === "live-chat" ? "chat(s)" : "caption file(s)"}, ` + `${fmtBytes(c.storedBytes)} → ${fmtBytes(c.storedLogicalBytes)} as plain files; ${freeText(k)}` + `${k === "live-chat" ? keptText : ""}`, ); } } continue; } if (dryRun) { await freeLine(); for (const k of kinds) { const c = kl[k]!; c.estimateAfterBytes = Math.round(c.plainBytes * RATIO[k]); if (c.plainFiles + c.storedFiles + (c.differs?.length ?? 0) + (k === "live-chat" ? kept.files : 0) > 0) { say( `${slug}${label(k)}: ${c.plainFiles} ${NOUN[k]}, ${fmtBytes(c.plainBytes)} → ~${fmtBytes(c.estimateAfterBytes)} ` + `(estimate, ${Math.round(RATIO[k] * 100)} %); already stored ${c.storedFiles} ` + `(${fmtBytes(c.storedBytes)} holding ${fmtBytes(c.storedLogicalBytes)}); ${freeText(k)}` + `${pairsText(k)}${differsText(k)}${k === "live-chat" ? keptText : ""}`, ); } } line.estimateAfterBytes = sum(all, (l) => l.estimateAfterBytes); continue; } if (verify) { line.verified = 0; line.problems = []; for (const k of kinds) { const c = kl[k]!; c.verified = 0; c.problems = []; for (const s of survey[k]!.stored) { if (opts.signal?.aborted) { stopped = "cancelled"; break; } if (opts.drainSignal?.aborted) { stopped = "drained"; break; } const v = await verifyStoredText(s.videoDir, s.name, { throttle }); if (v.status === "ok") { c.verified += 1; line.verified += 1; } else { const p = { id: s.id, name: s.name, status: v.status, ...("detail" in v ? { detail: v.detail } : {}) }; c.problems.push(p); line.problems.push(p); say(`${slug}/${s.id}/${s.name}: ${v.status}${"detail" in v ? ` — ${v.detail}` : ""}`); } } say(`${slug}${label(k)}: verified ${c.verified} stored ${k === "live-chat" ? "chat(s)" : "caption file(s)"}, ${c.problems.length} problem(s)`); if (stopped) break; } continue; } // ── a real run: compress, or restore ──────────────────────────────────── line.bytesBefore = 0; line.bytesAfter = 0; line.already = 0; line.changed = 0; line.skipped = {}; line.failed = []; if (restore) line.restored = 0; else line.compressed = 0; for (const k of kinds) { const c = kl[k]!; const s = survey[k]!; c.bytesBefore = 0; c.bytesAfter = 0; c.changed = 0; c.skipped = {}; c.failed = []; c.refused = []; const work = restore ? s.restoreWork : s.work; if (restore) { c.restored = 0; c.already = 0; } else { c.compressed = 0; // A stored file with nothing to finish is "already"; one in `work` // says so itself. const inWork = new Set(work.map((w) => `${w.id}/${w.name}`)); c.already = s.stored.filter((z) => !inWork.has(`${z.id}/${z.name}`)).length; } for (const w of work) { if (opts.signal?.aborted) { stopped = "cancelled"; break; } if (opts.drainSignal?.aborted) { stopped = "drained"; break; } if (opts.limit !== undefined && doneThisRun >= opts.limit) { stopped = "limit"; break; } if (opts.waitForRender) { const waited = await opts.waitForRender(); if (waited === null) { stopped = "cancelled"; break; } } const runOpts = { isBusy: opts.isBusy ? () => opts.isBusy!(slug, w.id) : undefined, throttle, ...(opts.signal ? { signal: opts.signal } : {}), onLog: (l: string) => opts.onLog(`${l}\n`), ...opts.compressOpts, }; let out: CompressOutcome | RestoreOutcome; try { out = restore ? await restoreStoredText(w.videoDir, w.name, runOpts) : await compressStoredText(w.videoDir, w.name, { quietMs: opts.quietMs ?? COMPRESS_QUIET_MS, now, ...runOpts, }); } catch (err) { if ((err as Error).name === "CompressKill") throw err; c.failed.push({ id: w.id, name: w.name, error: (err as Error).message }); say( `${slug}/${w.id}/${w.name}: failed — ${(err as Error).message} ` + `(${restore ? "the stored file" : "the original"} is untouched)`, ); continue; } const where = k === "live-chat" ? `${slug}/${w.id}` : `${slug}/${w.id}/${w.name}`; if (out.status === "compressed" || out.status === "restored") { doneThisRun += 1; if (out.status === "compressed") c.compressed! += 1; else c.restored! += 1; c.bytesBefore += out.before; c.bytesAfter += out.after; opts.onLog( `${where}: ${fmtBytes(out.before)} → ${fmtBytes(out.after)}${restore ? " (restored)" : ""}${out.tiered ? " (media tier)" : ""}\n`, ); } else if (out.status === "already") { c.already += 1; } else if (out.status === "changed") { c.changed += 1; } else if (out.status === "skipped") { c.skipped[out.reason] = (c.skipped[out.reason] ?? 0) + 1; if (out.reason === "both-differ" || out.reason === "stored-corrupt" || out.reason === "retired-kept") { c.refused.push({ id: w.id, name: w.name, reason: out.reason, ...(out.detail ? { detail: out.detail } : {}) }); say(`${where}: refused — ${out.reason}${out.detail ? ` (${out.detail})` : ""}; both files are kept`); } } } // The channel's totals. line.bytesBefore += c.bytesBefore; line.bytesAfter += c.bytesAfter; line.already += c.already; line.changed += c.changed; mergeSkipped(line.skipped, c.skipped); line.failed.push(...c.failed); if (restore) line.restored! += c.restored!; else line.compressed! += c.compressed!; const skippedText = Object.entries(c.skipped).map(([r, n]) => `${n} ${r}`).join(", "); if (restore && work.length > 0) { say( `${slug}${label(k)}: restored ${c.restored} (${fmtBytes(c.bytesBefore)} → ${fmtBytes(c.bytesAfter)}), ` + `already plain ${c.already}, changed ${c.changed}, skipped ${skippedText || "0"}, failed ${c.failed.length}`, ); } else if (!restore && work.length + c.storedFiles > 0) { say( `${slug}${label(k)}: compressed ${c.compressed} (${fmtBytes(c.bytesBefore)} → ${fmtBytes(c.bytesAfter)}), ` + `already ${c.already}, changed ${c.changed}, skipped ${skippedText || "0"}, failed ${c.failed.length}`, ); } if (stopped) break; } } const kindsText = kinds.map((k) => NOUN[k]).join(" and "); const storedNoun = kinds.map((k) => (k === "live-chat" ? "chat(s)" : "caption file(s)")).join(" and "); if (dryRun && restore) { const tot = channels.reduce((a, c) => a + c.storedLogicalBytes, 0); const n = channels.reduce((a, c) => a + c.storedFiles, 0); say(`Dry run (restore): ${n} stored ${storedNoun} → ${fmtBytes(tot)} as plain files. Nothing was written.`); } else if (restore) { const r = channels.reduce((a, l) => a + (l.restored ?? 0), 0); const f = channels.reduce((a, l) => a + (l.bytesAfter ?? 0), 0); say(`Restored ${r} ${kindsText} to their plain form (${fmtBytes(f)})${stopped ? ` — stopped (${stopped}); a re-run continues` : ""}.`); } else if (dryRun) { const parts = kinds.map((k) => { const n = channels.reduce((a, c) => a + (c.byKind?.[k]?.plainFiles ?? 0), 0); const b = channels.reduce((a, c) => a + (c.byKind?.[k]?.plainBytes ?? 0), 0); return `${n} ${NOUN[k]}, ${fmtBytes(b)} → ~${fmtBytes(Math.round(b * RATIO[k]))}`; }); const kf = channels.reduce((a, c) => a + (c.keptCaptures ?? 0), 0); const kb = channels.reduce((a, c) => a + (c.keptCaptureBytes ?? 0), 0); const pf = channels.reduce((a, c) => a + (c.byKind?.captions?.pairsEqualSize ?? 0), 0); const pb = channels.reduce((a, c) => a + (c.byKind?.captions?.pairsEqualSizeBytes ?? 0), 0); say( `Dry run: ${parts.join("; ")} (estimate)` + `${pf ? `; en / en-orig pairs of equal size: ${pf} (${fmtBytes(pb)} each side), compressed each as it is` : ""}` + `${kf ? `; earlier captures kept: ${kf} (${fmtBytes(kb)}), never removed automatically` : ""}. Nothing was written.`, ); } else if (!verify) { const c = channels.reduce((a, l) => a + (l.compressed ?? 0), 0); const b = channels.reduce((a, l) => a + (l.bytesBefore ?? 0), 0); const f = channels.reduce((a, l) => a + (l.bytesAfter ?? 0), 0); const refused = channels.reduce((a, l) => a + kinds.reduce((x, k) => x + (l.byKind?.[k]?.refused?.length ?? 0), 0), 0); const waiting = channels.reduce((a, l) => a + kinds.reduce((x, k) => x + (l.byKind?.[k]?.differs?.length ?? 0), 0), 0); say( `Compressed ${c} ${kindsText}: ${fmtBytes(b)} → ${fmtBytes(f)}` + `${refused ? `; ${refused} refused with both forms kept (listed above, and recorded: not work again until one changes)` : ""}` + `${waiting ? `; ${waiting} with both forms differing still wait for a person (the dry run lists them)` : ""}` + `${stopped ? ` — stopped (${stopped}); a re-run continues` : ""}.`, ); } return { dryRun, verify, restore, kinds: [...kinds], channels, ...(stopped ? { stopped } : {}), lines }; }