// THE "BEING COMPACTED" MARKER, `/.compacting.json` // (controller/compactSavedVideos.ts writes it; every persist, attach, import, // unpersist and drop of the video reads it). // // A marker is LIVE only when everything it names still holds: // - this machine's kernel (`/proc/sys/kernel/random/boot_id`) — a reboot // ends every compaction; // - this host (a marker written in another container or on the host by a // CLI cannot be checked from here, and counts as stale); // - a running process with that pid AND that process's start time (field 22 // of /proc//stat), so a pid reused by another process is not it; // - when the marker is this process's own and names a job: that job is one // the job registry knows as queued or running (a probe the controller // registers; lib does not import the registry); // - younger than MARKER_MAX_AGE_HOURS. // Anything else is stale: it is ignored by every guard and removed by the // sweep (at editor boot and at the start of every compaction run) and by // `pnpm ops compaction-markers {"clear": …}`. // // The compaction's own steps carry the marker's token, and pass where another // writer is refused (the drop of the original under after-verify, F4). import { link, readFile, rename, rm } from "node:fs/promises"; import { hostname } from "node:os"; import path from "node:path"; import { randomUUID } from "node:crypto"; import { readJsonFile, writeJsonAtomic } from "./jsonFile-server"; export const COMPACTING_MARKER_FILENAME = ".compacting.json"; export const MARKER_MAX_AGE_HOURS = 72; export type CompactingMarker = { pid: number; pidStart: string | null; bootId: string | null; host: string; jobId?: string; token: string; startedAt: string; video?: string; }; export class CompactionInProgressError extends Error { constructor(message: string) { super(message); this.name = "CompactionInProgressError"; } } async function bootId(): Promise { return readFile("/proc/sys/kernel/random/boot_id", "utf8").then((s) => s.trim(), () => null); } // The process's start time in clock ticks since boot, or null (no /proc, gone). export async function processStartTime(pid: number): Promise { try { const s = await readFile(`/proc/${pid}/stat`, "utf8"); const rest = s.slice(s.lastIndexOf(")") + 2).split(" "); // Fields after the comm start at field 3: start time is field 22. return rest[22 - 3] ?? null; } catch { return null; } } function alive(pid: number): boolean { try { process.kill(pid, 0); return true; } catch (e) { // EPERM: it exists, under another user. return (e as NodeJS.ErrnoException).code === "EPERM"; } } // The registry's word on a job of this process (registered by the controller). type JobProbe = (jobId: string) => boolean; let jobProbe: JobProbe | null = null; export function registerCompactionJobProbe(probe: JobProbe | null): void { jobProbe = probe; } export function markerPath(storeDir: string): string { return path.join(storeDir, COMPACTING_MARKER_FILENAME); } export async function writeCompactingMarker(storeDir: string, opts: { jobId?: string; video?: string; now?: Date } = {}): Promise { const m: CompactingMarker = { pid: process.pid, pidStart: await processStartTime(process.pid), bootId: await bootId(), host: hostname(), ...(opts.jobId ? { jobId: opts.jobId } : {}), token: randomUUID(), startedAt: (opts.now ?? new Date()).toISOString(), ...(opts.video ? { video: opts.video } : {}), }; await writeJsonAtomic(markerPath(storeDir), m); return m; } export async function readCompactingMarker(storeDir: string): Promise { const read = await readJsonFile(markerPath(storeDir)); if (!read.ok || !read.value || typeof read.value !== "object") return null; const r = read.value as Record; if (typeof r.pid !== "number") return null; return { pid: r.pid, pidStart: typeof r.pidStart === "string" ? r.pidStart : null, bootId: typeof r.bootId === "string" ? r.bootId : null, host: typeof r.host === "string" ? r.host : "", ...(typeof r.jobId === "string" ? { jobId: r.jobId } : {}), token: typeof r.token === "string" ? r.token : "", startedAt: typeof r.startedAt === "string" ? r.startedAt : "", ...(typeof r.video === "string" ? { video: r.video } : {}), }; } // Live, or why not. export async function markerLiveness(m: CompactingMarker, now = new Date()): Promise<{ live: boolean; why: string }> { if (m.host !== hostname()) return { live: false, why: `written on another host (${m.host || "unknown"})` }; const boot = await bootId(); if (!m.bootId || (boot && m.bootId !== boot)) return { live: false, why: "written before this machine last started" }; if (!alive(m.pid)) return { live: false, why: `its process ${m.pid} is gone` }; const start = await processStartTime(m.pid); if (!m.pidStart || (start !== null && start !== m.pidStart)) return { live: false, why: `pid ${m.pid} is another process now` }; if (m.pid === process.pid && m.jobId && jobProbe && !jobProbe(m.jobId)) { return { live: false, why: `its job ${m.jobId} is not running` }; } const age = (now.getTime() - Date.parse(m.startedAt)) / 3_600_000; if (!Number.isFinite(age) || age > MARKER_MAX_AGE_HOURS) return { live: false, why: `older than ${MARKER_MAX_AGE_HOURS} h` }; return { live: true, why: `pid ${m.pid} since ${m.startedAt.slice(0, 16)}${m.jobId ? `, job ${m.jobId}` : ""}` }; } export async function liveCompactingMarker(storeDir: string): Promise { const m = await readCompactingMarker(storeDir); if (!m) return null; return (await markerLiveness(m)).live ? m : null; } // Refused while a live marker is there — unless the caller holds its token // (the compaction's own steps). export async function assertNotCompacting(storeDir: string, what: string, ownToken?: string): Promise { const m = await liveCompactingMarker(storeDir); if (m && !(ownToken && m.token === ownToken)) { throw new CompactionInProgressError( `${what} refused: this video's saved copy is being compacted (since ${m.startedAt.slice(0, 16)}, pid ${m.pid}` + `${m.jobId ? `, job ${m.jobId}` : ""}). Run it again once the compaction is done.`, ); } } // Remove a marker that is not live (or, with `token`, the caller's own). // // NEVER A MARKER WRITTEN AFTER THE CHECK (review D3): a compaction may write a // fresh marker between this read and the removal. So the file is first // RENAMED aside (atomic), read again there, and removed only if it is still // the marker that was judged (same token); otherwise it is put back with a // link that refuses to overwrite (a newer marker at the path wins) and the // clear is refused. export async function clearCompactingMarker( storeDir: string, opts: { token?: string; beforeRemove?: () => Promise } = {}, ): Promise<{ cleared: boolean; why: string }> { const m = await readCompactingMarker(storeDir); if (!m) return { cleared: false, why: "no marker" }; let why: string; if (opts.token && m.token === opts.token) why = "the compaction's own"; else { const l = await markerLiveness(m); if (l.live) return { cleared: false, why: `live: ${l.why} — cancel that job instead` }; why = `stale: ${l.why}`; } await opts.beforeRemove?.(); const p = markerPath(storeDir); const aside = `${p}.clearing-${randomUUID()}`; try { await rename(p, aside); } catch { return { cleared: false, why: "the marker went meanwhile" }; } const read = await readJsonFile(aside); const token = read.ok && read.value && typeof read.value === "object" ? (read.value as { token?: unknown }).token : undefined; if (token !== m.token) { // A marker written after the check: it goes back where it was. await link(aside, p).catch(() => {}); await rm(aside, { force: true }); return { cleared: false, why: "a new marker was written meanwhile: kept" }; } await rm(aside, { force: true }); return { cleared: true, why }; }