// The filesystem half of the sync check: probe a window, record a good // verdict in its sidecar, set a desynced one aside. The rule and its measured // numbers are lib/clipWindowSync.ts. import path from "node:path"; import { readFile, rename, rm } from "node:fs/promises"; import { execa } from "execa"; import { writeJsonAtomic } from "./jsonFile-server"; import { CLIP_WINDOW_EXTS, clipWindowContains, clipWindowDesyncedFile, clipWindowDesyncedSidecar, clipWindowExtOf, windowTierOf, } from "./clipWindow"; import { clipWindowSidecarPath, listClipWindows, tallClipWindowCandidates, type ClipWindow, } from "./clipWindow-server"; import { parseRecordedClipWindowSync, windowSyncOf, type ClipWindowSync, type ProbedWindowStream, type RecordedClipWindowSync, } from "./clipWindowSync"; import "./childKillGuard"; // A window's streams, or null when they cannot be read. Injectable so tests // decide what a window holds without a real one. export type WindowStreamProbe = (file: string) => Promise; // ONE ffprobe of the container's stream headers — no decode, so it costs a // fraction of a second on a window even on a platter. Null when ffprobe is // missing, fails, times out or prints something unparseable: a window this // cannot read is NOT JUDGED (kept, nothing recorded), never set aside on a // guess. Whether the file is corrupt is the audio check's question, not this. export async function probeWindowStreams( file: string, ffprobeBin = "ffprobe", opts: { timeoutMs?: number; signal?: AbortSignal } = {}, ): Promise { try { const r = await execa( ffprobeBin, [ "-v", "error", "-show_entries", "stream=codec_type,start_time,duration:stream_disposition=attached_pic", "-of", "json", file, ], { reject: false, timeout: opts.timeoutMs ?? 15_000, ...(opts.signal ? { cancelSignal: opts.signal } : {}) }, ); if (r.exitCode !== 0) return null; const doc = JSON.parse(String(r.stdout)) as { streams?: unknown }; return Array.isArray(doc.streams) ? (doc.streams as ProbedWindowStream[]) : null; } catch { return null; } } export function ffprobeWindowProbe(ffprobeBin = "ffprobe"): WindowStreamProbe { return (file) => probeWindowStreams(file, ffprobeBin); } async function readRawSidecar(file: string): Promise | null> { const text = await readFile(file, "utf8").catch(() => null); if (text === null) return null; try { const raw = JSON.parse(text) as unknown; return raw && typeof raw === "object" && !Array.isArray(raw) ? (raw as Record) : null; } catch { return null; } } const sidecarOf = (win: Pick) => clipWindowSidecarPath(win); export type ClipWindowJudgement = { // Null: the window could not be probed, and is kept as it is. sync: ClipWindowSync | null; // Answered by the sidecar's recorded verdict, not a probe. fromRecord: boolean; }; // JUDGE ONE WINDOW. A sidecar that records `sync.ok` for the window's CURRENT // size answers without a probe; anything else is probed. A good verdict is // recorded in the sidecar (merged into it as it stands — fields this module // does not know are kept), unless `record: false` (a dry run writes nothing). // A window with no sidecar gets one holding only the verdict: it parses as no // provenance, exactly as the missing file did. export async function judgeClipWindow( win: ClipWindow, opts: { probe: WindowStreamProbe; record?: boolean; now?: () => Date }, ): Promise { const sidecar = sidecarOf(win); const raw = await readRawSidecar(sidecar); const recorded = parseRecordedClipWindowSync(raw?.sync); if (recorded?.ok && recorded.bytes === win.bytes) return { sync: recorded, fromRecord: true }; const streams = await opts.probe(win.path); if (!streams) return { sync: null, fromRecord: false }; const sync = windowSyncOf(streams, win.to - win.from); if (sync.ok && opts.record !== false) { const entry: RecordedClipWindowSync = { ...sync, bytes: win.bytes, checkedAt: (opts.now?.() ?? new Date()).toISOString(), }; // A failed write costs the next run one probe, nothing else. await writeJsonAtomic(sidecar, { ...(raw ?? {}), sync: entry }).catch(() => {}); } return { sync, fromRecord: false }; } // SET A DESYNCED WINDOW ASIDE: `-.` → `-.desynced.`, // its sidecar → `-.desynced.json` with the verdict and `setAsideAt`. // Never a delete: the bytes are evidence of what the source served, and // evictClipWindows ages them out as the cache they are. // // THE PATH ITSELF IS RENAMED, never a resolved target: `clips/` is never // tiered, but whatever a window is — a file, or a link someone made — it stays // that, under its new name, beside where it was. A window set aside earlier // for the same span (any extension) is replaced: the newest verdict is the one // worth keeping. The media goes first, so the window leaves every reader in one // step; a crash before the sidecar moves leaves a sidecar with no window, which // nothing reads and the next fetch of the span overwrites. export async function setAsideDesyncedWindow( win: Pick, sync: ClipWindowSync, now: Date = new Date(), ): Promise<{ file: string; path: string }> { const dir = path.dirname(win.path); const ext = clipWindowExtOf(win.file) ?? ".mp4"; // A tiered window is set aside under its tier: `-.h.desynced.`. const file = clipWindowDesyncedFile(win.from, win.to, ext, win.tier); const dest = path.join(dir, file); for (const other of CLIP_WINDOW_EXTS) { if (other !== ext) await rm(path.join(dir, clipWindowDesyncedFile(win.from, win.to, other, win.tier)), { force: true }); } await rename(win.path, dest); const sidecar = sidecarOf(win); const raw = await readRawSidecar(sidecar); const at = now.toISOString(); await writeJsonAtomic(path.join(dir, clipWindowDesyncedSidecar(win.from, win.to, win.tier)), { ...(raw ?? {}), sync: { ...sync, bytes: win.bytes, checkedAt: at }, setAsideAt: at, }); await rm(sidecar, { force: true }); return { file, path: dest }; } export type DesyncedClipWindow = { window: ClipWindow; sync: ClipWindowSync; // The name it was set aside as, or null when the caller asked for none. setAsideAs: string | null; }; // THE TIGHTEST CONTAINING WINDOW THAT IS IN SYNC — `findContainingClipWindow` // with the check in front of its answer. Candidates are judged tightest first // and the walk stops at the first good one, so a run probes only the windows it // would actually use. A desynced one is set aside (unless `setAside: false`: // a planner that only needs to know whether the span is held) and the next // candidate is asked; none left is null — the span is missing, and the caller // goes to the saved-video tier, then the network, as for any missing span. // // A TALL ASK (`maxHeight` above the plain 720, with `heightProbe`) takes the // plain and the tiered windows in tallClipWindowCandidates' order — the // tallest at or under the cap first — and the hit carries its `height`. Any // other ask is exactly as before: plain windows, tightest first, no height. export async function findInSyncContainingClipWindow( videoDir: string, from: number, to: number, opts: { probe: WindowStreamProbe; setAside?: boolean; record?: boolean; maxHeight?: number; heightProbe?: (file: string) => Promise; }, ): Promise<{ hit: ClipWindow | null; desynced: DesyncedClipWindow[] }> { const tall = windowTierOf(opts.maxHeight) !== undefined && opts.heightProbe; const candidates = tall ? await tallClipWindowCandidates(videoDir, from, to, opts.maxHeight!, opts.heightProbe!) : (await listClipWindows(videoDir)) .filter((w) => clipWindowContains(w, from, to)) .sort((a, b) => a.to - a.from - (b.to - b.from)); const desynced: DesyncedClipWindow[] = []; for (const w of candidates) { const { sync } = await judgeClipWindow(w, { probe: opts.probe, record: opts.record }); if (!sync || sync.ok) return { hit: w, desynced }; const aside = opts.setAside === false ? null : await setAsideDesyncedWindow(w, sync); desynced.push({ window: w, sync, setAsideAs: aside?.file ?? null }); } return { hit: null, desynced }; } // THE TIERED WINDOW A PLAIN MISS MAY BE CUT FROM (the height tier, D) — only // one that is in sync, judged exactly as a window is when it is used: the // tiered windows holding [from, to], tightest first (lowest tier of equals); // a desynced one is set aside as usual (unless `setAside: false`, a planner) // and the next asked; none left is null — the plain ask goes on as if there // were no tiered window at all. export async function findInSyncTieredWindowHolding( videoDir: string, from: number, to: number, opts: { probe: WindowStreamProbe; setAside?: boolean; record?: boolean }, ): Promise<{ hit: ClipWindow | null; desynced: DesyncedClipWindow[] }> { const candidates = (await listClipWindows(videoDir, { tiers: true })) .filter((w) => w.tier !== undefined && clipWindowContains(w, from, to)) .sort((a, b) => a.to - a.from - (b.to - b.from) || (a.tier ?? 0) - (b.tier ?? 0)); const desynced: DesyncedClipWindow[] = []; for (const w of candidates) { const { sync } = await judgeClipWindow(w, { probe: opts.probe, record: opts.record }); if (!sync || sync.ok) return { hit: w, desynced }; const aside = opts.setAside === false ? null : await setAsideDesyncedWindow(w, sync); desynced.push({ window: w, sync, setAsideAs: aside?.file ?? null }); } return { hit: null, desynced }; }