// STORED TEXT ON DISK — THE READ PATH (lib/storedText.ts has the names and // the rules). Every reader of a declared name goes through here and accepts // either form: the plain file when it is present (the truth), else the stored // `.zst`, decompressed. A reader that opens the plain name directly sees // a compressed file as ABSENT — which, for the live chat, makes the app fetch // it again — and storedText.grep.test.ts fails any such read added outside // this module. // // THE FORMAT: one zstd frame, the content size in its header (the logical size // is a few header bytes away) and the content checksum on (a corrupt file // throws instead of returning wrong text). Node's zstd does NOT throw on a // TRUNCATED frame — it returns what it decoded — so every read here also // requires the decoded length to equal the header's content size. // // SERVER-ONLY. import path from "node:path"; import { lstat, open, readdir, readFile, stat } from "node:fs/promises"; import type { Stats } from "node:fs"; import zlib from "node:zlib"; import type { Transform } from "node:stream"; import { isStoredTextName, logicalEntries, storedNameOf, type StoredForms, } from "./storedText"; // Node's zstd, typed here: the workspace's @types/node predates it. export type ZstdOptions = { pledgedSrcSize?: number; maxOutputLength?: number; params?: Record; }; type ZstdZlib = { zstdDecompress?: (buf: Buffer, opts: ZstdOptions, cb: (err: Error | null, out: Buffer) => void) => void; createZstdCompress?: (opts: ZstdOptions) => Transform; createZstdDecompress?: (opts?: ZstdOptions) => Transform; constants: Record; }; const z = zlib as unknown as ZstdZlib; export function createStoredTextCompressor(size: number): Transform { assertZstdAvailable(); return z.createZstdCompress!(storedTextCompressOptions(size)); } export function createStoredTextDecompressor(): Transform { assertZstdAvailable(); return z.createZstdDecompress!(); } // Node's zstd: `zlib.zstdCompress` and friends from Node 22.15.0 (23.8.0). // Asked at first use, not at import: a process on an older Node that never // meets a stored file keeps working, and one that does gets this sentence. export function assertZstdAvailable(): void { if ( typeof z.zstdDecompress !== "function" || typeof z.createZstdCompress !== "function" || typeof z.createZstdDecompress !== "function" ) { throw new StoredTextUnsupportedError( `stored text needs node:zlib zstd — Node >= 22.15 (this is ${process.version})`, ); } } // This Node cannot read a stored file at all (no zstd). Every process asks at // boot (lib/zstdSupport.mjs) and refuses to start; this is the backstop. export class StoredTextUnsupportedError extends Error { constructor(message: string) { super(message); this.name = "StoredTextUnsupportedError"; } } // A STORED FILE THAT IS THERE AND CANNOT BE READ — a frame that does not // decode, or a Node without zstd — is an ERROR, never "no text" (REVIEW-1 F3, // captions lane): a reader that skips it as it skips a missing file would let // the index write a record with no cues over a readable one, or a lane read // the video as needing a transcript. Readers that tolerate a missing or // malformed track RETHROW these. export function isStoredTextReadError(err: unknown): boolean { return err instanceof StoredTextCorruptError || err instanceof StoredTextUnsupportedError; } export const STORED_TEXT_LEVEL = 9; // The compressor's options for a source of `size` bytes: level 9, checksum on, // the size pledged so it lands in the frame header. export function storedTextCompressOptions(size: number): ZstdOptions { assertZstdAvailable(); const c = z.constants; return { pledgedSrcSize: size, params: { [c.ZSTD_c_compressionLevel]: STORED_TEXT_LEVEL, [c.ZSTD_c_checksumFlag]: 1, [c.ZSTD_c_contentSizeFlag]: 1, }, }; } const ZSTD_MAGIC = 0xfd2fb528; // The content size a zstd frame header declares, or null when the bytes are // not a frame header that carries one. `head` needs at most 18 bytes. export function frameContentSize(head: Uint8Array): number | null { if (head.length < 5) return null; const dv = new DataView(head.buffer, head.byteOffset, head.byteLength); if (dv.getUint32(0, true) !== ZSTD_MAGIC) return null; const fhd = head[4]; const fcsFlag = fhd >> 6; const singleSegment = (fhd >> 5) & 1; const dictFlag = fhd & 3; if (fcsFlag === 0 && !singleSegment) return null; // size not recorded let off = 5 + (singleSegment ? 0 : 1) + [0, 1, 2, 4][dictFlag]; const fcsBytes = fcsFlag === 0 ? 1 : [1, 2, 4, 8][fcsFlag]; if (head.length < off + fcsBytes) return null; switch (fcsBytes) { case 1: return head[off]; case 2: return dv.getUint16(off, true) + 256; case 4: return dv.getUint32(off, true); default: { const lo = dv.getUint32(off, true); const hi = dv.getUint32(off + 4, true); const n = hi * 2 ** 32 + lo; return Number.isSafeInteger(n) ? n : null; } } } // One whole buffer as a stored frame (the compressor streams; this is for a // small file and for tests' fixtures). export async function encodeStoredBytes(bytes: Buffer): Promise { const c = createStoredTextCompressor(bytes.length); const out: Buffer[] = []; c.on("data", (d: Buffer) => out.push(d)); const done = new Promise((resolve, reject) => { c.on("end", () => resolve()); c.on("error", reject); }); c.end(bytes); await done; return Buffer.concat(out); } export class StoredTextCorruptError extends Error { constructor(file: string, why: string) { super(`${file}: not a whole stored-text frame (${why})`); this.name = "StoredTextCorruptError"; } } // A stored file's bytes, decoded and checked: the frame's checksum (zstd // throws), and the decoded length against the header's content size (a // truncated frame decodes short without an error). export async function decodeStoredBytes(bytes: Buffer, label = "stored text"): Promise { assertZstdAvailable(); const want = frameContentSize(bytes.subarray(0, 18)); if (want === null) throw new StoredTextCorruptError(label, "no content size in the frame header"); let out: Buffer; try { out = await new Promise((resolve, reject) => z.zstdDecompress!(bytes, { maxOutputLength: Math.max(1, want + 1) }, (err, res) => err ? reject(err) : resolve(res), ), ); } catch (err) { throw new StoredTextCorruptError(label, (err as Error).message); } if (out.length !== want) { throw new StoredTextCorruptError(label, `decoded ${out.length} bytes, header says ${want}`); } return out; } function isEnoent(err: unknown): boolean { const code = (err as NodeJS.ErrnoException | null)?.code; return code === "ENOENT" || code === "ENOTDIR"; } function enoent(dir: string, name: string): NodeJS.ErrnoException { const err = new Error(`ENOENT: no such file, '${path.join(dir, name)}' (nor its stored form)`) as NodeJS.ErrnoException; err.code = "ENOENT"; return err; } // THE READ: the plain file's bytes when it opens; else (a declared name) the // stored form, decoded. A plain name that is a dangling link (an interrupted // removal, a drive not mounted) does not open, so the stored form is read; // when neither opens, ENOENT. export async function readStoredText(dir: string, name: string): Promise; export async function readStoredText(dir: string, name: string, encoding: "utf8"): Promise; export async function readStoredText( dir: string, name: string, encoding?: "utf8", ): Promise { try { return encoding ? await readFile(path.join(dir, name), encoding) : await readFile(path.join(dir, name)); } catch (err) { if (!isEnoent(err) || !isStoredTextName(name)) throw err; } const storedPath = path.join(dir, storedNameOf(name)); let bytes: Buffer; try { bytes = await readFile(storedPath); } catch (err) { if (isEnoent(err)) throw enoent(dir, name); throw err; } const out = await decodeStoredBytes(bytes, storedPath); return encoding ? out.toString(encoding) : out; } // THE HEAD of a declared file: its first `bytes` bytes as the plain file has // them — read from the plain file when it opens, else DECODED from the stored // form (the first bytes of a zstd frame are not text: a sniff of them would // answer wrong, not absent — the caption provenance sniff, the word-timing // sniff). Only the head is decoded; the frame's checksum is checked by a whole // read, not here. ENOENT when neither form opens. export async function readStoredTextHead(dir: string, name: string, bytes: number): Promise { try { const fh = await open(path.join(dir, name), "r"); try { const buf = Buffer.alloc(bytes); const { bytesRead } = await fh.read(buf, 0, bytes, 0); return buf.subarray(0, bytesRead); } finally { await fh.close(); } } catch (err) { if (!isEnoent(err) || !isStoredTextName(name)) throw err; } const storedPath = path.join(dir, storedNameOf(name)); let fh; try { fh = await open(storedPath, "r"); } catch (err) { if (isEnoent(err)) throw enoent(dir, name); throw err; } const src = fh.createReadStream(); const dec = createStoredTextDecompressor(); const out: Buffer[] = []; let n = 0; try { await new Promise((resolve, reject) => { const finish = () => resolve(); dec.on("data", (chunk: Buffer) => { if (n >= bytes) return; out.push(chunk); n += chunk.length; if (n >= bytes) { src.unpipe(dec); src.destroy(); dec.destroy(); finish(); } }); dec.on("end", finish); dec.on("error", (err) => reject(new StoredTextCorruptError(storedPath, err.message))); src.on("error", reject); src.pipe(dec); }); } finally { src.destroy(); await fh.close().catch(() => {}); } return Buffer.concat(out).subarray(0, bytes); } export type StoredTextStat = { // Which form answered. form: "plain" | "zst"; // The path that was stat'ed. file: string; stats: Stats; }; // THE STAT a freshness or change check asks: of the plain name when it is // there, else of the stored form — which carries the plain file's times // exactly (the compressor sets them, numeric seconds), so the answer's // `mtimeMs` is the SAME number either way. `link: true` is `lstat` (a tiered // name is asked on the corpus disk, never on the media drive); otherwise // `stat`, where a dangling plain link falls through to the stored form. export async function statStoredText( dir: string, name: string, opts: { link?: boolean } = {}, ): Promise { const ask = opts.link ? lstat : stat; const plain = path.join(dir, name); try { return { form: "plain", file: plain, stats: await ask(plain) }; } catch (err) { if (!isEnoent(err) || !isStoredTextName(name)) throw err; } const stored = path.join(dir, storedNameOf(name)); try { return { form: "zst", file: stored, stats: await ask(stored) }; } catch (err) { if (isEnoent(err)) throw enoent(dir, name); throw err; } } // The `mtimeMs` of `statStoredText`, or null when neither form answers. export async function storedTextMtimeMs( dir: string, name: string, opts: { link?: boolean } = {}, ): Promise { try { return (await statStoredText(dir, name, opts)).stats.mtimeMs; } catch { return null; } } // Is `name` here in either form? An `lstat` — what a listing would say: a // dangling link is an entry (a drive that is not mounted is not an empty dir). export async function storedTextExists(dir: string, name: string): Promise { try { await statStoredText(dir, name, { link: true }); return true; } catch { return false; } } // Which forms are present, by `lstat` of each. export async function storedTextForms(dir: string, name: string): Promise { const here = (n: string) => lstat(path.join(dir, n)).then(() => true, () => false); const plain = await here(name); const zst = isStoredTextName(name) ? await here(storedNameOf(name)) : false; if (plain && zst) return "both"; if (plain) return "plain"; if (zst) return "zst"; return null; } // The LOGICAL size: the plain file's, or the content size the stored frame's // header declares (18 bytes read, nothing decompressed). Follows links. export async function storedTextLogicalSize(dir: string, name: string): Promise { const s = await statStoredText(dir, name); if (s.form === "plain") return s.stats.size; const fh = await open(s.file, "r"); try { const head = Buffer.alloc(18); const { bytesRead } = await fh.read(head, 0, 18, 0); const n = frameContentSize(head.subarray(0, bytesRead)); if (n === null) throw new StoredTextCorruptError(s.file, "no content size in the frame header"); return n; } finally { await fh.close(); } } // A MATCHING listing of a dir: readdir, each declared `X.zst` reported as `X`. // A missing dir lists nothing. export async function readdirLogical(dir: string): Promise { return logicalEntries(await readdir(dir).catch(() => [] as string[])); }