// WHAT FREE UP SPACE NEVER OFFERS, AND THE CHECK AT THE CLICK (lane // space-suggestions, review 1 B2 and B4). // // ONE HELD PREDICATE. The scan (controller/spaceScan.ts) asks it of every // video a row would touch, the store rows included, and the page's button asks // it again before anything runs (editor/app/cleanup/space/lib/runSpaceAction.ts). // A video is held by: // - do-not-clean; // - a live recording of it that is must-keep, or whose run is not over // (anything but landed, failed, cancelled or superseded; interrupted and // awaiting a resume hold); // - a job queued or running for it (or a channel-wide writer on its channel); // - its channel's relocation marker. // The store's rows are held, too, by the store's own relocation marker. A pin // keeps every copy of its video (ruling 2): that rule is alternateDisposition's // (lib/spaceSuggestions.ts), for the one kind that removes a copy of it. // // THE RE-CHECK (rulings for B4, orchestrator's, 24 Nov). A scan older than a // day is refused ("rescan first"). Then, for the row's own subject: the held // predicate, as it is now; every target file still there with the size and // mtime the scan saw, and one link; a channel-wide clip eviction's whole set // of old windows the same as at the scan, and no video holding a window held. // A partial is also refused when its video is not known to be on its platform // (it may be the only copy of those bytes). Any mismatch refuses the row and // says why. Reads only. import path from "node:path"; import { createHash } from "node:crypto"; import { lstat, readdir } from "node:fs/promises"; import type { Paths } from "../lib/paths"; import { getRegistry, type JobRecord } from "../jobs/registry"; import type { SpaceScanResult, SpaceSuggestion } from "../lib/spaceSuggestions"; import { readRelocationMarker } from "../lib/channelMedia"; import { readSavedVideosMarker } from "../lib/savedVideoStore"; import { doNotCleanPath } from "../lib/doNotClean-server"; import { readJsonFile } from "../lib/jsonFile-server"; import { resolveEffectiveAvailability } from "../lib/availability-server"; import { CLIPS_DIR_NAME, parseAnyClipWindowName, parseDesyncedClipWindowName, clipWindowStem } from "../lib/clipWindow"; import { LIVE_RECORDINGS_FILENAME, loadLiveRecordingsFile, type LiveRecordingRow } from "../lib/liveRecordings-server"; import { SPACE_SCAN_VERSION } from "../lib/spaceSuggestions"; import { VIDEO_WRITING_KINDS } from "./videoBusy"; export const SPACE_MAX_SCAN_AGE_MS = 24 * 60 * 60 * 1000; // A scan dated further ahead than this was written by a wrong clock or by hand. export const SPACE_MAX_SCAN_FUTURE_MS = 5 * 60 * 1000; // A downloader's partial: what `delete-file` may be asked to remove once it is // abandoned. NARROWER than mediaTier's scratch on purpose — a stored-text // run's `.retire-` (possibly the only copy), a `.landed-kept` or // `.corrupt-kept` container, a tier hook's temp are somebody's kept bytes. const PARTIAL_RES: readonly RegExp[] = [ /\.part$/, /\.ytdl$/, /\.part-Frag\d+$/, /\.part\.(good|testing)$/, /\.stored\.part\.json$/, /^\.syncthing\..*\.tmp$/, /^audio\.tmp-\d+\./, /\.temp\./, ]; export function isAbandonablePartial(name: string): boolean { return PARTIAL_RES.some((re) => re.test(name)); } // On its platform by the record's word (public or unlisted). Anything else — // gone, private, unknown — and a partial may be the only copy. export function partialMayBeOnlyCopy(availability: string | null): boolean { return availability !== "public" && availability !== "unlisted"; } export type SpaceHoldKind = "do-not-clean" | "must-keep" | "live" | "job" | "moving" | "store-moving"; export type SpaceHold = { kind: SpaceHoldKind; why: string }; export const SPACE_HOLD_LABELS: Record = { "do-not-clean": "Videos marked do-not-clean", "must-keep": "Must-keep live recordings", live: "Videos with a live recording not over", job: "Videos a job is working on", moving: "Channels mid-relocation", "store-moving": "The saved-video store, mid-move", }; type LiveRowLike = Pick & { status: string; supersededBy?: string; awaitingResume?: string[]; }; const TERMINAL = new Set(["landed", "failed", "cancelled"]); export function liveRowHold(r: LiveRowLike): SpaceHold | null { if (r.mustKeep) return { kind: "must-keep", why: "a must-keep live recording" }; if (r.awaitingResume?.length) return { kind: "live", why: "a live recording awaiting a resume" }; if (r.supersededBy) return null; if (!TERMINAL.has(r.status)) return { kind: "live", why: `a live recording (${r.status})` }; return null; } type JobLike = Pick & Partial>; // FAIL CLOSED (review 2, F6): a do-not-clean file that is there but cannot be // read or parsed holds its video, and says so. Absent holds nothing. A file // that parses is a mark whatever it holds (doNotClean-server's rule). export async function readDoNotCleanHold(videoDir: string): Promise { const read = await readJsonFile(doNotCleanPath(videoDir)); if (read.ok) return { kind: "do-not-clean", why: "do-not-clean" }; if (read.reason === "absent") return null; return { kind: "do-not-clean", why: `its do-not-clean mark could not be read (${read.reason}): held` }; } // A channel's live rows off its own file; a file there that cannot be read or // parsed THROWS, so every video of the channel is held (F6). async function liveRowsOffDisk(paths: Pick, slug: string): Promise { const f = await loadLiveRecordingsFile(paths, slug); if (f.problem) throw new Error(f.problem); return f.rows; } export type SpaceHoldDeps = { // A do-not-clean hold for a video dir (default: readDoNotCleanHold). doNotClean?: (videoDir: string) => Promise; liveRows?: (slug: string) => Promise; jobs?: () => readonly JobLike[]; }; function jobIds(j: JobLike): string[] | null { const ids = (j.spec?.params as { ids?: unknown } | undefined)?.ids; return Array.isArray(ids) ? ids.filter((x): x is string => typeof x === "string") : null; } export class SpaceHolds { private readonly live = new Map>(); private readonly markers = new Map>(); private storeMemo: Promise | null = null; private jobList: readonly JobLike[] | null = null; constructor( private readonly paths: Pick, private readonly deps: SpaceHoldDeps = {}, ) {} private jobs(): readonly JobLike[] { if (!this.jobList) { this.jobList = (this.deps.jobs ?? defaultJobs)().filter((j) => j.status === "queued" || j.status === "running"); } return this.jobList; } channel(slug: string): Promise { let m = this.markers.get(slug); if (!m) { m = readRelocationMarker(this.paths, slug).then((marker) => marker ? { kind: "moving" as const, why: `a relocation is in flight (${marker.direction}, phase ${marker.phase})` } : null, ); this.markers.set(slug, m); } return m; } store(): Promise { this.storeMemo ??= readSavedVideosMarker(this.paths).then((marker) => marker ? { kind: "store-moving" as const, why: `the saved-video store is being moved (${marker.direction}, phase ${marker.phase})` } : null, ); return this.storeMemo; } // The rows, or the error the file gave (held, F6). private liveRows(slug: string): Promise { let p = this.live.get(slug); if (!p) { p = (this.deps.liveRows ?? ((s: string) => liveRowsOffDisk(this.paths, s)))(slug).catch((e: Error) => ({ error: e.message || String(e) })); this.live.set(slug, p); } return p; } job(slug: string, id: string): SpaceHold | null { for (const j of this.jobs()) { if (j.kind === "space-scan") continue; if (j.channelSlug && j.channelSlug !== slug) continue; const ids = jobIds(j); const forIt = j.videoId ? j.videoId === id : ids ? ids.includes(id) : !!j.channelSlug && VIDEO_WRITING_KINDS.has(j.kind); if (forIt) return { kind: "job", why: `a job is working on it (${j.kind}, ${j.status})` }; } return null; } // `opts.noDoNotCleanFile`: the caller listed the dir and saw no // do-not-clean file (the scan), so it is not read. async video(slug: string, id: string, opts: { noDoNotCleanFile?: boolean } = {}): Promise { const moving = await this.channel(slug); if (moving) return moving; const dir = path.join(this.paths.channelsDir, slug, "data", id); if (!opts.noDoNotCleanFile) { const dnc = await (this.deps.doNotClean ?? readDoNotCleanHold)(dir).catch((e: Error) => ({ kind: "do-not-clean" as const, why: `its do-not-clean mark could not be read (${e.message}): held`, })); if (dnc) return dnc; } const rows = await this.liveRows(slug); if (!Array.isArray(rows)) return { kind: "live", why: `the channel's ${LIVE_RECORDINGS_FILENAME} could not be read (${rows.error}): held` }; for (const r of rows) { if (r.id !== id) continue; const h = liveRowHold(r); if (h) return h; } return this.job(slug, id); } } function defaultJobs(): readonly JobLike[] { return getRegistry().list(); } // --- clip windows --------------------------------------------------------------------- export type ClipWindowFile = { id: string; name: string; stem: string; path: string; size: number; mtimeMs: number; nlink: number; blocks: number }; // One video dir's clip windows (the media, never the sidecars), as the // evictor reads them. export async function clipWindowsOf(videoDir: string, id: string): Promise { const dir = path.join(videoDir, CLIPS_DIR_NAME); const out: ClipWindowFile[] = []; for (const name of await readdir(dir).catch(() => [] as string[])) { const span = parseAnyClipWindowName(name) ?? parseDesyncedClipWindowName(name); if (!span) continue; const p = path.join(dir, name); const st = await lstat(p).catch(() => null); if (!st?.isFile()) continue; out.push({ id, name, stem: clipWindowStem(span.from, span.to, span.tier), path: p, size: st.size, mtimeMs: st.mtimeMs, nlink: st.nlink, blocks: st.blocks * 512 }); } return out; } export function digestOf(files: readonly Pick[]): string { const h = createHash("sha1"); for (const line of files.map((f) => `${f.id}/${f.name}\u0000${f.size}\u0000${f.mtimeMs}`).sort()) h.update(line + "\n"); return h.digest("hex"); } // A channel's windows not touched for `olderThanDays` at `now`, digested, and // every video that holds any window (old or not). export async function clipWindowsDigest( paths: Pick, slug: string, olderThanDays: number, now: Date, ): Promise<{ count: number; sha1: string; videosWithWindows: string[]; shared: number }> { const data = path.join(paths.channelsDir, slug, "data"); const cutoff = now.getTime() - olderThanDays * 86_400_000; const old: ClipWindowFile[] = []; const videos: string[] = []; let shared = 0; for (const id of await readdir(data).catch(() => [] as string[])) { const w = await clipWindowsOf(path.join(data, id), id); if (!w.length) continue; videos.push(id); for (const f of w) { if (f.mtimeMs > cutoff) continue; old.push(f); if (f.nlink > 1) shared += 1; } } return { count: old.length, sha1: digestOf(old), videosWithWindows: videos, shared }; } // The first held video of a channel (every video dir asked), or null. export async function heldInChannel( paths: Pick, slug: string, holds: SpaceHolds, ): Promise<(SpaceHold & { id: string }) | null> { for (const id of await readdir(path.join(paths.channelsDir, slug, "data")).catch(() => [] as string[])) { const h = await holds.video(slug, id); if (h) return { ...h, id }; } return null; } // --- the re-check ---------------------------------------------------------------------- export async function recheckSpaceRow(opts: { paths: Pick; result: Pick; row: SpaceSuggestion; now?: Date; holds: SpaceHolds; availability?: (videoDir: string) => Promise; }): Promise { const now = opts.now ?? new Date(); if (opts.result.version !== SPACE_SCAN_VERSION) { return `the last scan is of an older format (version ${String(opts.result.version ?? "none")}, this editor writes ${SPACE_SCAN_VERSION}): rescan first`; } const age = now.getTime() - Date.parse(opts.result.computedAt); if (age < -SPACE_MAX_SCAN_FUTURE_MS) return "the last scan is dated in the future (a wrong clock?): rescan first"; if (!(age <= SPACE_MAX_SCAN_AGE_MS)) { return `the last scan is ${Number.isFinite(age) ? `${Math.round(age / 3_600_000)} h` : "of an unknown"} old: rescan first`; } const { row, holds } = opts; const h = row.hold; // A row that would act names what to check (F2): one that does not is // refused, never run unchecked. if (row.actions?.length && !h?.slug && !h?.store) return "the row names nothing to check: rescan first"; if (h?.store) { const s = await holds.store(); if (s) return `held: ${s.why}`; } if (h?.slug) { const held = h.id ? await holds.video(h.slug, h.id) : await holds.channel(h.slug); if (held) return `held: ${held.why}`; } for (const t of row.targets ?? []) { const st = await lstat(t.path).catch(() => null); if (!st?.isFile()) return `${path.basename(t.path)} is no longer there: rescan`; if (st.size !== t.size || st.mtimeMs !== t.mtimeMs) return `${path.basename(t.path)} changed since the scan: rescan`; if (st.nlink !== 1) return `${path.basename(t.path)} has another hard link now: removing it would free nothing`; } if (row.kind === "stale-partial" && h?.slug && h.id) { if (!row.file || !isAbandonablePartial(row.file)) return `${row.file ?? "?"} is not a partial download`; const a = await (opts.availability ?? resolveEffectiveAvailability)(path.join(opts.paths.channelsDir, h.slug, "data", h.id)).catch(() => null); if (partialMayBeOnlyCopy(a)) return `held: the video is not known to be on its platform (${a ?? "unknown"}): the partial may be the only copy`; } // A CHANNEL-WIDE AUDIO SWEEP (review 2, F1): the sweep knows do-not-clean // and keep-latest by its own rules, not a must-keep or unfinished live // recording — so every video of the channel is asked again. if ((row.kind === "clean-audio" || row.kind === "clean-extra-formats") && h?.slug) { const held = await heldInChannel(opts.paths, h.slug, holds); if (held) return `held: ${held.id}: ${held.why}`; } if (row.digest && h?.slug) { const d = await clipWindowsDigest(opts.paths, h.slug, row.digest.olderThanDays, now); if (d.count !== row.digest.count || d.sha1 !== row.digest.sha1) return "the channel's old clip windows changed since the scan: rescan"; if (d.shared) return "a window has another hard link now: rescan"; for (const id of d.videosWithWindows) { const held = await holds.video(h.slug, id); if (held) return `held: ${id}: ${held.why}`; } } return null; }