// THE RENDER POOL: a content-addressed cache of built units, shared by every // take of every project (operator, 4 Nov: "every clip that could be inserted // into a video is put into a shared cached clip pool by all input params by // default, kind of like archilyzer videos"). // // Each built unit is stored ONCE, under the hash of its kind, its kind's // renderer salt and the full key the build already computes for it: // // post a post item's segment and its record (post-render.mjs // postSegmentKeyOf: the entry, its plan, the box, the encode, its // files' stamps, the narration…): `seg.mp4`, `post.json` // clip a clip (or still) segment and its cut record (segment-cache.mjs // segmentKey: the ffmpeg argv with every input by its identity): // `seg.mp4`, `cut.json` // chunk a chunk of the final encode (chunked-encode.mjs chunkKey: its // inputs' contents, its graph in its own clock -- position-free): // `chunk.mp4` // sound a cut's sound (the hard-cut pins and encode, or the crossfade's // graph): `sound.m4a` // frame one chrome frame, by its frame key (frame-keys.mjs: what it // draws): `.png`, a file of its own // // Every build looks in the pool when its own out/ misses, and HARD-LINKS a hit // into the take; a unit it builds is linked into the pool (through a tmp // directory renamed into place, so a reader never sees half an object). A // link, never a copy: the pool costs no disk while a take holds the same // inode, and a build REPLACES its files (rename), never writes through them, // so neither side can change the other's bytes. Another filesystem than the // pool's (EXDEV) is simply no pool. // // WHERE: `UMTOOL_RENDER_POOL` (a directory), else `/.render-pool` // (UMTOOL_MEDIA_DIR's, else the reports root's) -- for an out/ under that // root only, so a test's or a scratch copy's build never writes into the // operator's pool. `UMTOOL_RENDER_POOL=0` turns it off. // // DISK: `UMTOOL_RENDER_POOL_MAX_GB` (default 30) caps the bytes ONLY the pool // holds (a file with one link: no take has it). Over the cap, objects go least // recently used first (an object's directory -- a frame's shard -- is touched // on every hit); an object a take still links is never evicted, so neither is // one a pinned or picked take holds, nor one a running build just made or // took. `umtool pool stats|prune|verify`. // // Hits and misses are appended to `/events.ndjson` (a line each, an // atomic append), which `stats` reads. // // Plain node; every path is a parameter or the environment. import { createHash, randomBytes } from "node:crypto"; import { createReadStream } from "node:fs"; import { appendFile, link, lstat, mkdir, readdir, readFile, realpath, rename, rm, stat, utimes, writeFile } from "node:fs/promises"; import path from "node:path"; import { MEDIA_ROOT } from "../lib/paths.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; /** * The kinds, each with its renderer SALT: bumped when code changes what a * kind's unit is for unchanged inputs (every object of the kind is then a * miss once). A kind's own key may carry a salt of its own as well * (post-render POST_SEGMENT_RV, SEGMENT_KEY_VERSION, CHUNK_KEY_VERSION, * FRAME_KEY_VERSION): those are in the keys this hashes. */ export const POOL_KINDS = Object.freeze({ post: { salt: 1, noun: "post segments" }, clip: { salt: 1, noun: "clip segments" }, chunk: { salt: 1, noun: "final-encode chunks" }, sound: { salt: 1, noun: "cut sounds" }, frame: { salt: 1, noun: "chrome frames" }, }); /** The pool's default cap on the bytes only it holds, in GB. */ export const POOL_MAX_GB_DEFAULT = 30; const META = "meta.json"; const EVENTS = "events.ndjson"; const sha256 = (s) => createHash("sha256").update(s).digest("hex"); /** * The pool for a build whose out dir is `outDir`: a directory, or null (off, * or an out/ outside the media root with no pool named). */ export async function poolFor(outDir, env = process.env) { const named = env.UMTOOL_RENDER_POOL; if (named === "0" || named === "off") return null; if (named) return path.resolve(named); const root = await realpath(MEDIA_ROOT).catch(() => MEDIA_ROOT); const out = await realpath(outDir).catch(() => path.resolve(outDir)); if (!(out === root || out.startsWith(root + path.sep))) return null; return path.join(root, ".render-pool"); } /** An object's id: its kind, the kind's salt and the build's key, hashed. */ export function poolId(kind, key) { const k = POOL_KINDS[kind]; if (!k) throw new Error(`render pool: no kind ${kind}`); return sha256(JSON.stringify({ kind, salt: k.salt, key: String(key) })).slice(0, 40); } /** Where an object lives: a directory for a unit, a file for a frame. */ export function objectPath(pool, kind, key) { const id = poolId(kind, key); return kind === "frame" ? path.join(pool, kind, id.slice(0, 2), `${id}.png`) : path.join(pool, kind, id.slice(0, 2), id); } const MADE = new Set(); async function event(pool, kind, hit) { if (!MADE.has(pool)) { await mkdir(pool, { recursive: true }).catch(() => {}); MADE.add(pool); } await appendFile(path.join(pool, EVENTS), JSON.stringify({ at: Date.now(), kind, hit }) + "\n").catch(() => {}); } /** Hard-link `src` at `dst` through a rename (whatever was at `dst` replaced); false when it cannot (EXDEV, gone). */ async function linkInto(src, dst) { const tmp = path.join(path.dirname(dst), `.${path.basename(dst)}.${process.pid}.${randomBytes(3).toString("hex")}.pool`); try { await link(src, tmp); } catch { return false; } await rename(tmp, dst); return true; } const touch = (p) => utimes(p, new Date(), new Date()).catch(() => {}); /** * A unit from the pool: each of `files` (`{ name: dest }`) hard-linked at its * dest. True on a hit (every file linked), false on a miss. */ export async function poolFetch(pool, kind, key, files) { if (!pool) return false; const dir = objectPath(pool, kind, key); const meta = await readFile(path.join(dir, META), "utf8").then((t) => JSON.parse(t), () => null); const names = Object.keys(files); if (!meta || names.some((n) => !meta.files?.[n])) { await event(pool, kind, false); return false; } for (const n of names) { if (!(await linkInto(path.join(dir, n), files[n]))) { await event(pool, kind, false); return false; } } await touch(dir); await event(pool, kind, true); return true; } function fileSha(file) { return new Promise((resolve, reject) => { const h = createHash("sha256"); createReadStream(file).on("error", reject).on("data", (b) => h.update(b)).on("end", () => resolve(h.digest("hex"))); }); } /** * A unit into the pool: each of `files` (`{ name: src }`) hard-linked into a * tmp directory with its `meta.json` (each file's bytes and sha256), renamed * into place. An object already there is kept. Never throws: a pool that * cannot take it (another filesystem, a full disk) is no pool. */ export async function poolPut(pool, kind, key, files, extra = {}) { if (!pool) return false; const dir = objectPath(pool, kind, key); try { if ((await stat(path.join(dir, META)).catch(() => null))?.isFile()) return true; const shard = path.dirname(dir); await mkdir(shard, { recursive: true }); // A hidden work dir of its own beside the shards (`/.tmp---`). const tmp = tmpPathFor(path.dirname(shard) + path.sep); await mkdir(tmp); try { const meta = { kind, key: String(key), salt: POOL_KINDS[kind].salt, at: new Date().toISOString(), files: {}, ...extra }; for (const [n, src] of Object.entries(files)) { await link(src, path.join(tmp, n)); const st = await stat(src); meta.files[n] = { bytes: st.size, sha256: await fileSha(src) }; } await writeFile(path.join(tmp, META), JSON.stringify(meta, null, 1) + "\n", "utf8"); await rename(tmp, dir).catch(async (e) => { if (e?.code !== "EEXIST" && e?.code !== "ENOTEMPTY") throw e; }); } finally { await rm(tmp, { recursive: true, force: true }); } return true; } catch { return false; } } /** A frame's file in the pool, when it has one (its shard touched), else null. */ export async function poolFrame(pool, key) { if (!pool) return null; const f = objectPath(pool, "frame", key); if (!(await stat(f).catch(() => null))?.isFile()) return null; await touch(path.dirname(f)); return f; } /** Frames into the pool: each `[key, file]` linked in (one already there kept). Returns how many went in. */ export async function poolPutFrames(pool, pairs) { if (!pool || !pairs.length) return 0; let n = 0; const shards = new Set(); for (const [key, src] of pairs) { const f = objectPath(pool, "frame", key); if (!shards.has(path.dirname(f))) { await mkdir(path.dirname(f), { recursive: true }).catch(() => {}); shards.add(path.dirname(f)); } if ((await lstat(f).catch(() => null))?.isFile()) continue; if (await linkInto(src, f).catch(() => false)) n += 1; } return n; } /** Record a batch of frame lookups (one line, not one per frame). */ export async function poolFrameEvents(pool, hits, misses) { if (!pool || !(hits + misses)) return; await mkdir(pool, { recursive: true }).catch(() => {}); await appendFile(path.join(pool, EVENTS), JSON.stringify({ at: Date.now(), kind: "frame", hits, misses }) + "\n").catch(() => {}); } // ---- the pool as a whole: stats, prune, verify ------------------------------- /** Every object: `{ kind, path, bytes, onlyPool, used }` (`onlyPool`: the bytes no take links). */ export async function poolObjects(pool) { const out = []; for (const kind of Object.keys(POOL_KINDS)) { const kdir = path.join(pool, kind); for (const shard of await readdir(kdir).catch(() => [])) { if (shard.startsWith(".")) continue; const sdir = path.join(kdir, shard); const sst = await stat(sdir).catch(() => null); if (!sst?.isDirectory()) continue; for (const name of await readdir(sdir).catch(() => [])) { const p = path.join(sdir, name); const st = await lstat(p).catch(() => null); if (!st) continue; if (kind === "frame") { if (!st.isFile()) continue; out.push({ kind, path: p, bytes: st.size, onlyPool: st.nlink <= 1 ? st.size : 0, linked: st.nlink > 1, used: sst.mtimeMs }); continue; } if (!st.isDirectory()) continue; let bytes = 0; let only = 0; let linked = false; for (const f of await readdir(p).catch(() => [])) { const fs = await lstat(path.join(p, f)).catch(() => null); if (!fs?.isFile()) continue; bytes += fs.size; if (f === META || fs.nlink <= 1) only += fs.size; else linked = true; } out.push({ kind, path: p, bytes, onlyPool: linked ? 0 : only, linked, used: st.mtimeMs }); } } } return out; } /** The cap on the bytes only the pool holds: `UMTOOL_RENDER_POOL_MAX_GB`, else the default. */ export function poolMaxBytes(env = process.env) { const gb = Number(env.UMTOOL_RENDER_POOL_MAX_GB); return (Number.isFinite(gb) && gb >= 0 ? gb : POOL_MAX_GB_DEFAULT) * 1024 ** 3; } /** * Size, what only the pool holds, hits and misses per kind (from the events, * `since` ms), the biggest objects. */ export async function poolStats(pool, { since = 0, top = 10 } = {}) { const objs = await poolObjects(pool); const kinds = {}; for (const k of Object.keys(POOL_KINDS)) kinds[k] = { objects: 0, bytes: 0, onlyPool: 0, hits: 0, misses: 0 }; for (const o of objs) { kinds[o.kind].objects += 1; kinds[o.kind].bytes += o.bytes; kinds[o.kind].onlyPool += o.onlyPool; } const text = await readFile(path.join(pool, EVENTS), "utf8").catch(() => ""); for (const line of text.split("\n")) { if (!line) continue; let e; try { e = JSON.parse(line); } catch { continue; } if (!kinds[e.kind] || e.at < since) continue; if (Number.isFinite(e.hits)) { kinds[e.kind].hits += e.hits; kinds[e.kind].misses += e.misses ?? 0; } else if (e.hit) kinds[e.kind].hits += 1; else kinds[e.kind].misses += 1; } const bytes = objs.reduce((n, o) => n + o.bytes, 0); const onlyPool = objs.reduce((n, o) => n + o.onlyPool, 0); const biggest = [...objs].sort((a, b) => b.bytes - a.bytes).slice(0, top).map((o) => ({ kind: o.kind, path: o.path, bytes: o.bytes, linked: o.onlyPool === 0 })); return { pool, objects: objs.length, bytes, onlyPool, maxOnlyPool: poolMaxBytes(), kinds, biggest }; } /** * Evict least-recently-used objects that no take links until the bytes only * the pool holds are under `maxBytes`; tmp directories over a day old go too. * `dryRun` says what would go. */ export async function poolPrune(pool, { maxBytes = poolMaxBytes(), dryRun = false } = {}) { const objs = await poolObjects(pool); let only = objs.reduce((n, o) => n + o.onlyPool, 0); const before = only; const gone = []; // An object a take links (any file with a second name) is never a candidate. const free = objs.filter((o) => !o.linked).sort((a, b) => a.used - b.used); for (const o of free) { if (only <= maxBytes) break; if (!dryRun) await rm(o.path, { recursive: true, force: true }); only -= o.onlyPool; gone.push({ kind: o.kind, path: o.path, bytes: o.bytes }); } for (const kind of Object.keys(POOL_KINDS)) { for (const name of await readdir(path.join(pool, kind)).catch(() => [])) { if (!name.startsWith(".tmp-")) continue; const p = path.join(pool, kind, name); const st = await stat(p).catch(() => null); if (st && Date.now() - st.mtimeMs > 86_400_000 && !dryRun) await rm(p, { recursive: true, force: true }); } } return { before, after: only, maxBytes, evicted: gone.length, bytes: gone.reduce((n, o) => n + o.bytes, 0), gone }; } /** * Check a sample of objects: each unit's files against the sha256 its meta * recorded, each frame a PNG. Returns the problems (and removes nothing). */ export async function poolVerify(pool, { sample = 50, all = false } = {}) { const objs = await poolObjects(pool); const pick = all ? objs : [...objs].sort(() => Math.random() - 0.5).slice(0, sample); const problems = []; for (const o of pick) { if (o.kind === "frame") { const head = await readFile(o.path).then((b) => b.subarray(0, 8).toString("hex"), () => null); if (head !== "89504e470d0a1a0a") problems.push(`${o.path}: not a PNG`); continue; } const meta = await readFile(path.join(o.path, META), "utf8").then((t) => JSON.parse(t), () => null); if (!meta) { problems.push(`${o.path}: no ${META}`); continue; } for (const [n, f] of Object.entries(meta.files ?? {})) { const got = await fileSha(path.join(o.path, n)).catch(() => null); if (got !== f.sha256) problems.push(`${o.path}/${n}: ${got ? "its bytes are not the ones put in" : "missing"}`); } } return { checked: pick.length, of: objs.length, problems }; } /** Prune at most once an hour per pool (the end of a build calls this). */ export async function poolPruneThrottled(pool, env = process.env) { if (!pool) return null; const mark = path.join(pool, ".pruned"); const st = await stat(mark).catch(() => null); if (st && Date.now() - st.mtimeMs < 3_600_000) return null; await mkdir(pool, { recursive: true }).catch(() => {}); await writeFile(mark, new Date().toISOString() + "\n").catch(() => {}); return poolPrune(pool, { maxBytes: poolMaxBytes(env) }).catch(() => null); }