Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 9a2a077f2f83a88fb568f0fa8633f3f6b9a9d9ec
parent 2a0ea61b63bbd18be61066b835fdf84ea634756a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 21 Nov 2026 02:44:39 -0500

stored text, slice 2: the compressor and `pnpm ops compress-text` for the raw live chat

compressStoredText (lib/storedText-write-server.ts) puts one raw chat into its
stored form where its bytes are (media/<id>/ for a tier link, no mkdir):
stream through sha256 and zstd (level 9, checksum, size pledged) into a temp
opened wx, fsync, read back through the decompressor and compare hash and
length, check the source unchanged, give the temp the source's times in
numeric seconds, rename it into place, fsync the dir; a tier link of the plain
link's own times; then the original set aside, checked to be the same file,
and removed through removeMediaFile. A stored file appears only by the rename
of a verified temp.

Resumable after a kill at any step (a dead pid's temp discarded, a stored form
beside the original verified before the original goes, a set-aside original
renamed back, a dangling plain link beside a whole stored form removed).
Refused, touching nothing: both forms with different content, a corrupt stored
form, a .part beside it, a live-recording.json saying recording, a job running
for the video, a write within the quiet period, a move of the channel's media
(also re-asked before the original goes), an unreachable drive, low space.

controller/compressText.ts walks channels smallest first, paced by a byte
token bucket (40 MB/s, 8 while a recording runs) and render mode; dryRun
reports files, bytes, stored files, the estimate and free space and writes
nothing; verify decodes every stored file. Job kind compress-text: drainable,
replayable, needsMedia, not ingest, never resumed at boot; one job per channel
on the machine-wide compress-text queue (so a media move sees it as a writer);
limit takes one channel. Ops action, route, replay handler, OPERATING.md,
COMMANDS.md, CHANGELOG.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
MCOMMANDS.md | 1+
MOPERATING.md | 27+++++++++++++++++++++++++++
Mcommon/controller/buildIndex.test.ts | 26++++++++++++++++++++++++++
Acommon/controller/compressText.test.ts | 156+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/compressText.ts | 351+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/jobKinds.test.ts | 15++++++++++++++-
Mcommon/jobs/jobKinds.ts | 14++++++++++++++
Mcommon/lib/storedText-write-server.ts | 656++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Acommon/lib/storedText.compress.test.ts | 329+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/storedText.grep.test.ts | 2+-
Meditor/CHANGELOG.md | 7+++++++
Aeditor/app/api/ops/compress-text/route.test.ts | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/compress-text/route.ts | 52++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/jobs/jobReplayRegistry.ts | 11+++++++++++
Aeditor/app/storage/compressTextActions.ts | 153+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 23+++++++++++++++++++++++
16 files changed, 1879 insertions(+), 7 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -160,6 +160,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `review-compacted-original` | review-compacted-original records a person's review of one compacted copy (watch it first: get compaction-review's "watch"): {"slug", "id", "note"?}. It names the copy it is for ("watched", its sha256) and counts for that copy only; it changes nothing on disk. It is what lets drop-saved-alternate ("confirmOriginal": true) drop the original of a video not freshly checked on its platform. "formerOriginal": "&lt;file&gt;" reviews the active copy that replaced a former original instead. | | | `compaction-markers` | compaction-markers lists the "being compacted" markers (.compacting.json), each live or stale and why: {}. {"clear": {"slug", "id"}} removes a stale one; a live one is refused (cancel its job). Stale ones are also swept at editor boot and at the start of every compaction run. | | | `kept-failed-encodes` | kept-failed-encodes lists the encodes kept after a failed check (in each video's .compact-scratch, never active: chunks and the joined copy, their size, what failed): {}. {"clear": {"slug", "id"}} removes one (refused while its compaction runs). compact-saved-videos "reverify": true re-checks one without encoding. | | +| `compress-text` | compress-text stores the raw live-chat replays compressed (zstd, level 9): transcript.live\_chat.json becomes transcript.live\_chat.json.zst, read back by every reader as the same file, with the same times (the index sees no change): {"slugs"?: \[...\], "kinds"?: \["live-chat"\], "dryRun"?, "limit"?, "verify"?}. One file at a time: written beside the original, fsynced, read back and hashed against it, and only then the original removed; a crash at any step leaves a whole copy, and the next run finishes it. Left alone and counted: a file written in the last 10 minutes, one with a .part beside it, a video recording or with a job running, a drive that does not answer, a channel whose media is moving. Both forms present with different content are refused and both kept. "dryRun": true answers per channel the raw chats, their bytes, the stored ones, the estimate after (about 5 %, an estimate) and the free space, and writes nothing; "verify": true decodes every stored file in full and writes nothing; "limit" counts files compressed and takes exactly one channel in "slugs". One job per channel with work, on the machine-wide compress-text queue (one file at a time), waiting while render mode holds the machine and slower while a live recording runs; never resumed at boot (it removes originals) -- a re-run continues. | | | `build-cues` | build-cues writes each video's transcript.cues.json from its raw transcript (the caption-track rule for VTTs), as the digest card's Normalize button does: {"slug"}, "ids": \[...\] for those videos only (every one held), "force": true to rewrite a fresh one. A job on the channel's queue. The file every reader without an index build wants. | `pnpm ops build-cues --json '{"slug":"demo-yt","ids":["<videoId>"]}' --wait` | | `feed-metadata` | feed-metadata completes a podcast channel's records from its RSS feed: one fetch of the channel's url, then title, date, description and duration into each record that lacks them: {"slug"}. "dryRun": true counts matched, unmatched and already complete, and writes nothing. | `pnpm ops feed-metadata --json '{"slug":"demo-podcast","dryRun":true}' --wait` | | `refresh-report` | refresh-report regenerates a channel's report (the buckets and counts its page shows) on the one serial report queue: {"slug"} answers the job queued, or the one already waiting ("started": false); {"all": true} queues every channel and answers {queued, jobIds, skipped}. | `pnpm ops refresh-report --json '{"all":true}'` | diff --git a/OPERATING.md b/OPERATING.md @@ -1580,6 +1580,33 @@ pnpm wt prune --dry-run [--json] # w - **Not done by it**: the clip-window cache (`evict-clips`: re-fetching is paced), a project's only preview, other sessions' job directories, anything under `transcripts/`. +### Compress the raw live chats + +```sh +pnpm ops compress-text --json '{"dryRun":true}' # per channel: raw chats, bytes, the estimate after, free space; writes nothing +pnpm ops compress-text --json '{"slugs":["example"],"limit":20}' --wait # a first batch (limit: one channel) +pnpm ops compress-text --json '{"verify":true}' --wait # decode every stored chat in full; writes nothing +pnpm ops compress-text --json '{}' --wait # the rest; a re-run continues +``` + +- **What it does.** A raw live-chat replay, `transcript.live_chat.json`, is stored as `transcript.live_chat.json.zst` + (one zstd frame, level 9, its content size and checksum in the frame): about 5 % of its size. Every reader — the + index, normalize, the chat plan, the snapshot, the archive build, the missing-subs fetch — reads either form as the + same file (`common/lib/storedText-server.ts`). The stored file carries the original's times exactly, so the index + sees no change and nothing is re-normalized. +- **Safe at every step.** One file at a time: the stored form is written beside the original (in `media/<id>/` for a + tiered chat, on the same drive), fsynced, read back and hashed against the original, and only then is the original + removed, through `removeMediaFile`. A kill at any step leaves a whole copy, and the next run finishes it. +- **Left alone and counted:** a file written in the last 10 minutes; one with a `.part` beside it (a capture or a + download in progress); a video whose `live-recording.json` says `recording`, or with a job running; a drive that + is not mounted or not answering; a channel whose media is moving. **Both forms present with different content + are refused, and both kept**: the plain one is what readers read; look at the pair by hand. +- **One job per channel** with work, on one machine-wide queue, so a move of that channel's media refuses while it + runs. **Paced.** It waits while render mode holds the machine, reads at 40 MB/s (8 MB/s while a live recording runs), + and is never resumed by the boot pass: it removes originals, so a person re-runs it. Drain stops it between files. +- **By hand:** `zstdcat transcript.live_chat.json.zst` reads one. Delete a chat through the video page or the app, + never with `rm`: a plain file deleted beside an older stored one would bring that one back (the app removes both). + ### Compact saved videos ```sh diff --git a/common/controller/buildIndex.test.ts b/common/controller/buildIndex.test.ts @@ -943,6 +943,32 @@ test("(s) lane text-compress: a raw chat compressed in place changes NOTHING the assert.ok(tracksOf("d2").includes("live_chat"), "read through the stored form's tier link"); }); +test("(t) lane text-compress: THE COMPRESSOR itself, over a real and a tiered chat — the index sees no change", async () => { + resetCorpus(); + seedVideo("c1"); + seedDriveChannel(); + const chat = + JSON.stringify({ replayChatItemAction: { actions: [{ addChatItemAction: { item: { liveChatTextMessageRenderer: { message: { runs: [{ text: "real" }] }, authorName: { simpleText: "a" }, timestampUsec: "1000000" } } } }], videoOffsetTimeMsec: "1000" } }) + "\n"; + const { utimesSync, lutimesSync } = await import("node:fs"); + writeFileSync(path.join(videoDir("c1"), "transcript.live_chat.json"), chat); + utimesSync(path.join(videoDir("c1"), "transcript.live_chat.json"), 1763700000.123457, 1763700000.987653); + mkdirSync(path.join(DRIVE_MEDIA(), "d2"), { recursive: true }); + writeFileSync(path.join(DRIVE_MEDIA(), "d2", "transcript.live_chat.json"), chat); + symlinkSync("../../media/d2/transcript.live_chat.json", path.join(videoDir("d2", DRIVE_CHANNEL), "transcript.live_chat.json")); + lutimesSync(path.join(videoDir("d2", DRIVE_CHANNEL), "transcript.live_chat.json"), 1763700001.5, 1763700001.000003); + const mtimesOf = () => withIndex((db) => [...db("mtimes").getRange()].map(({ key, value }) => [key, value])); + await runIndex(); + const before = mtimesOf(); + const { compressStoredText } = await import("../lib/storedText-write-server"); + for (const dir of [videoDir("c1"), videoDir("d2", DRIVE_CHANNEL)]) { + const out = await compressStoredText(dir, "transcript.live_chat.json", { reserveBytes: 0 }); + assert.equal(out.status, "compressed", JSON.stringify(out)); + } + const after = await runIndex(); + assert.equal(after.res.changed, 0, after.log.join("\n")); + assert.deepEqual(mtimesOf(), before); +}); + test("(z) no write this file caused landed outside its temp root", () => { // LMDB writes natively, past the spy: its file must be under the root too. assert.ok(paths.lmdbPath.startsWith(ROOT + path.sep), paths.lmdbPath); diff --git a/common/controller/compressText.test.ts b/common/controller/compressText.test.ts @@ -0,0 +1,156 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { lstat, mkdir, mkdtemp, readdir, readFile, readlink, rm, symlink, utimes, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/compressText.test.ts +// +// THE MIGRATION (lane text-compress, slice 2): `compress-text` over a temp +// corpus — a dry run that touches nothing, a real run, its limit, its check, +// the render-mode wait and the slower pace while a recording runs. + +const ROOT = await mkdtemp(path.join(tmpdir(), "compress-text-")); +process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts"); +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +await mkdir(process.env.TRANSCRIPTS_DIR, { recursive: true }); +await writeFile(process.env.SETTINGS_FILE, "{}"); +test.after(() => rm(ROOT, { recursive: true, force: true })); + +const { getPaths } = await import("../lib/paths"); +const { compressText, byteThrottle } = await import("./compressText"); +const { readStoredText } = await import("../lib/storedText-server"); + +const paths = getPaths(); +const CHAT = "transcript.live_chat.json"; +const body = (seed: string, lines: number) => + Array.from({ length: lines }, (_, i) => + JSON.stringify({ replayChatItemAction: { actions: [{ text: `${seed} ${i} ${createHash("md5").update(seed + i).digest("hex")}` }], videoOffsetTimeMsec: String(i * 1000) } }), + ).join("\n") + "\n"; + +async function channel(slug: string, videos: Record<string, string>, opts: { tiered?: boolean } = {}): Promise<void> { + const channelDir = path.join(paths.channelsDir, slug); + await mkdir(path.join(channelDir, "data"), { recursive: true }); + await writeFile(path.join(channelDir, "config.json"), JSON.stringify({ handling: "youtube", url: `https://www.youtube.com/@${slug}` })); + if (opts.tiered) await mkdir(path.join(channelDir, "media"), { recursive: true }); + for (const [id, chat] of Object.entries(videos)) { + const dir = path.join(channelDir, "data", id); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify({ id })); + if (opts.tiered) { + await mkdir(path.join(channelDir, "media", id), { recursive: true }); + await writeFile(path.join(channelDir, "media", id, CHAT), chat); + await symlink(path.join("..", "..", "media", id, CHAT), path.join(dir, CHAT)); + } else { + await writeFile(path.join(dir, CHAT), chat); + } + // Old enough for the quiet period. + await utimes(path.join(dir, CHAT), 1_700_000_000, 1_700_000_000.5); + } +} + +async function tree(dir: string): Promise<string[]> { + const out: string[] = []; + async function walk(d: string): Promise<void> { + for (const e of (await readdir(d).catch(() => [] as string[])).sort()) { + const p = path.join(d, e); + const l = await lstat(p); + if (l.isSymbolicLink()) out.push(`${p} -> ${await readlink(p)} ${l.mtimeMs}`); + else if (l.isDirectory()) { + out.push(`${p}/ ${l.mtimeMs}`); + await walk(p); + } else out.push(`${p} ${l.size} ${l.mtimeMs} ${createHash("sha256").update(await readFile(p)).digest("hex")}`); + } + } + await walk(dir); + return out; +} + +const A = { a1: body("a1", 4000), a2: body("a2", 2000) }; +const B = { b1: body("b1", 3000) }; +await channel("alpha", A); +await channel("beta", B, { tiered: true }); + +test("a dry run reports bytes before and the estimate after, per channel — and touches NOTHING", async () => { + const before = await tree(ROOT); + const lines: string[] = []; + const r = await compressText({ paths, dryRun: true, onLog: (l) => lines.push(l) }); + assert.deepEqual(await tree(ROOT), before, "not one entry changed, not one mtime"); + const alpha = r.channels.find((c) => c.slug === "alpha")!; + assert.equal(alpha.plainFiles, 2); + assert.equal(alpha.plainBytes, A.a1.length + A.a2.length); + assert.equal(alpha.estimateAfterBytes, Math.round(alpha.plainBytes * 0.05)); + assert.ok(typeof alpha.free?.corpus === "number"); + const beta = r.channels.find((c) => c.slug === "beta")!; + assert.equal(beta.plainFiles, 1, "a tier link's bytes are counted through the link"); + assert.equal(beta.plainBytes, B.b1.length); + assert.match(lines.join(""), /Nothing was written/); +}); + +test("a real run with a limit compresses that many, smallest first; a re-run continues; the check passes", async () => { + const waits: number[] = []; + const first = await compressText({ + paths, + slugs: ["alpha"], + limit: 1, + onLog: () => {}, + waitForRender: async () => (waits.push(1), 0), + }); + assert.equal(first.stopped, "limit"); + const alpha = first.channels[0]; + assert.equal(alpha.compressed, 1); + // Smallest first: a2. + const a2 = path.join(paths.channelsDir, "alpha", "data", "a2"); + assert.deepEqual((await readdir(a2)).sort(), ["metadata.info.json", `${CHAT}.zst`]); + assert.equal(await readStoredText(a2, CHAT, "utf8"), A.a2); + assert.equal(waits.length, 1, "render mode was asked before the file"); + + const rest = await compressText({ paths, onLog: () => {} }); + assert.equal(rest.stopped, undefined); + const byslug = Object.fromEntries(rest.channels.map((c) => [c.slug, c])); + assert.equal(byslug.alpha.compressed, 1); + assert.equal(byslug.alpha.already, 1); + assert.equal(byslug.beta.compressed, 1); + for (const [slug, vids] of [["alpha", A], ["beta", B]] as const) { + for (const [id, chat] of Object.entries(vids)) { + assert.equal(await readStoredText(path.join(paths.channelsDir, slug, "data", id), CHAT, "utf8"), chat, `${slug}/${id}`); + } + } + const again = await compressText({ paths, onLog: () => {} }); + assert.equal(again.channels.reduce((a, c) => a + (c.compressed ?? 0), 0), 0); + + const check = await compressText({ paths, verify: true, onLog: () => {} }); + assert.deepEqual( + check.channels.map((c) => [c.slug, c.verified, c.problems?.length]), + [["alpha", 2, 0], ["beta", 1, 0]], + ); +}); + +test("render mode ending the wait by a cancel stops the run before any file", async () => { + await channel("gamma", { g1: body("g1", 100) }); + const r = await compressText({ paths, slugs: ["gamma"], onLog: () => {}, waitForRender: async () => null }); + assert.equal(r.stopped, "cancelled"); + assert.deepEqual((await readdir(path.join(paths.channelsDir, "gamma", "data", "g1"))).sort(), ["metadata.info.json", CHAT]); +}); + +test("the pace: a token bucket over bytes, at whatever rate is asked each time (slower while recording)", async () => { + let t = 0; + const slept: number[] = []; + let recording = false; + const throttle = byteThrottle( + () => (recording ? 8 : 40) * 1024 * 1024, + async (ms) => { + slept.push(Math.round(ms)); + t += ms; + }, + () => t, + ); + await throttle(40 * 1024 * 1024); // the first second's worth: no wait + await throttle(40 * 1024 * 1024); // the next waits a second + recording = true; + await throttle(8 * 1024 * 1024); // queued behind the second; 8 MB at 8 MB/s is one more second + await throttle(8 * 1024 * 1024); + assert.deepEqual(slept, [1000, 1000, 1000]); +}); diff --git a/common/controller/compressText.ts b/common/controller/compressText.ts @@ -0,0 +1,351 @@ +// COMPRESS TEXT — the migration that puts the existing raw live-chat replays +// into their stored form (lib/storedText.ts): `transcript.live_chat.json` → +// `transcript.live_chat.json.zst`, 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). Lane text-compress, +// slice 2; `pnpm ops compress-text` posts it. +// +// 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, 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. +// `verify` decodes every stored file in full and writes nothing. + +import path from "node:path"; +import { open, readdir, stat, statfs } from "node:fs/promises"; +import type { Paths } from "../lib/paths"; +import { LIVE_CHAT_FILENAME } from "../lib/videoStatus"; +import { storedFormsIn, storedNameOf } from "../lib/storedText"; +import { frameContentSize } from "../lib/storedText-server"; +import { + compressStoredText, + verifyStoredText, + type CompressOutcome, + type CompressSkipReason, +} 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"] as const; +export type CompressTextKind = (typeof COMPRESS_TEXT_KINDS)[number]; + +// Measured on a sample (lane text-compress design §1): a raw chat at level 9 +// is ~5 % of its size. An estimate, and every line that uses it says so. +export const CHAT_RATIO_ESTIMATE = 0.05; +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[]; + dryRun?: boolean; + verify?: 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<number | null>; + sleep?: (ms: number, signal?: AbortSignal) => Promise<void>; + now?: () => number; + // Tests: the compressor's options passed through (a kill point, a pid). + compressOpts?: Parameters<typeof compressStoredText>[2]; +}; + +export type ChannelLine = { + slug: string; + // Why the channel was not walked, when it was not. + refused?: string; + plainFiles: number; + plainBytes: number; + storedFiles: number; + storedLogicalBytes: number; + storedBytes: number; + // Dry run only: what the plain files would take at the estimated ratio. + estimateAfterBytes?: number; + // Dry run only: free space now on the disk(s) holding this channel's chats. + free?: { corpus?: number; media?: number }; + // A real run. + compressed?: number; + bytesBefore?: number; + bytesAfter?: number; + already?: number; + changed?: number; + skipped?: Partial<Record<CompressSkipReason, number>>; + failed?: { id: string; error: string }[]; + // Verify. + verified?: number; + problems?: { id: string; status: string; detail?: string }[]; +}; + +export type CompressTextResult = { + dryRun: boolean; + verify: boolean; + channels: ChannelLine[]; + stopped?: "drained" | "cancelled" | "limit"; + lines: string[]; +}; + +type Candidate = { id: string; videoDir: string; size: 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<void>, + now: () => number = Date.now, + signal?: AbortSignal, +): (bytes: number) => Promise<void> { + 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<void>((resolve) => { + const t = setTimeout(resolve, ms); + signal?.addEventListener("abort", () => { + clearTimeout(t); + resolve(); + }, { once: true }); + }); + +async function storedLogicalSize(file: string): Promise<number | null> { + 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; + } +} + +// One channel's chats, by what is on disk. Sizes are `stat`s (through a tier +// link, under the drive's watchdog); no content is read. +async function surveyChannel( + channelDir: string, + drive: string | undefined, +): Promise<{ plain: Candidate[]; stored: { id: string; videoDir: string; bytes: number; logical: number }[] }> { + const dataDir = path.join(channelDir, "data"); + const ids = (await readdir(dataDir).catch(() => [] as string[])).sort(); + const plain: Candidate[] = []; + const stored: { id: string; videoDir: string; bytes: number; logical: number }[] = []; + const sizeOf = (p: string) => + (drive ? onDrive(drive, () => stat(p)) : stat(p)).then((s) => s.size, () => null); + for (const id of ids) { + const videoDir = path.join(dataDir, id); + const entries = await readdir(videoDir).catch(() => null); + if (!entries) continue; + const forms = storedFormsIn(entries, LIVE_CHAT_FILENAME); + if (forms === "plain" || forms === "both") { + const size = await sizeOf(path.join(videoDir, LIVE_CHAT_FILENAME)); + if (size !== null) plain.push({ id, videoDir, size }); + } + if (forms === "zst" || forms === "both") { + const zp = path.join(videoDir, storedNameOf(LIVE_CHAT_FILENAME)); + const bytes = await sizeOf(zp); + const logical = bytes === null ? null : await (drive + ? onDrive(drive, () => storedLogicalSize(zp)) + : storedLogicalSize(zp)).catch(() => null); + if (bytes !== null) stored.push({ id, videoDir, bytes, logical: logical ?? 0 }); + } + } + // Smallest first: the early files are the cheap ones. + plain.sort((a, b) => a.size - b.size || (a.id < b.id ? -1 : 1)); + return { plain, stored }; +} + +export async function compressText(opts: CompressTextOptions): Promise<CompressTextResult> { + const dryRun = opts.dryRun === true; + const verify = !dryRun && opts.verify === true; + 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[] = []; + let compressedThisRun = 0; + let stopped: CompressTextResult["stopped"]; + + 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 { plain, stored } = await surveyChannel(channelDir, drive); + line.plainFiles = plain.length; + line.plainBytes = plain.reduce((a, c) => a + c.size, 0); + line.storedFiles = stored.length; + line.storedBytes = stored.reduce((a, c) => a + c.bytes, 0); + line.storedLogicalBytes = stored.reduce((a, c) => a + c.logical, 0); + + if (dryRun) { + line.estimateAfterBytes = Math.round(line.plainBytes * CHAT_RATIO_ESTIMATE); + const freeOf = (p: string) => + statfs(p).then((f) => f.bavail * f.bsize, () => undefined); + line.free = { + corpus: await freeOf(path.join(channelDir, "data")), + ...(drive ? { media: await onDrive(drive, () => freeOf(drive)).catch(() => undefined) } : {}), + }; + if (line.plainFiles + line.storedFiles > 0) { + say( + `${slug}: ${line.plainFiles} raw chat(s), ${fmtBytes(line.plainBytes)} → ~${fmtBytes(line.estimateAfterBytes)} ` + + `(estimate, ${Math.round(CHAT_RATIO_ESTIMATE * 100)} %); already stored ${line.storedFiles} ` + + `(${fmtBytes(line.storedBytes)} holding ${fmtBytes(line.storedLogicalBytes)}); ` + + `free on ${drive ? "the media drive" : "the corpus disk"} ` + + `${fmtBytes((drive ? line.free.media : line.free.corpus) ?? 0)}`, + ); + } + continue; + } + + if (verify) { + line.verified = 0; + line.problems = []; + for (const s of stored) { + if (opts.signal?.aborted) { stopped = "cancelled"; break; } + if (opts.drainSignal?.aborted) { stopped = "drained"; break; } + const v = await verifyStoredText(s.videoDir, LIVE_CHAT_FILENAME, { throttle }); + if (v.status === "ok") line.verified += 1; + else { + line.problems.push({ id: s.id, status: v.status, ...("detail" in v ? { detail: v.detail } : {}) }); + say(`${slug}/${s.id}: ${v.status}${"detail" in v ? ` — ${v.detail}` : ""}`); + } + } + say(`${slug}: verified ${line.verified} stored chat(s), ${line.problems.length} problem(s)`); + continue; + } + + line.compressed = 0; + line.bytesBefore = 0; + line.bytesAfter = 0; + line.already = line.storedFiles; + line.changed = 0; + line.skipped = {}; + line.failed = []; + for (const c of plain) { + if (opts.signal?.aborted) { stopped = "cancelled"; break; } + if (opts.drainSignal?.aborted) { stopped = "drained"; break; } + if (opts.limit !== undefined && compressedThisRun >= opts.limit) { stopped = "limit"; break; } + if (opts.waitForRender) { + const waited = await opts.waitForRender(); + if (waited === null) { stopped = "cancelled"; break; } + } + let out: CompressOutcome; + try { + out = await compressStoredText(c.videoDir, LIVE_CHAT_FILENAME, { + quietMs: opts.quietMs ?? COMPRESS_QUIET_MS, + now, + isBusy: opts.isBusy ? () => opts.isBusy!(slug, c.id) : undefined, + throttle, + ...(opts.signal ? { signal: opts.signal } : {}), + onLog: (l) => opts.onLog(`${l}\n`), + ...opts.compressOpts, + }); + } catch (err) { + if ((err as Error).name === "CompressKill") throw err; + line.failed.push({ id: c.id, error: (err as Error).message }); + say(`${slug}/${c.id}: failed — ${(err as Error).message} (the original is untouched)`); + continue; + } + if (out.status === "compressed") { + compressedThisRun += 1; + line.compressed += 1; + line.bytesBefore += out.before; + line.bytesAfter += out.after; + opts.onLog(`${slug}/${c.id}: ${fmtBytes(out.before)} → ${fmtBytes(out.after)}${out.tiered ? " (media tier)" : ""}\n`); + } else if (out.status === "already") { + line.already += 1; + } else if (out.status === "changed") { + line.changed += 1; + } else if (out.status === "skipped") { + line.skipped[out.reason] = (line.skipped[out.reason] ?? 0) + 1; + if (out.reason === "both-differ" || out.reason === "stored-corrupt" || out.reason === "retired-kept") { + say(`${slug}/${c.id}: refused — ${out.reason}${out.detail ? ` (${out.detail})` : ""}; both files are kept`); + } + } + } + const skippedText = Object.entries(line.skipped) + .map(([r, n]) => `${n} ${r}`) + .join(", "); + if (line.plainFiles + line.storedFiles > 0) { + say( + `${slug}: compressed ${line.compressed} (${fmtBytes(line.bytesBefore)} → ${fmtBytes(line.bytesAfter)}), ` + + `already ${line.already}, changed ${line.changed}, skipped ${skippedText || "0"}, failed ${line.failed.length}`, + ); + } + } + + if (dryRun) { + const tot = channels.reduce((a, c) => a + c.plainBytes, 0); + const n = channels.reduce((a, c) => a + c.plainFiles, 0); + say(`Dry run: ${n} raw chat(s), ${fmtBytes(tot)} → ~${fmtBytes(Math.round(tot * CHAT_RATIO_ESTIMATE))} (estimate). 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); + say(`Compressed ${c} raw chat(s): ${fmtBytes(b)} → ${fmtBytes(f)}${stopped ? ` — stopped (${stopped}); a re-run continues` : ""}.`); + } + return { dryRun, verify, channels, ...(stopped ? { stopped } : {}), lines }; +} diff --git a/common/jobs/jobKinds.test.ts b/common/jobs/jobKinds.test.ts @@ -301,7 +301,8 @@ test("release 18: every drainable kind but the lane runners and the clip-window // fetch-windows writes only `data/<id>/clips/`, a cache the index never reads. // wayback-scan writes only `wayback-scan.json`, which the index never reads. // save-page-now-batch writes only its own state and evidence (.spn-batches/). - const notIngest = new Set(["fetch-windows", "wayback-scan", "save-page-now-batch"]); + // compress-text changes how a raw chat is stored, never what the index reads. + const notIngest = new Set(["fetch-windows", "wayback-scan", "save-page-now-batch", "compress-text"]); for (const kind of jobKindIds()) { if (!isDrainableKind(kind) || runners.has(kind) || notIngest.has(kind)) continue; assert.equal(isIngestKind(kind), true, `${kind} is drainable and per channel: an ingest kind`); @@ -448,3 +449,15 @@ test("compact-saved-videos is a drainable, replayable media ingest kind the boot assert.equal(isIngestKind("compact-saved-videos"), true); assert.equal(kindIsNetwork("compact-saved-videos"), false); }); + +test("compress-text is a drainable, replayable media kind: not ingest, never resumed by the boot pass", () => { + const meta = getJobKind("compress-text"); + assert.ok(meta, "registered"); + assert.equal(jobKindLabel("compress-text"), "Compress text"); + assert.equal(isDrainableKind("compress-text"), true); + assert.equal(meta.replayable, true); + assert.equal(meta.resumeOnBoot, undefined); + assert.equal(kindNeedsMedia("compress-text"), true); + assert.equal(isIngestKind("compress-text"), false); + assert.equal(kindIsNetwork("compress-text"), false); +}); diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts @@ -1625,6 +1625,20 @@ const JOB_KINDS: Record<string, JobKindMeta> = { queueKeyStrategy: "custom", needsMedia: true, }, + // THE RAW LIVE CHATS PUT INTO THEIR STORED FORM (controller/compressText.ts, + // `pnpm ops compress-text`; lane text-compress): one file at a time on the + // machine-wide `compress-text` queue, one job per channel. It opens and + // removes the big file (media). NOT an ingest kind: the index reads the same + // cues and the same times after it (the stored form carries them). NOT + // resumed by the boot pass: it removes originals, and a person re-runs it. + "compress-text": { + kind: "compress-text", + label: "Compress text", + drainable: true, + replayable: true, + queueKeyStrategy: "custom", + needsMedia: true, + }, }; export function getJobKind(kind: string): JobKindMeta | undefined { diff --git a/common/lib/storedText-write-server.ts b/common/lib/storedText-write-server.ts @@ -1,7 +1,7 @@ // STORED TEXT ON DISK — THE WRITE HALF: the one way to delete a declared name -// (`removeStoredText`), and the compressor (`compressStoredText`, below). The -// names and the rules are lib/storedText.ts; the read path is -// lib/storedText-server.ts. +// (`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 @@ -14,8 +14,40 @@ // // lib/, so no controller import (architecture.test.ts). SERVER-ONLY. -import { removeMediaFile } from "./mediaTier-server"; -import { storedNameOf } from "./storedText"; +import path from "node:path"; +import { createHash } from "node:crypto"; +import { createReadStream, type Stats } from "node:fs"; +import { + lstat, + lutimes, + open, + readdir, + readFile, + readlink, + rename, + rm, + stat, + statfs, + symlink, + utimes, +} from "node:fs/promises"; +import { Transform, Writable } from "node:stream"; +import { pipeline } from "node:stream/promises"; +import { + MEDIA_LINK_NAME, + TIER_RELOCATION_MARKER, + removeMediaFile, + tierMediaFile, +} from "./mediaTier-server"; +import { onDrive, stalledLocationForPath } from "./storageHealth"; +import { LIVE_RECORDING_FILENAME } from "./liveCapture"; +import { isStoredTextName, storedNameOf } from "./storedText"; +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 — @@ -24,3 +56,617 @@ export async function removeStoredText(videoDir: string, name: string): Promise< await removeMediaFile(videoDir, storedNameOf(name)); await removeMediaFile(videoDir, name); } + +// ── 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/<id>/<name> -> ../../media/<id>/<name>` the work happens in +// `media/<id>/` and the stored form gets a tier link of its own; for a real +// file, in `data/<id>/`. 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 (`<name>.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 (`.<name>.retire-<pid>`), 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 pid'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. + +export type CompressSkipReason = + | "not-declared" + | "relocating" // the channel's media is moving (its marker stands) + | "partial" // a `<name>.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 + +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<void>; + // Free space the disk must keep beyond the temp (default 2 GiB). + reserveBytes?: number; + // The pid temps are named for (tests: a dead one, to stand for a kill). + pid?: number; + 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 { + if (pid === process.pid) return true; + try { + process.kill(pid, 0); + return true; + } catch (err) { + return errCode(err) === "EPERM"; + } +} + +const lstatOrNull = (p: string) => lstat(p).catch(() => null); + +async function fsyncDir(dir: string): Promise<void> { + 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<void>): 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<number | null> { + 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<void> } = {}, +): Promise<Digest> { + 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<Entry> { + 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<boolean> { + 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<string | null> { + 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 compression per file in this process at a time (the migration and a +// finalise could otherwise meet on one file and remove each other's temp). +const active = new Set<string>(); + +export async function compressStoredText( + videoDir: string, + name: string, + opts: CompressOptions = {}, +): Promise<CompressOutcome> { + if (!isStoredTextName(name)) return { status: "skipped", reason: "not-declared" }; + const key = path.resolve(videoDir, name); + if (active.has(key)) return { status: "skipped", reason: "busy", detail: "being compressed" }; + active.add(key); + try { + return await compressOne(videoDir, name, opts); + } finally { + active.delete(key); + } +} + +async function compressOne(videoDir: string, name: string, opts: CompressOptions): Promise<CompressOutcome> { + const pid = opts.pid ?? process.pid; + const crash = (p: CompressKillPoint) => opts.crashAt?.(p); + const log = opts.onLog ?? (() => {}); + 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"); + + let reach: "yes" | "no" | "none" | undefined; + const reachable = async () => (reach ??= await mediaReachable(channelDir)); + + // ── repair: a dead run's leftovers in the video dir ─────────────────────── + const tempRe = new RegExp(`^\\.${escapeRe(stored)}\\.(?:compressing|tierlink)-(\\d+)$`); + const retireRe = new RegExp(`^\\.${escapeRe(name)}\\.retire-(\\d+)$`); + const dead = (m: RegExpExecArray | null) => !!m && Number(m[1]) !== pid && !processAlive(Number(m[1])); + for (const e of entries) { + // Scratch of a run that is gone (a temp, a temp link): never a copy. + if (dead(tempRe.exec(e))) await rm(path.join(videoDir, e), { force: true }); + } + for (const e of entries) { + if (!dead(retireRe.exec(e))) continue; + const r = await entryAt(videoDir, e); + if (r.kind === "link" && (await 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 the file again, + // and is verified below like any plain file. + await rename(path.join(videoDir, e), path.join(videoDir, name)); + 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); + } + + // ── 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 === "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; + if (opts.quietMs && now() - s.mtimeMs < 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) { + for (const e of await readdir(workDir).catch(() => [] as string[])) { + if (dead(tempRe.exec(e))) await rm(path.join(workDir, e), { force: true }); + } + } + + // ── 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; + } + + 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) { + 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); + } 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, opts); + if (made !== "ok") return made; + zPath = path.join(workDir, stored); + crash("placed"); + } + + // ── its tier link ───────────────────────────────────────────────────────── + if (tiered && zKind === "none") { + const tmpLink = path.join(videoDir, `.${stored}.tierlink-${pid}`); + 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}`; + const retiredPath = path.join(videoDir, retired); + await rename(p.path, retiredPath); + 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. + 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 log(` kept ${retired} beside the newer ${name}: it is neither`); + } + } + log(` ${name} changed while it was being compressed: left for the next run`); + return { status: "changed" }; + } + await removeMediaFile(videoDir, retired); + await fsyncDir(videoDir); + + // ── 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 {} + +// 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, + pid: number, + opts: CompressOptions, +): Promise<"ok" | CompressOutcome> { + const tmp = path.join(workDir, `.${stored}.compressing-${pid}`); + 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<void> } = {}, +): Promise<VerifyOutcome> { + 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 }; +} diff --git a/common/lib/storedText.compress.test.ts b/common/lib/storedText.compress.test.ts @@ -0,0 +1,329 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { + lstat, + mkdir, + mkdtemp, + readdir, + readFile, + readlink, + rename, + rm, + stat, + symlink, + utimes, + writeFile, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/storedText.compress.test.ts +// +// THE COMPRESSOR (lane text-compress, slice 2) — a DATA-LOSS-SENSITIVE path: +// it removes originals. Every case is a temp channel tree. The kill points are +// the compressor's `crashAt` seam: it throws there and nothing after it runs, +// cleanup included — what a SIGKILL leaves — and the temps carry a pid that is +// not alive. After each: a reader still gets ONE WHOLE COPY, a leftover +// partial stored file never counts as the file, and the next run finishes. + +const ROOT = await mkdtemp(path.join(tmpdir(), "stored-compress-")); +test.after(() => rm(ROOT, { recursive: true, force: true })); + +const { + compressStoredText, + CompressKill, + verifyStoredText, +} = await import("./storedText-write-server"); +const { readStoredText, statStoredText, readdirLogical, encodeStoredBytes } = await import("./storedText-server"); + +const CHAT = "transcript.live_chat.json"; +const ZST = `${CHAT}.zst`; +const DEAD = 999_999_999; // never a live pid +const KILL_POINTS = ["compressing", "written", "verified", "placed", "linked", "retired"] as const; + +// ~1.6 MB of chat lines, varied enough that the stored frame is written in +// several chunks (so a kill at "compressing" leaves a PARTIAL temp). +const ORIGINAL = Array.from({ length: 12_000 }, (_, i) => + JSON.stringify({ + replayChatItemAction: { + actions: [{ addChatItemAction: { item: { liveChatTextMessageRenderer: { message: { runs: [{ text: `msg ${i} ${createHash("md5").update(String(i)).digest("hex")}` }] }, authorName: { simpleText: `viewer${i % 97}` } } } } }], + videoOffsetTimeMsec: String(i * 1000), + }, + }), +).join("\n") + "\n"; + +let n = 0; +type Fixture = { channelDir: string; videoDir: string; mediaDir: string; tiered: boolean; plainMs: number; bytesMs: number }; + +// A video with its raw chat — a real file, or a tier link into media/<id>/ — +// with sub-millisecond times (as ext4 keeps them). +async function fixture(tiered: boolean, opts: { mediaAway?: boolean } = {}): Promise<Fixture> { + const slug = `ch${++n}`; + const channelDir = path.join(ROOT, "channels", slug); + const id = "vid00000001"; + const videoDir = path.join(channelDir, "data", id); + const mediaRoot = path.join(ROOT, "drive", slug, "media"); + const mediaDir = path.join(mediaRoot, id); + await mkdir(videoDir, { recursive: true }); + await writeFile(path.join(channelDir, "config.json"), JSON.stringify({ handling: "youtube" })); + await writeFile(path.join(videoDir, "metadata.info.json"), JSON.stringify({ id })); + if (tiered) { + await mkdir(mediaDir, { recursive: true }); + await symlink(mediaRoot, path.join(channelDir, "media")); + await writeFile(path.join(mediaDir, CHAT), ORIGINAL); + await utimes(path.join(mediaDir, CHAT), 1763700000.111111, 1763700000.222223); + await symlink(path.join("..", "..", "media", id, CHAT), path.join(videoDir, CHAT)); + const { lutimes } = await import("node:fs/promises"); + await lutimes(path.join(videoDir, CHAT), 1763700005.5, 1763700005.123457); + } else { + await writeFile(path.join(videoDir, CHAT), ORIGINAL); + await utimes(path.join(videoDir, CHAT), 1763700000.111111, 1763700000.987653); + } + const plainMs = (await lstat(path.join(videoDir, CHAT))).mtimeMs; + const bytesMs = (await stat(path.join(videoDir, CHAT))).mtimeMs; + return { channelDir, videoDir, mediaDir, tiered, plainMs, bytesMs }; +} + +const killAt = (point: string) => (p: string) => { + if (p === point) throw new CompressKill(p as never); +}; + +// A READER GETS ONE WHOLE COPY: the read path answers the original, the +// logical listing has the chat, and a stored form that is there decodes whole. +async function assertWhole(f: Fixture, why: string): Promise<void> { + assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), ORIGINAL, `${why}: the read path`); + assert.ok((await readdirLogical(f.videoDir)).includes(CHAT), `${why}: listed`); + const z = await lstat(path.join(f.videoDir, ZST)).catch(() => null); + if (z) { + const v = await verifyStoredText(f.videoDir, CHAT); + assert.equal(v.status, "ok", `${why}: a stored form present is whole (${JSON.stringify(v)})`); + } +} + +// THE END STATE: the stored form only, the same content, the same times, no +// temp anywhere. +async function assertFinal(f: Fixture, why: string): Promise<void> { + const data = (await readdir(f.videoDir)).sort(); + assert.deepEqual(data, ["metadata.info.json", ZST], `${why}: data/<id>`); + if (f.tiered) { + assert.ok((await lstat(path.join(f.videoDir, ZST))).isSymbolicLink(), `${why}: a tier link`); + assert.equal(await readlink(path.join(f.videoDir, ZST)), path.join("..", "..", "media", "vid00000001", ZST)); + assert.deepEqual((await readdir(f.mediaDir)).sort(), [ZST], `${why}: media/<id>`); + } + assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), ORIGINAL, `${why}: content`); + assert.equal((await statStoredText(f.videoDir, CHAT, { link: true })).stats.mtimeMs, f.plainMs, `${why}: the lstat key`); + assert.equal((await statStoredText(f.videoDir, CHAT)).stats.mtimeMs, f.bytesMs, `${why}: the stat`); + assert.ok((await stat(path.join(f.videoDir, ZST))).size < ORIGINAL.length / 4, `${why}: compressed`); +} + +const run = (f: Fixture, extra: Parameters<typeof compressStoredText>[2] = {}) => + compressStoredText(f.videoDir, CHAT, { reserveBytes: 0, ...extra }); + +for (const tiered of [false, true]) { + const how = tiered ? "tiered" : "real"; + + test(`${how}: compressed, then idempotent`, async () => { + const f = await fixture(tiered); + const out = await run(f); + assert.equal(out.status, "compressed", JSON.stringify(out)); + assert.ok(out.status === "compressed" && out.before === ORIGINAL.length && out.tiered === tiered); + await assertFinal(f, "first run"); + assert.equal((await run(f)).status, "already"); + await assertFinal(f, "second run"); + }); + + // A real file has no tier link to place. + for (const point of KILL_POINTS.filter((p) => tiered || p !== "linked")) { + test(`${how}: killed at "${point}" — one whole copy remains, a partial never counts, the next run finishes`, async () => { + const f = await fixture(tiered); + let partial = 0; + await assert.rejects(run(f, { pid: DEAD, crashAt: killAt(point) }), CompressKill); + await assertWhole(f, `after the kill at ${point}`); + if (point === "compressing" || point === "written" || point === "verified") { + // The temp is the only stored bytes, and no reader sees it. + const work = tiered ? f.mediaDir : f.videoDir; + const temps = (await readdir(work)).filter((e) => e.includes(".compressing-")); + assert.equal(temps.length, 1, `${point}: the temp is there`); + assert.equal(await lstat(path.join(work, ZST)).catch(() => null), null, `${point}: no stored file`); + partial = (await stat(path.join(work, temps[0]))).size; + } + const out = await run(f); + assert.equal(out.status, "compressed", `${point}: ${JSON.stringify(out)}`); + await assertFinal(f, `the run after ${point}`); + if (point === "compressing") { + assert.ok(partial < (await stat(path.join(f.videoDir, ZST))).size, "the temp the kill left was partial"); + } + }); + } + + test(`${how}: both forms with DIFFERENT content are refused, and nothing is touched`, async () => { + const f = await fixture(tiered); + await run(f); + // A newer plain file beside the stored one (a re-fetch). + await writeFile(path.join(f.videoDir, CHAT), "NEWER\n"); + const before = await tree(f.channelDir); + const out = await run(f); + assert.deepEqual(out.status === "skipped" && out.reason, "both-differ", JSON.stringify(out)); + assert.deepEqual(await tree(f.channelDir), before); + assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), "NEWER\n", "the plain one is read"); + }); + + test(`${how}: a writer that replaces the file mid-run wins — "changed", the new file kept`, async () => { + // The seam is synchronous: the new file lands by rename, as yt-dlp's do, + // between the stored form landing and the original being set aside. + const g = await fixture(tiered); + const { writeFileSync, renameSync } = await import("node:fs"); + const r = await run(g, { + crashAt: (p) => { + if (p !== "placed") return; + writeFileSync(path.join(g.videoDir, ".new-chat"), "REWRITTEN\n"); + renameSync(path.join(g.videoDir, ".new-chat"), path.join(g.videoDir, CHAT)); + }, + }); + assert.equal(r.status, "changed", JSON.stringify(r)); + assert.equal(await readFile(path.join(g.videoDir, CHAT), "utf8"), "REWRITTEN\n"); + assert.equal(await readStoredText(g.videoDir, CHAT, "utf8"), "REWRITTEN\n"); + assert.deepEqual((await readdir(g.videoDir)).filter((e) => e.includes(".retire-")), []); + }); + + test(`${how}: skipped, touching nothing — a .part, a recording, a move, a job, a recent write, a full disk`, async () => { + const cases: [string, (f: Fixture) => Promise<Parameters<typeof compressStoredText>[2]>][] = [ + ["partial", async (f) => (await writeFile(path.join(f.videoDir, `${CHAT}.part`), "x"), {})], + ["recording", async (f) => (await writeFile(path.join(f.videoDir, "live-recording.json"), JSON.stringify({ status: "recording" })), {})], + ["relocating", async (f) => (await writeFile(path.join(f.channelDir, ".relocating.json"), "{}"), {})], + ["busy", async () => ({ isBusy: () => true })], + ["recent", async (f) => ({ quietMs: 600_000, now: () => f.bytesMs + 1000 })], + ["low-space", async () => ({ reserveBytes: Number.MAX_SAFE_INTEGER })], + ]; + for (const [reason, arrange] of cases) { + const f = await fixture(tiered); + const extra = await arrange(f); + const before = await tree(path.dirname(path.dirname(f.channelDir))); + const out = await run(f, extra); + assert.equal(out.status === "skipped" && out.reason, reason, `${reason}: ${JSON.stringify(out)}`); + assert.deepEqual(await tree(path.dirname(path.dirname(f.channelDir))), before, `${reason}: nothing touched`); + } + }); +} + +for (const tiered of [false, true]) { + const how = tiered ? "tiered" : "real"; + + test(`${how}: a move of the channel's media that begins mid-run keeps the original (the tier hook's rule)`, async () => { + const f = await fixture(tiered); + const { writeFileSync } = await import("node:fs"); + const out = await run(f, { + crashAt: (p) => { + if (p === "placed") writeFileSync(path.join(f.channelDir, ".relocating.json"), "{}"); + }, + }); + assert.equal(out.status === "skipped" && out.reason, "relocating", JSON.stringify(out)); + assert.equal(await readFile(path.join(f.videoDir, CHAT), "utf8"), ORIGINAL, "the original is untouched"); + await assertWhole(f, "mid-move"); + await rm(path.join(f.channelDir, ".relocating.json")); + assert.equal((await run(f)).status, "compressed"); + await assertFinal(f, "after the move"); + }); + + test(`${how}: a newer file written just after the original was set aside is kept, and read`, async () => { + const f = await fixture(tiered); + const { writeFileSync } = await import("node:fs"); + const out = await run(f, { + crashAt: (p) => { + if (p === "retired") writeFileSync(path.join(f.videoDir, CHAT), "NEWEST\n"); + }, + }); + assert.equal(out.status, "compressed", JSON.stringify(out)); + assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), "NEWEST\n", "the newer file is the truth"); + assert.deepEqual((await readdir(f.videoDir)).filter((e) => e.includes(".retire-")), []); + const again = await run(f); + assert.equal(again.status === "skipped" && again.reason, "both-differ", "refused, both kept"); + }); +} + +test("an unmounted media drive: skipped as unreachable, and nothing is created on the root filesystem", async () => { + const f = await fixture(true); + const drive = path.join(ROOT, "drive", path.basename(f.channelDir)); + await rename(drive, `${drive}-unmounted`); + try { + const out = await run(f); + assert.equal(out.status === "skipped" && out.reason, "unreachable", JSON.stringify(out)); + assert.equal(await lstat(drive).catch(() => null), null, "the mountpoint is not rebuilt"); + assert.deepEqual((await readdir(f.videoDir)).sort(), ["metadata.info.json", CHAT]); + } finally { + await rename(`${drive}-unmounted`, drive); + } + assert.equal((await run(f)).status, "compressed"); +}); + +test("killed INSIDE the original's removal (its bytes gone, its link not): readers get the stored form; the next run removes the link", async () => { + const f = await fixture(true); + await run(f); + // What `removeMediaFile` leaves when killed between its two steps. + await symlink(path.join("..", "..", "media", "vid00000001", CHAT), path.join(f.videoDir, CHAT)); + assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), ORIGINAL); + const out = await run(f); + assert.equal(out.status, "already", JSON.stringify(out)); + await assertFinal(f, "after the dangling link"); +}); + +test("a dangling plain link with NO stored form is left alone (the bytes may be on a drive)", async () => { + const f = await fixture(true); + await rm(path.join(f.mediaDir, CHAT)); + const out = await run(f); + assert.equal(out.status === "skipped" && out.reason, "dangling"); + assert.ok((await lstat(path.join(f.videoDir, CHAT))).isSymbolicLink()); +}); + +test("a corrupt stored form beside the plain file is refused; a truncated one never reads as the file", async () => { + const f = await fixture(false); + const good = await encodeStoredBytes(Buffer.from(ORIGINAL)); + await writeFile(path.join(f.videoDir, ZST), good.subarray(0, Math.floor(good.length / 2))); + // The plain file is the truth while it is there. + assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), ORIGINAL); + const out = await run(f); + assert.equal(out.status === "skipped" && out.reason, "stored-corrupt", JSON.stringify(out)); + assert.ok((await lstat(path.join(f.videoDir, CHAT))).isFile(), "the original stays"); + assert.equal((await verifyStoredText(f.videoDir, CHAT)).status, "corrupt"); +}); + +test("a set-aside original of a dead run that is NOT the stored content is kept for a person", async () => { + const f = await fixture(false); + await run(f); + await writeFile(path.join(f.videoDir, CHAT), "NEWER\n"); + await writeFile(path.join(f.videoDir, `.${CHAT}.retire-${DEAD}`), "SOMETHING ELSE\n"); + const out = await run(f); + assert.equal(out.status === "skipped" && out.reason, "retired-kept", JSON.stringify(out)); + assert.equal(await readFile(path.join(f.videoDir, `.${CHAT}.retire-${DEAD}`), "utf8"), "SOMETHING ELSE\n"); +}); + +test("not a declared name: refused", async () => { + const f = await fixture(false); + const out = await compressStoredText(f.videoDir, "transcript.en.vtt"); + assert.equal(out.status === "skipped" && out.reason, "not-declared"); +}); + +// Every entry under `dir`: its kind, size, times and content hash (a link: +// its target and its own times) — what "nothing was touched" compares. +async function tree(dir: string): Promise<string[]> { + const out: string[] = []; + async function walk(d: string): Promise<void> { + for (const e of (await readdir(d).catch(() => [] as string[])).sort()) { + const p = path.join(d, e); + const l = await lstat(p); + const rel = path.relative(ROOT, p); + if (l.isSymbolicLink()) out.push(`${rel} -> ${await readlink(p)} ${l.mtimeMs}`); + else if (l.isDirectory()) { + out.push(`${rel}/`); + await walk(p); + } else { + const h = createHash("sha256").update(await readFile(p)).digest("hex"); + out.push(`${rel} ${l.size} ${l.mtimeMs} ${h}`); + } + } + } + await walk(dir); + return out; +} diff --git a/common/lib/storedText.grep.test.ts b/common/lib/storedText.grep.test.ts @@ -32,7 +32,7 @@ const NAMES = /\bLIVE_CHAT_(?:MEDIA_|STORED_)?FILENAME\b|transcript\.live_chat\. // The read path, the existence checks, the one deleter, and the tier hook // (which moves whichever form it is given and never reads it). const SANCTIONED = - /\b(?:listingHas|storedFormsIn|logicalEntries|readdirLogical|storedTextExists|storedTextForms|storedTextMtimeMs|statStoredText|readStoredText|storedTextLogicalSize|removeStoredText|compressStoredText|tierMediaFile|isStoredTextName)\b/; + /\b(?:listingHas|storedFormsIn|logicalEntries|readdirLogical|storedTextExists|storedTextForms|storedTextMtimeMs|statStoredText|readStoredText|storedTextLogicalSize|removeStoredText|compressStoredText|verifyStoredText|storedNameOf|tierMediaFile|isStoredTextName)\b/; // Where the names are DEFINED or are the rules themselves. const DEFINITIONS = new Set([ diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,13 @@ # Changelog ## [Unreleased] +- **Raw live chats can be stored compressed: `pnpm ops compress-text`.** + - `transcript.live_chat.json` becomes `transcript.live_chat.json.zst` (zstd, about 5 % of the size). Every reader + of the raw chat reads either form, with the same times, so the index sees no change and no chat is fetched again. + - One file at a time, verified by reading it back before the original is removed; a crash at any step leaves a + whole copy and the next run finishes. `dryRun` reports bytes per channel and writes nothing; `verify` decodes + every stored chat; `limit` caps a run. It waits for render mode and goes slower while a live recording runs. + - Deleting a chat (the video page, the auto-caption purge, the clear-transcript fix) removes both forms. - **umtool: the gap mark's border is the deck's accent colour.** - The operator picked variant B. The border is drawn in the deck's accent, the colour of the deck's accent rule and the dots in its source line, at full opacity. The box behind the text is near-black at 90 %, and the text diff --git a/editor/app/api/ops/compress-text/route.test.ts b/editor/app/api/ops/compress-text/route.test.ts @@ -0,0 +1,63 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readdir, rm, stat, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/compress-text/route.test.ts" +// +// The body's shape and the refusals that come before any job, then a dry run +// that answers per channel and writes nothing. Nothing is compressed here. + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "compress-text-route-")); +process.env.WORKER_TOKEN = "test-token"; +process.env.TRANSCRIPTS_DIR = ROOT; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +const { POST } = await import("./route"); +test.after(() => rm(ROOT, { recursive: true, force: true })); + +const videoDir = path.join(ROOT, "channels", "synth", "data", "aaaaaaaaaaa"); +await mkdir(videoDir, { recursive: true }); +await writeFile(path.join(ROOT, "channels", "synth", "config.json"), JSON.stringify({ handling: "youtube" })); +await writeFile(path.join(videoDir, "transcript.live_chat.json"), '{"replayChatItemAction":{}}\n'.repeat(100)); + +async function post(body: Record<string, unknown>) { + const res = await POST( + new Request("http://localhost/api/ops/compress-text", { + method: "POST", + headers: { authorization: "Bearer test-token", "content-type": "application/json" }, + body: JSON.stringify(body), + }), + ); + return { status: res.status, json: (await res.json()) as Record<string, unknown> }; +} + +test("refusals before any job", async () => { + const cases: [Record<string, unknown>, RegExp][] = [ + [{ force: true }, /unknown key\(s\): force/], + [{ slugs: ["../x"] }, /not a valid channel slug/], + [{ slugs: ["nope"], dryRun: true }, /Channel\(s\) not found: nope/], + [{ kinds: ["captions"] }, /"kinds" must be a list of: live-chat/], + [{ limit: 0 }, /limit/], + [{ limit: 5 }, /"limit" is per channel: name exactly one in "slugs"/], + [{ dryRun: true, verify: true }, /two different runs/], + ]; + for (const [body, re] of cases) { + const r = await post(body); + assert.equal(r.status, 400, JSON.stringify(body)); + assert.match(String(r.json.error), re, JSON.stringify(body)); + } +}); + +test("a dry run answers per channel and writes nothing", async () => { + const before = (await stat(path.join(videoDir, "transcript.live_chat.json"))).mtimeMs; + const r = await post({ dryRun: true, kinds: ["live-chat"] }); + assert.equal(r.status, 200, JSON.stringify(r.json)); + const result = r.json.result as { channels: { slug: string; plainFiles: number; plainBytes: number }[] }; + const synth = result.channels.find((c) => c.slug === "synth"); + assert.equal(synth?.plainFiles, 1); + assert.equal(synth?.plainBytes, '{"replayChatItemAction":{}}\n'.length * 100); + assert.deepEqual(await readdir(videoDir), ["transcript.live_chat.json"]); + assert.equal((await stat(path.join(videoDir, "transcript.live_chat.json"))).mtimeMs, before); +}); diff --git a/editor/app/api/ops/compress-text/route.ts b/editor/app/api/ops/compress-text/route.ts @@ -0,0 +1,52 @@ +import { NextResponse } from "next/server"; +import { compressTextAction } from "../../../storage/compressTextActions"; +import { OpsInputError, ops, opsFail, optBool, optPositiveInt, reqSlugs, type OpsBody } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slugs?, kinds?, dryRun?, limit?, verify? } +// dryRun -> { ok: true, dryRun: true, result: { channels: [{ slug, plainFiles, +// plainBytes, storedFiles, storedBytes, storedLogicalBytes, +// estimateAfterBytes, free }], lines } } +// else -> { ok: true, dryRun: false, verify, jobs: [{ slug, jobId }], jobIds, +// jobId (one job only), skipped: [{ slug, reason }] } +// +// The raw live-chat replays put into their stored form, `transcript.live_chat.json` +// → `transcript.live_chat.json.zst` (lib/storedText.ts; lane text-compress): +// one file at a time — written beside, fsynced, read back and hashed against +// the original, the original then removed through removeMediaFile. A crash at +// any step leaves a whole copy and the next run finishes. Paced (render mode +// waits it; slower while a live recording runs); a file written in the last +// 10 minutes, with a `.part` beside it, whose video is recording or busy, or +// on a drive that does not answer, is left alone and counted. Both forms with +// different content are refused and both kept. `dryRun` writes nothing; +// `verify` decodes every stored file and writes nothing; `limit` counts files +// compressed by the job, and takes exactly one channel in `slugs`. One job per +// channel with work, on the machine-wide `compress-text` queue (one file at a +// time); a re-run continues. +// `kinds`: what to compress. Only the raw live chat is a stored name today. +function optKinds(body: OpsBody): void { + if (body.kinds === undefined) return; + if (!Array.isArray(body.kinds) || body.kinds.length === 0 || body.kinds.some((k) => k !== "live-chat")) { + throw new OpsInputError('"kinds" must be a list of: live-chat'); + } +} + +export async function POST(request: Request) { + return ops(request, ["slugs", "kinds", "dryRun", "limit", "verify"], async (body) => { + optKinds(body); + const dryRun = optBool(body, "dryRun") ?? false; + const verify = optBool(body, "verify") ?? false; + if (dryRun && verify) return opsFail('"dryRun" and "verify" are two different runs: ask one'); + const limit = optPositiveInt(body, "limit"); + const result = await compressTextAction({ + ...(body.slugs !== undefined ? { slugs: reqSlugs(body, "slugs") } : {}), + dryRun, + verify, + ...(limit !== undefined ? { limit } : {}), + }); + if (!result.ok) return opsFail(result.error); + if (result.dryRun) return NextResponse.json(result); + return NextResponse.json({ ...result, ...(result.jobIds.length === 1 ? { jobId: result.jobIds[0] } : {}) }); + }); +} diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts @@ -19,6 +19,7 @@ import type { AudioFormat } from "yt-dlp-transcript-common/lib/channelConfig"; import { isSourceVideoQuality } from "yt-dlp-transcript-common/ytdlp/downloadFormat"; import { isPersistReplacePolicy } from "yt-dlp-transcript-common/controller/persistVideos"; import { compactChannelVideosAction } from "../saved-videos/compactActions"; +import { compressTextJobAction } from "../storage/compressTextActions"; import { downloadAction, downloadMissingAction, @@ -625,6 +626,16 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { }, // The same list, mode and overrides: a replay (a person's Retry) resumes at // the first chunk not encoded and skips what is already compacted. + // The same channel, limit and mode: a replay (a person's Retry) re-walks + // and continues — every file already stored is skipped. + "compress-text": (spec) => { + const { p } = params(spec); + const limit = num(p.limit); + return compressTextJobAction(spec.slug, { + ...(limit !== undefined ? { limit } : {}), + ...(p.verify === true ? { verify: true } : {}), + }); + }, "compact-saved-videos": (spec) => { const { p } = params(spec); return compactChannelVideosAction(spec.slug, strings(p.ids) ?? [], { diff --git a/editor/app/storage/compressTextActions.ts b/editor/app/storage/compressTextActions.ts @@ -0,0 +1,153 @@ +"use server"; + +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { listChannelSlugs } from "yt-dlp-transcript-common/controller/channels"; +import { + COMPRESS_RATE_BYTES, + COMPRESS_RATE_RECORDING_BYTES, + compressText, + type CompressTextResult, +} from "yt-dlp-transcript-common/controller/compressText"; +import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; +import { + runManagedFunction, + type StreamActionResult, +} from "yt-dlp-transcript-common/jobs/streamCommand"; +import { waitWhileRenderHeld } from "yt-dlp-transcript-common/lib/renderHold"; + +// COMPRESS TEXT: the `compress-text` job, as `pnpm ops compress-text` posts it +// (`/api/ops/compress-text`). The work and its rules are +// common/controller/compressText.ts and lib/storedText-write-server.ts. +// +// ONE QUEUE MACHINE-WIDE, ONE JOB PER CHANNEL: one file at a time across every +// channel. Per channel because the job is a media writer of THAT channel — +// the media guard asks it before the job starts, and a move of the channel's +// media refuses while it runs (`channelMediaWriters` finds it by its slug). +// So `limit` is per job, and is taken only with one channel named. Never +// resumed by the boot pass — it removes originals; the job's Retry (a person) +// re-runs it, and a re-run continues. +const COMPRESS_QUEUE = "compress-text"; + +export type CompressTextActionResult = + | { ok: false; error: string } + | { ok: true; dryRun: true; result: CompressTextResult } + | { + ok: true; + dryRun: false; + verify: boolean; + jobs: { slug: string; jobId: string }[]; + jobIds: string[]; + skipped: { slug: string; reason: string }[]; + }; + +// A job running for this video: one of its own, or a batch with a task on it. +// The compress job itself is not counted. +function videoBusy(slug: string, id: string, self: string): boolean { + return getRegistry() + .list() + .some( + (j) => + j.id !== self && + j.status === "running" && + j.channelSlug === slug && + (j.videoId === id || (j.tasks ?? []).some((t) => t.id === id)), + ); +} + +// A live recording in progress anywhere: the reads go slower. +function recordingRunning(): boolean { + return getRegistry() + .list() + .some((j) => j.kind === "record-live" && j.status === "running"); +} + +const sleep = (ms: number, signal?: AbortSignal) => + new Promise<void>((resolve) => { + const t = setTimeout(resolve, ms); + signal?.addEventListener( + "abort", + () => { + clearTimeout(t); + resolve(); + }, + { once: true }, + ); + }); + +export async function compressTextJobAction( + slug: string, + opts: { limit?: number; verify?: boolean } = {}, +): Promise<StreamActionResult> { + const paths = getPaths(); + return runManagedFunction({ + kind: "compress-text", + queueKey: COMPRESS_QUEUE, + paths, + channelSlug: slug, + spec: { + kind: "compress-text", + slug, + params: { + ...(opts.limit !== undefined ? { limit: opts.limit } : {}), + ...(opts.verify ? { verify: true } : {}), + }, + }, + fn: async (onLog, signal, _progress, ctx) => { + const result = await compressText({ + paths, + slugs: [slug], + ...(opts.limit !== undefined ? { limit: opts.limit } : {}), + ...(opts.verify ? { verify: true } : {}), + onLog, + signal, + drainSignal: ctx.drainSignal, + isBusy: (s, id) => videoBusy(s, id, ctx.jobId), + rate: () => (recordingRunning() ? COMPRESS_RATE_RECORDING_BYTES : COMPRESS_RATE_BYTES), + waitForRender: () => + waitWhileRenderHeld({ sleep, onLog: (l) => onLog(`${l}\n`), what: "compress-text", signal }), + sleep, + }); + const failed = result.channels.reduce((a, c) => a + (c.failed?.length ?? 0) + (c.problems?.length ?? 0), 0); + if (result.stopped === "cancelled") throw new Error("Stopped: cancelled. A re-run continues."); + if (failed > 0) throw new Error(`${failed} file(s) failed or did not verify — see the lines above.`); + }, + }); +} + +// `slugs` (default: every channel). A dry run answers with the plan and +// writes nothing; a real run (or a check) starts one job per channel that has +// a raw chat to compress (or a stored one to check). +export async function compressTextAction(input: { + slugs?: string[]; + dryRun?: boolean; + verify?: boolean; + limit?: number; +}): Promise<CompressTextActionResult> { + const paths = getPaths(); + const all = (await listChannelSlugs(paths)).sort(); + const missing = (input.slugs ?? []).filter((s) => !all.includes(s)); + if (missing.length) return { ok: false, error: `Channel(s) not found: ${missing.join(", ")}` }; + if (input.limit !== undefined && input.slugs?.length !== 1) { + return { ok: false, error: '"limit" is per channel: name exactly one in "slugs"' }; + } + const slugs = input.slugs ?? all; + const plan = await compressText({ paths, slugs, dryRun: true, onLog: () => {} }); + if (input.dryRun) return { ok: true, dryRun: true, result: plan }; + const jobs: { slug: string; jobId: string }[] = []; + const skipped: { slug: string; reason: string }[] = []; + for (const line of plan.channels) { + if (line.refused) { + skipped.push({ slug: line.slug, reason: line.refused }); + continue; + } + const work = input.verify ? line.storedFiles : line.plainFiles; + if (work === 0) continue; + const r = await compressTextJobAction(line.slug, { + ...(input.limit !== undefined ? { limit: input.limit } : {}), + ...(input.verify ? { verify: true } : {}), + }); + if (r.ok) jobs.push({ slug: line.slug, jobId: r.jobId }); + else skipped.push({ slug: line.slug, reason: r.error }); + } + return { ok: true, dryRun: false, verify: input.verify === true, jobs, jobIds: jobs.map((j) => j.jobId), skipped }; +} diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -558,6 +558,9 @@ const ACTIONS = [ "compaction-markers", // The failed encodes kept for a re-verify, and clearing one ({} | {clear: {slug, id}}). "kept-failed-encodes", + // The raw live chats stored zstd-compressed, one file at a time, verified + // before each original goes ({slugs?, kinds?, dryRun?, limit? (one slug), verify?}). + "compress-text", // Write transcript.cues.json from each video's raw transcript ({slug, ids?, // force?}) — what a reader with no index build wants. "build-cues", @@ -2291,6 +2294,26 @@ export function usage() { ' while its compaction runs). compact-saved-videos "reverify": true re-checks', " one without encoding.", "", + 'compress-text stores the raw live-chat replays compressed (zstd, level 9):', + ' transcript.live_chat.json becomes transcript.live_chat.json.zst, read', + " back by every reader as the same file, with the same times (the index", + ' sees no change): {"slugs"?: [...], "kinds"?: ["live-chat"], "dryRun"?,', + ' "limit"?, "verify"?}. One file at a time: written beside the original,', + " fsynced, read back and hashed against it, and only then the original", + " removed; a crash at any step leaves a whole copy, and the next run", + " finishes it. Left alone and counted: a file written in the last 10", + " minutes, one with a .part beside it, a video recording or with a job", + " running, a drive that does not answer, a channel whose media is moving.", + " Both forms present with different content are refused and both kept.", + ' "dryRun": true answers per channel the raw chats, their bytes, the', + " stored ones, the estimate after (about 5 %, an estimate) and the free", + ' space, and writes nothing; "verify": true decodes every stored file in', + ' full and writes nothing; "limit" counts files compressed and takes', + ' exactly one channel in "slugs". One job per channel with work, on the', + " machine-wide compress-text queue (one file at a time), waiting while", + " render mode holds the machine and slower while a live recording runs;", + " never resumed at boot (it removes originals) -- a re-run continues.", + "", 'compaction-markers lists the "being compacted" markers (.compacting.json),', ' each live or stale and why: {}. {"clear": {"slug", "id"}} removes a stale', " one; a live one is refused (cancel its job). Stale ones are also swept at",