// A hard link where the filesystem allows one, else a copy. // // Identical frames are deduplicated onto one inode (a cut's blank fx frames // are ~50,000 links to a single PNG), and every take built `--from` another // links them again, so the inode reaches ext4's cap of 65,000 links within a // few takes and link() fails EMLINK -- measured 2026-10-30, the Ember cut's // draft-17 refused at its first fx frame. A link that cannot be made // becomes ONE copy per source inode: the first refusal copies the file, and // every later link of that inode in the same linker goes to the copy (a fresh // inode, with its own 65,000), so 50,000 refusals cost one file, not 50,000. // EXDEV (another filesystem) is handled the same way. // // Plain node. import { copyFile, link, stat } from "node:fs/promises"; const FALLBACK = new Set(["EMLINK", "EXDEV"]); /** * A `link(src, dst)` that copies when the link is refused for its count or * its filesystem. One linker remembers the copies it made, by source inode; * use one per batch of links (a frame directory, a take). * @returns {((src: string, dst: string) => Promise<"link" | "copy">) & { copies: () => number }} */ export function makeLinker() { /** @type {Map>} source inode -> the copy linked in its place */ const stand = new Map(); let copies = 0; const fn = async (src, dst) => { try { await link(src, dst); return "link"; } catch (err) { if (!FALLBACK.has(/** @type {any} */ (err)?.code)) throw err; } const s = await stat(src); const key = `${s.dev}:${s.ino}`; const prior = stand.get(key); if (prior) { const copy = await prior; try { await link(copy, dst); return "link"; } catch (err) { if (!FALLBACK.has(/** @type {any} */ (err)?.code)) throw err; } } // This dst becomes the stand-in: later links of the same inode go to it. const made = copyFile(src, dst).then(() => dst); stand.set(key, made); await made; copies += 1; return "copy"; }; fn.copies = () => copies; return fn; } /** One link with the fallback, for a caller with no batch to share a linker over. */ export const linkOrCopy = (src, dst) => makeLinker()(src, dst);