import { existsSync } from "node:fs"; import { readdir, stat } from "node:fs/promises"; import path from "node:path"; import { caseChannels } from "yt-dlp-transcript-common/controller/caseCorpus"; import { readDefinition, readStages } from "yt-dlp-transcript-common/lib/research/caseStore-server"; import type { Decision } from "@/lib/decisions"; import { CHANNELS_DIR, REPORTS_ROOT } from "@/lib/paths.mjs"; import { caseDir, isCaseId, readCase, researchDir } from "@/lib/research/cases.mjs"; import { researchCasePipelineHref } from "@/lib/research/hrefs"; import { corpusPaths } from "@/lib/research/pipeline"; import { caseCuesDecision, lastScanOf, newSince } from "./caseCues.mjs"; // --------------------------------------------------------------------------- // New transcripts on a live case, for the Inbox (lib/inbox/caseCues.mjs says // what counts): every research case with a pipeline, not done, scanned at // least once; its scope's channels (common's caseChannels) and, per video, // when its cues were last written -- // // the transcript index's `mtimes` (key [channel, video] -> transcriptMs / // subsMs, build-index's own record: channelSignature.ts reads the same) when // the index is there -- a key range per channel, no file opened; // else (a fixture, a corpus never indexed) the video directories' cue files. // // Kept per case and scan for ten minutes (new transcripts land in batches; the // rail asks every ten seconds). A case that cannot be read adds nothing; this // never throws. SERVER ONLY. // --------------------------------------------------------------------------- const MEMO_MS = 10 * 60_000; type Row = { channel: string; id: string; at: number }; type Memo = Map; const g = globalThis as typeof globalThis & { __umtoolCaseCuesMemo?: Memo }; const memo: Memo = (g.__umtoolCaseCuesMemo ??= new Map()); /** A cue file's name: the transcript and its sidecars, a caption track. */ const CUE_FILE = /^(transcript\..+|.+\.vtt)$/; /** Per video of `slugs`, when its cues were last written (ms), from an index already open. */ type MtimesDb = { getRange(o: { start: unknown; end: unknown }): Iterable<{ key: unknown; value: { transcriptMs?: number | null; subsMs?: number | null } }> }; function fromIndex(mtimes: MtimesDb, slugs: string[]): Row[] { const out: Row[] = []; for (const slug of slugs) { for (const { key, value } of mtimes.getRange({ start: [slug], end: [slug, "\uffff"] })) { const k = key as [string, string]; if (k[0] !== slug) break; const at = Math.max(value?.transcriptMs ?? 0, value?.subsMs ?? 0); if (at > 0) out.push({ channel: slug, id: k[1], at }); } } return out; } /** The same from the files: each video directory's newest cue file. */ async function fromFiles(channelsDir: string, slugs: string[]): Promise { const out: Row[] = []; for (const slug of slugs) { const data = path.join(/* turbopackIgnore: true */ channelsDir, slug, "data"); const ids = await readdir(/* turbopackIgnore: true */ data, { withFileTypes: true }).catch(() => []); for (const d of ids) { if (!d.isDirectory() || d.name.startsWith(".")) continue; const names = await readdir(/* turbopackIgnore: true */ path.join(data, d.name)).catch(() => [] as string[]); let at = 0; for (const n of names) { if (!CUE_FILE.test(n)) continue; const s = await stat(/* turbopackIgnore: true */ path.join(data, d.name, n)).catch(() => null); if (s && s.mtimeMs > at) at = s.mtimeMs; } if (at > 0) out.push({ channel: slug, id: d.name, at }); } } return out; } async function caseRow(id: string, index: () => Promise): Promise { const dir = caseDir(REPORTS_ROOT, id); const def = await readDefinition(dir, id); if (!def || def.status === "done") return null; const since = lastScanOf(await readStages(dir)); if (since === null) return null; const key = `${id}:${since}`; const hit = memo.get(key); if (hit && Date.now() - hit.at < MEMO_MS) return hit.value; const paths = corpusPaths(); const { slugs } = await caseChannels(paths, def); const mtimes = await index(); const rows = mtimes ? fromIndex(mtimes, slugs) : await fromFiles(CHANNELS_DIR, slugs); const title = (await readCase(REPORTS_ROOT, id).catch(() => null))?.title ?? id; const value = caseCuesDecision({ id, title, since, fresh: newSince(rows, since), href: researchCasePipelineHref(id) }) as Decision | null; for (const k of memo.keys()) if (k.startsWith(`${id}:`)) memo.delete(k); memo.set(key, { at: Date.now(), value }); return value; } /** Every live case's "N new transcripts since the last scan". Never throws. */ export async function caseCuesDecisions(): Promise { try { const names = await readdir(/* turbopackIgnore: true */ researchDir(REPORTS_ROOT), { withFileTypes: true }).catch(() => []); const ids = names.filter((d) => d.isDirectory() && isCaseId(d.name)).map((d) => d.name); if (!ids.length) return []; // The index opened ONCE for every case (lmdb-js shares an environment by path: a close per case could // end another case's range read), and the cases read one after another. // Opened only when a case is not answered from the memo. const lmdbPath = corpusPaths().lmdbPath; type Env = { openDB: (o: object) => unknown; close: () => Promise }; let root = null as Env | null; let opened: Promise | null = null; const index = () => (opened ??= (async () => { if (!existsSync(/* turbopackIgnore: true */ lmdbPath)) return null; try { const { open } = await import("lmdb"); root = open({ path: lmdbPath, readOnly: true, maxDbs: 14 }) as unknown as Env; return root.openDB({ name: "mtimes", encoding: "msgpack" }) as MtimesDb; } catch { return null; } })()); try { const out: Decision[] = []; for (const id of ids) { const r = await caseRow(id, index).catch(() => null); if (r) out.push(r); } return out; } finally { await root?.close().catch(() => {}); } } catch { return []; } }