// THE MIRROR SCAN (release 31, lane D): a mirror channel (config `mirror.of`) // paired with the creator's channels by lib/mirrors/match.ts, the result in // `transcripts/mirrors/.json` (lib/mirrors/scanFile.ts) — a `mirror-scan` // job, `pnpm ops mirror-scan {slug, dryRun?}`, the channel page's Mirror stage. // // CHEAP: no media, no network. Each channel's records come from the LMDB index // (the `mtimes` range of the channel gives each data dir's index key, `sums` its // summary: title, upload date, duration, live, recorded date), and only a dir // the index has not seen is read off disk (its metadata.info.json through // summarize(), as the index would). A record's recorded date is the index's, // else the channel's title rule applied here — so a scan is right before the // index is rebuilt for a new rule. The creator's gone state is THE gone reading // (lib/sourceGone-server.ts sourceGoneState: availability.json reconciled with // download-outcome.json), read only for videos dated where a match or the // removed list can reach (the mirror's window widened by the day margins). // // A dry run reads and matches the same and writes nothing; the totals are in // the log's `@@mirror-scan` line either way. import path from "node:path"; import { existsSync } from "node:fs"; import { open } from "lmdb"; import type { Paths } from "../lib/paths"; import type { TranscriptSummary } from "../lib/transcripts"; import { loadRawMetadataFromDir, summarize } from "../lib/transcripts-server"; import { assertChannelTextReadable } from "../lib/channelMedia"; import { mapConcurrent } from "../lib/concurrency"; import { compileRecordedDateRule, deriveRecordedDate } from "../lib/recordedDate"; import { sourceGoneState } from "../lib/sourceGone-server"; import { isSafeChannelSegment } from "../lib/citations/moments"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { addDays, contentDate, matchMirror, MIRROR_DAYS_AFTER, MIRROR_DAYS_BEFORE, type MirrorRecord, } from "../lib/mirrors/match"; import { MIRROR_RULES, MIRROR_SCAN_FORMAT, MIRROR_SCAN_VERSION, type MirrorScanFile } from "../lib/mirrors/scanFile"; import { writeMirrorScan } from "../lib/mirrors/scanFile-server"; import { readChannelConfig } from "./channels"; import { heldVideoIds } from "./videoCues"; export const MIRROR_SCAN_JOB_KIND = "mirror-scan"; // One scan at a time, machine-wide: each reads the index and thousands of // small sidecars; two at once only halve each other. export const MIRROR_SCAN_QUEUE = "mirror-scan"; export const MIRROR_SCAN_RESULT_MARKER = "@@mirror-scan "; export const MIRROR_SCAN_BODY_KEYS = ["slug", "dryRun"] as const; const GONE_READ_CONCURRENCY = 32; type IndexKey = [string, string, string]; type PathKey = [string, string]; export type ChannelRecords = { slug: string; platform: string; records: MirrorRecord[]; fromIndex: number; fromDisk: number; // Data dirs with no readable metadata (no record). noMetadata: number; }; // The channel's index summaries by data dir. Never throws: a missing, locked // or mid-rebuild index is "nothing from the index", and the disk carries on. function indexSummaries(paths: Paths, slug: string, dirs: ReadonlySet): Map { const out = new Map(); if (dirs.size === 0 || !existsSync(paths.lmdbPath)) return out; let root: ReturnType; try { // `compression: true` on a reader too (videoTitles.ts's note). root = open({ path: paths.lmdbPath, readOnly: true, maxDbs: 18, compression: true }); } catch { return out; } try { const sums = root.openDB({ name: "sums", encoding: "msgpack" }); const mtimes = root.openDB<{ indexKey?: IndexKey }, PathKey>({ name: "mtimes", encoding: "msgpack" }); for (const { key, value } of mtimes.getRange({ start: [slug], end: [slug, "￿"] })) { const k = key as PathKey; if (k[0] !== slug) break; if (!dirs.has(k[1]) || !value?.indexKey) continue; const s = sums.get(value.indexKey); if (s && typeof s.id === "string") out.set(k[1], s); } } catch { // A partial read stands; the rest comes off disk. } finally { void root.close().catch(() => {}); } return out; } // The platform a channel is on: its config's, else the one most of its // records carry. function channelPlatform(configured: string | undefined, summaries: Iterable): string { if (configured) return configured; const n = new Map(); for (const s of summaries) n.set(s.platform, (n.get(s.platform) ?? 0) + 1); return [...n.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0]?.[0] ?? "unknown"; } // One channel's videos as the matcher reads them; the gone state read for the // records dated inside `goneWindow` (none read without one). export async function readChannelRecords( paths: Paths, slug: string, opts: { goneWindow?: { from: string; to: string } | null } = {}, ): Promise { const config = await readChannelConfig(paths, slug); if (!config) throw new Error(`Channel "${slug}" not found`); // The text guard: an unmounted or moving drive is not an empty channel. await assertChannelTextReadable(paths, slug, config); const dataDir = path.join(paths.channelsDir, slug, "data"); const dirs = await heldVideoIds(dataDir); const fromIndex = indexSummaries(paths, slug, dirs); const summaries = new Map(fromIndex); let noMetadata = 0; const rest = [...dirs].filter((d) => !summaries.has(d)).sort(); await mapConcurrent(rest, 16, async (dir) => { const meta = await loadRawMetadataFromDir(path.join(dataDir, dir)).catch(() => null); if (!meta) { noMetadata++; return; } summaries.set(dir, summarize(slug, dir, meta, config.name)); }); const rule = config.recordedDate ? compileRecordedDateRule(config.recordedDate) : null; const records: (MirrorRecord & { dir: string })[] = []; for (const [dir, s] of [...summaries.entries()].sort((a, b) => a[0].localeCompare(b[0]))) { const recordedDate = s.recordedDate ?? (rule ? deriveRecordedDate(rule, s.title, s.uploadDate) : undefined); records.push({ id: s.id, dir, title: s.title, duration: typeof s.duration === "number" && Number.isFinite(s.duration) ? s.duration : 0, uploadDate: s.uploadDate ?? "", ...(recordedDate ? { recordedDate } : {}), wasLive: s.isLivestream === true, gone: null, }); } const w = opts.goneWindow; if (w) { const inWindow = records.filter((r) => { const d = contentDate(r); return d !== null && d >= w.from && d <= w.to; }); await mapConcurrent(inWindow, GONE_READ_CONCURRENCY, async (r) => { r.gone = await sourceGoneState(path.join(dataDir, r.dir)).catch(() => null); }); } return { slug, platform: channelPlatform(config.platform, summaries.values()), records, fromIndex: fromIndex.size, fromDisk: summaries.size - fromIndex.size, noMetadata, }; } export type MirrorScanOptions = { dryRun?: boolean; jobId?: string; onLog?: (line: string) => void; now?: () => Date; }; export type MirrorScanOutcome = { file: MirrorScanFile; // Where it was written; absent on a dry run. path?: string; }; // The refusal for a channel that cannot be scanned, or null. export async function mirrorScanRefusal(paths: Paths, slug: string): Promise { if (!isSafeChannelSegment(slug)) return `not a channel slug: ${JSON.stringify(slug)}`; const config = await readChannelConfig(paths, slug); if (!config) return `Channel "${slug}" not found`; const of = (config.mirror?.of ?? []).filter((s) => s !== slug); if (of.length === 0) { return `${slug} is not a mirror: its config has no mirror.of — set the creator's channels first: pnpm ops channel-config --json '{"slug":"${slug}","patch":{"mirrorOf":", …"}}'`; } const found = await Promise.all(of.map(async (s) => ((await readChannelConfig(paths, s)) ? s : null))); if (!found.some(Boolean)) return `none of ${slug}'s mirror.of channels is in this corpus (${of.join(", ")})`; return null; } export async function runMirrorScan(paths: Paths, slug: string, opts: MirrorScanOptions = {}): Promise { const log = opts.onLog ?? (() => {}); const refusal = await mirrorScanRefusal(paths, slug); if (refusal) throw new Error(refusal); const config = (await readChannelConfig(paths, slug))!; const of = config.mirror!.of.filter((s) => s !== slug); const missing: string[] = []; for (const s of of) if (!(await readChannelConfig(paths, s))) missing.push(s); if (missing.length > 0) log(`not in this corpus, skipped: ${missing.join(", ")}`); const mirror = await readChannelRecords(paths, slug); log(`${slug}: ${mirror.records.length} videos (${mirror.fromIndex} from the index, ${mirror.fromDisk} from disk)`); const dates = mirror.records.map(contentDate).filter((d): d is string => d !== null).sort(); const goneWindow = dates.length > 0 ? { from: addDays(dates[0], -MIRROR_DAYS_BEFORE), to: addDays(dates.at(-1)!, MIRROR_DAYS_AFTER) } : null; const creators: ChannelRecords[] = []; for (const s of of.filter((x) => !missing.includes(x))) { const c = await readChannelRecords(paths, s, { goneWindow }); const gone = c.records.filter((r) => r.gone).length; log(`${s} (${c.platform}): ${c.records.length} videos (${c.fromIndex} from the index, ${c.fromDisk} from disk), ${gone} gone in reach`); creators.push(c); } const result = matchMirror({ mirror: { slug, platform: mirror.platform, records: mirror.records, titleRule: config.recordedDate ? compileRecordedDateRule(config.recordedDate) : null }, creators: creators.map((c) => ({ slug: c.slug, platform: c.platform, records: c.records })), }); const file: MirrorScanFile = { format: MIRROR_SCAN_FORMAT, version: MIRROR_SCAN_VERSION, mirror: slug, of, ...(missing.length > 0 ? { missing } : {}), generatedAt: (opts.now?.() ?? new Date()).toISOString(), ...(opts.jobId ? { jobId: opts.jobId } : {}), rules: { ...MIRROR_RULES }, ...result, }; if (opts.dryRun) return { file }; return { file, path: await writeMirrorScan(paths.transcriptsDir, file) }; } // The `@@mirror-scan` line's JSON: the totals both ways, no per-video rows. export function mirrorScanSummary(out: MirrorScanOutcome, dryRun: boolean) { const f = out.file; return { slug: f.mirror, dryRun, ...(out.path ? { file: out.path } : {}), of: f.of, ...(f.missing ? { missing: f.missing } : {}), window: f.window, videos: f.totals.videos, matched: f.totals.matched, byStatus: f.totals.byStatus, byPlatform: f.totals.byPlatform, creatorRemoved: f.totals.creatorRemoved, }; } export type MirrorScanBody = { slug: string; dryRun: boolean }; export function parseMirrorScanBody(raw: Record): MirrorScanBody { const slug = typeof raw.slug === "string" ? raw.slug.trim() : ""; if (!slug) throw new Error('"slug" is required: the mirror channel'); if (!isSafeChannelSegment(slug)) throw new Error(`not a channel slug: ${JSON.stringify(slug)}`); if (raw.dryRun !== undefined && typeof raw.dryRun !== "boolean") throw new Error('"dryRun" must be true or false'); return { slug, dryRun: raw.dryRun === true }; } // Enqueue a `mirror-scan` job (refused before any job for a channel that is no // mirror). `onDone` runs after a scan that wrote its file (the editor // revalidates the channel page there). export async function enqueueMirrorScan( raw: Record, deps: { paths: Paths; onDone?: (slug: string) => void; now?: () => Date }, ): Promise { let body: MirrorScanBody; try { body = parseMirrorScanBody(raw); } catch (e) { return { ok: false, error: (e as Error).message }; } const refusal = await mirrorScanRefusal(deps.paths, body.slug); if (refusal) return { ok: false, error: refusal }; return runManagedFunction({ kind: MIRROR_SCAN_JOB_KIND, queueKey: MIRROR_SCAN_QUEUE, paths: deps.paths, channelSlug: body.slug, fn: async (onLog, _signal, _setProgress, ctx) => { onLog(`mirror scan of ${body.slug}${body.dryRun ? " (dry run: nothing is written)" : ""}`); const out = await runMirrorScan(deps.paths, body.slug, { dryRun: body.dryRun, jobId: ctx.jobId, onLog, ...(deps.now ? { now: deps.now } : {}) }); const t = out.file.totals; onLog( `${t.videos} videos: ${t.byStatus["only-copy"]} only copy, ${t.byStatus["creator-deleted"]} creator deleted, ` + `${t.byStatus["never-uploaded"]} never uploaded, ${t.byStatus["creator-public"]} creator public`, ); onLog(`the creator removed ${t.creatorRemoved.inWindow} in this window; the mirror holds ${t.creatorRemoved.held}`); if (out.path) onLog(`wrote ${out.path}`); onLog(`${MIRROR_SCAN_RESULT_MARKER}${JSON.stringify(mirrorScanSummary(out, body.dryRun))}`); if (out.path) deps.onDone?.(body.slug); }, }); }