// The phrase finder's cue-text cache (release 34): what a phrase scan needs of // each video — its cue texts, their times, and five fields of the record — // kept per channel in ONE file read front to back, so a second search reads // one file per channel instead of thousands of cue files with their // descriptions and metadata. // // //.ndjson // one line per video, in video-id order: {"id": "", "r": record | null} // //.index.json // { version, videos: { "": [mtimeMs, size] } } // // A video's line is used only while its transcript.cues.json has the same // modification time and size as the index says; anything else is read again // (an unreadable file is remembered as null, so it is not re-parsed every // search). Lines are streamed, one at a time, so a channel of eight thousand // videos costs one line's memory, not the channel's. When anything changed the // channel's file is written again as the scan goes (a temporary name, renamed at // the end); when nothing did, nothing is written. // // It never writes under the channels directory: the cache dir is the caller's // (umtool's CACHE_DIR/phrase-text). Delete it at any time; the next search // rebuilds it. import { createHash } from "node:crypto"; import { createReadStream, createWriteStream } from "node:fs"; import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { createInterface } from "node:readline"; import { tmpPathFor } from "../atomicFile.mjs"; export const CACHE_VERSION = 3; const squash = (t) => String(t ?? "").replace(/\s+/g, " ").trim(); /** * What a scan keeps of a parsed transcript.cues.json: `uploadDate`, * `duration`, `title`, `platform`, `source` as they are, and the cues as three * columns — `j` the squashed texts joined with a newline (a squashed text has * none), `a` the starts, `b` the ends (null where a cue has none) — or all * three null when the record has no cue list. */ export function compactRecord(d) { const cues = Array.isArray(d?.cues) ? d.cues : null; return { uploadDate: d?.uploadDate ?? null, duration: d?.duration ?? null, title: d?.title ?? null, platform: d?.platform ?? null, source: d?.source ?? null, j: cues ? cues.map((c) => squash(c?.text)).join("\n") : null, a: cues ? cues.map((c) => c?.start ?? null) : null, b: cues ? cues.map((c) => c?.end ?? null) : null, }; } /** A compact record's cue texts (its `j`, split again). */ export const textsOf = (r) => (r?.a?.length ? String(r.j ?? "").split("\n") : []); const cueFile = (channelsDir, slug, id) => path.join(channelsDir, slug, "data", id, "transcript.cues.json"); async function parseFile(file) { try { return JSON.parse(await readFile(file, "utf8")); } catch { return null; } } /** One video's compact record straight from its cue file, or null when it is missing or parses to nothing. */ export async function readCompact(channelsDir, slug, id) { const d = await parseFile(cueFile(channelsDir, slug, id)); return d ? compactRecord(d) : null; } /** The directory a channels dir's cache files live in. */ export function cacheRoot(cacheDir, channelsDir) { const h = createHash("sha1").update(path.resolve(channelsDir)).digest("hex").slice(0, 12); return path.join(cacheDir, h); } async function statAll(files, n) { const out = new Array(files.length).fill(null); let next = 0; const worker = async () => { while (next < files.length) { const k = next++; out[k] = await stat(files[k]).catch(() => null); } }; await Promise.all(Array.from({ length: Math.min(n, files.length) }, worker)); return out; } /** * A channel's cache, for one pass over `ids` (sorted, as the scan visits * them). `read(id)` → `{r, line}` (call it in id order, as many in flight as * you like): `r` the record (null: not a transcript), `line` what to `keep`; * `keep(id, line)` in id order; `close()` writes the channel's file when * anything changed. `changed` says whether it will. */ export async function openChannelCache(cacheDir, channelsDir, slug, ids) { const root = cacheRoot(cacheDir, channelsDir); const base = path.join(root, encodeURIComponent(slug)); const dataFile = `${base}.ndjson`; const indexFile = `${base}.index.json`; let index = {}; try { const doc = JSON.parse(await readFile(indexFile, "utf8")); if (doc?.version === CACHE_VERSION && doc.videos && typeof doc.videos === "object") index = doc.videos; } catch { /* none yet, or unreadable: rebuilt */ } const hasData = await stat(dataFile).then((s) => s.isFile(), () => false); if (!hasData) index = {}; const stats = await statAll(ids.map((id) => cueFile(channelsDir, slug, id)), 32); const statOf = new Map(ids.map((id, k) => [id, stats[k]])); const fresh = new Set(); for (const [k, id] of ids.entries()) { const st = stats[k]; const e = index[id]; if (st && Array.isArray(e) && e[0] === st.mtimeMs && e[1] === st.size) fresh.add(id); } const changed = fresh.size !== ids.filter((id) => statOf.get(id)).length || fresh.size !== Object.keys(index).length; // The old file, a line at a time; a line is taken only in id order. let lines = null; let rl = null; if (fresh.size) { rl = createInterface({ input: createReadStream(dataFile, { encoding: "utf8" }), crlfDelay: Infinity }); lines = rl[Symbol.asyncIterator](); } let chain = Promise.resolve(); // A line the index promised and the file did not hold: the file is rebuilt next time. let missed = false; const take = async (id) => { for (;;) { const { value, done } = await lines.next(); if (done) return null; let doc; try { doc = JSON.parse(value); } catch { continue; } if (doc?.id === id) return { r: doc.r ?? null, line: value }; } }; let out = null; let tmp = null; const nextIndex = {}; if (changed) { await mkdir(root, { recursive: true }); tmp = tmpPathFor(dataFile); out = createWriteStream(tmp, { encoding: "utf8" }); } return { changed, read(id) { const st = statOf.get(id); if (!st) return Promise.resolve({ r: null, line: null }); if (fresh.has(id)) { const p = chain.then(() => take(id)); chain = p.then( () => {}, () => {}, ); return p.then(async (got) => { if (got) return got; missed = true; return this.readFile(id); }); } return this.readFile(id); }, async readFile(id) { const d = await parseFile(cueFile(channelsDir, slug, id)); const r = d ? compactRecord(d) : null; return { r, line: JSON.stringify({ id, r }) }; }, async keep(id, line) { if (!out || line === null) return; const st = statOf.get(id); nextIndex[id] = [st.mtimeMs, st.size]; if (!out.write(line + "\n")) await new Promise((resolve) => out.once("drain", resolve)); }, async close() { rl?.close(); if (!out) { if (missed) await rm(indexFile, { force: true }); return false; } await new Promise((resolve, reject) => out.end((e) => (e ? reject(e) : resolve()))); await rename(tmp, dataFile); const itmp = tmpPathFor(indexFile); await writeFile(itmp, JSON.stringify({ version: CACHE_VERSION, slug, videos: nextIndex }), "utf8"); await rename(itmp, indexFile); return true; }, async abort() { rl?.close(); if (out) { out.destroy(); await rm(tmp, { force: true }); } }, }; }