// A LIBRARY'S MEDIA, KEPT ONCE (lane x-trending-2). // // channels//trending/media-store//. the bytes, once // per content hash // channels//trending/posts-media// a HARDLINK to // its blob // channels//trending/media-index.json hash → bytes, // the addresses it came from, and the posts (and file names) that carry it // // EXACT DUPLICATES ONLY: two files are one when their SHA-256 is. The same // video at another quality, or a picture re-encoded, is another file. // // WHY HARDLINKS. Every reader of a capture directory (the listing's // thumbnail, the capture's own file list, umtool) opens a plain file and // needs to know nothing. Unlinking one post's name cannot touch another // post's bytes: the file system counts the links, and the bytes go when the // last one does. A file system that refuses a link (another device, a link // limit) leaves the file where it was, an ordinary copy: nothing is lost, // that file is simply not shared. // // KNOWN ADDRESS, NO FETCH. The index remembers the address each blob came // from, so a post carrying a file the library already holds is linked to it // without asking the CDN (linkXTrendingMedia). // // NOT IN THE MEDIA TIER. The tier (lib/mediaTier.ts) is by name over a video // dir, `data//`; no posts channel's `posts-media/` is in it, and a // library's is not either: it stays on the corpus disk beside the library's // text, like `clips/`. So nothing here is a link out of the channel, and // removeMediaFile (the one `rm` of a media file) removes these names as the // plain files they are. // // NEVER COMMITTED. `trending/.gitignore` keeps `posts-media/` and // `media-store/` out of the corpus's own git repo: hardlinks do not survive // git, and the bytes are big. The index is small text and is not ignored. // // THIS MODULE IS THE ONE WRITER of media-index.json and of the store; every // write is under the index's lock. SERVER-ONLY (node:fs). import path from "node:path"; import { link, lstat, mkdir, readFile, readdir, rename, rm, rmdir, stat } from "node:fs/promises"; import { readJsonFile, withJsonFileLock, writeFileAtomic, writeJsonAtomic } from "../jsonFile-server"; import { removeMediaFile } from "../mediaTier-server"; import { fileDigest, postCaptureDir } from "../../social/postCapture"; import { trendingDir, xTrendingPostsMediaDir } from "./store"; export const X_TRENDING_MEDIA_STORE_DIRNAME = "media-store"; export const X_TRENDING_MEDIA_INDEX_FILENAME = "media-index.json"; export function xTrendingMediaStoreDir(channelRoot: string): string { return path.join(trendingDir(channelRoot), X_TRENDING_MEDIA_STORE_DIRNAME); } export function xTrendingMediaIndexPath(channelRoot: string): string { return path.join(trendingDir(channelRoot), X_TRENDING_MEDIA_INDEX_FILENAME); } export const TRENDING_MEDIA_GITIGNORE = "# A library's captured media: hardlinked, big, never committed.\nposts-media/\nmedia-store/\n"; // trending/, with the .gitignore that keeps the media out of the corpus repo. export async function ensureXTrendingMediaIgnore(channelRoot: string): Promise { const dir = trendingDir(channelRoot); await mkdir(dir, { recursive: true }); const file = path.join(dir, ".gitignore"); const have = await readFile(file, "utf8").catch(() => null); if (have !== TRENDING_MEDIA_GITIGNORE) await writeFileAtomic(file, TRENDING_MEDIA_GITIGNORE); } export type XTrendingMediaBlob = { bytes: number; ext: string; addedAt: string; // The addresses this content came from (a file's identity address, as the // capture names it), oldest first. urls: string[]; // Post id → its file names that are this blob. posts: Record; }; export type XTrendingMediaIndex = { version: 1; blobs: Record; // Addresses whose file was found larger than a cap, and how large (the // cap + 1 when it was cut off mid-stream): not asked for again while the // cap stands, so a watch does not start the same big download every tick. oversize: Record; }; const SHA = /^[0-9a-f]{64}$/; const POST_ID = /^\d{1,25}$/; // A media file's name inside a capture directory: no path, no dotfile. const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,120}$/; function parseIndex(raw: unknown): XTrendingMediaIndex { const blobs = (raw as { blobs?: unknown } | null)?.blobs; const out: XTrendingMediaIndex = { version: 1, blobs: {}, oversize: {} }; const oversize = (raw as { oversize?: unknown } | null)?.oversize; if (oversize && typeof oversize === "object" && !Array.isArray(oversize)) { for (const [url, o] of Object.entries(oversize as Record)) { if (!o || typeof o !== "object" || !(Number(o.bytes) > 0)) continue; out.oversize[url] = { bytes: Number(o.bytes), at: typeof o.at === "string" ? o.at : "" }; } } if (!blobs || typeof blobs !== "object" || Array.isArray(blobs)) return out; for (const [sha, b] of Object.entries(blobs as Record | null>)) { if (!SHA.test(sha) || !b || typeof b !== "object") continue; const posts: Record = {}; for (const [id, names] of Object.entries(b.posts && typeof b.posts === "object" ? b.posts : {})) { if (!POST_ID.test(id) || !Array.isArray(names)) continue; const kept = names.filter((n): n is string => typeof n === "string" && NAME.test(n)); if (kept.length > 0) posts[id] = kept; } out.blobs[sha] = { bytes: Number(b.bytes) || 0, ext: typeof b.ext === "string" && /^[a-z0-9]{1,5}$/.test(b.ext) ? b.ext : "bin", addedAt: typeof b.addedAt === "string" ? b.addedAt : "", urls: Array.isArray(b.urls) ? b.urls.filter((u): u is string => typeof u === "string" && u !== "") : [], posts, }; } return out; } // The index exists and cannot be read as one. export class XTrendingMediaIndexError extends Error { constructor(file: string, why: string) { super( `The library's media index (${file}) ${why}. Nothing was written: an index read as empty would be written back over the record of ` + "every file the library holds. Repair the file, or move it away (the store's files stay; captures made after that are indexed afresh).", ); this.name = "XTrendingMediaIndexError"; } } // The index — an EMPTY one only when there is no file yet. A file that is // there and cannot be read or parsed THROWS (review 1 S8): every writer here // reads, changes and writes back, and "unreadable" taken for "empty" would // replace the whole record with the one entry being added. The capture job // fails with the sentence, naming the file. export async function readXTrendingMediaIndex(channelRoot: string): Promise { const file = xTrendingMediaIndexPath(channelRoot); const read = await readJsonFile(file); if (!read.ok) { if (read.reason === "absent") return { version: 1, blobs: {}, oversize: {} }; throw new XTrendingMediaIndexError(file, read.reason === "unparseable" ? "is not JSON (cut short, or edited by hand)" : "cannot be read"); } if (!read.value || typeof read.value !== "object" || Array.isArray(read.value)) { throw new XTrendingMediaIndexError(file, "is not a media index (not an object)"); } return parseIndex(read.value); } // The blob that came from this address, or undefined. export function xTrendingBlobByUrl(index: XTrendingMediaIndex, url: string): string | undefined { for (const [sha, b] of Object.entries(index.blobs)) if (b.urls.includes(url)) return sha; return undefined; } function extOf(name: string): string { const ext = path.extname(name).slice(1).toLowerCase(); return /^[a-z0-9]{1,5}$/.test(ext) ? ext : "bin"; } function blobPath(channelRoot: string, sha: string, ext: string): string { return path.join(xTrendingMediaStoreDir(channelRoot), sha.slice(0, 2), `${sha}.${ext}`); } function checked(postId: string, name: string): void { if (!POST_ID.test(postId)) throw new Error(`"${postId}" is not a post id`); if (!NAME.test(name)) throw new Error(`"${name}" is not a media file's name`); } // `target` linked at `file`, replacing what is there, atomically (a link // beside it, renamed over it). False when the file system refuses the link. async function linkOver(target: string, file: string): Promise { const tmp = path.join(path.dirname(file), `.${path.basename(file)}.link-${process.pid}`); await rm(tmp, { force: true }); try { await link(target, tmp); } catch (err) { const code = (err as NodeJS.ErrnoException).code; if (code === "EXDEV" || code === "EPERM" || code === "EMLINK" || code === "ENOTSUP") return false; throw err; } await rename(tmp, file); return true; } // Link temps a crash left in a capture directory (`..link-`): // removed under the index's lock, where no link of this process is in flight. async function sweepLinkTemps(dir: string): Promise { const names = await readdir(dir).catch(() => [] as string[]); for (const name of names) if (/^\..+\.link-\d+$/.test(name)) await rm(path.join(dir, name), { force: true }); } const sameFile = (a: { dev: number; ino: number }, b: { dev: number; ino: number }) => a.dev === b.dev && a.ino === b.ino; function note(blob: XTrendingMediaBlob, postId: string, name: string, url?: string): void { const names = (blob.posts[postId] ??= []); if (!names.includes(name)) names.push(name); if (url && !blob.urls.includes(url)) blob.urls.push(url); } // An address whose file is larger than a cap, remembered with its size. export async function noteXTrendingOversize( channelRoot: string, o: { url: string; bytes: number; now?: () => number }, ): Promise { await withJsonFileLock(xTrendingMediaIndexPath(channelRoot), async () => { const index = await readXTrendingMediaIndex(channelRoot); index.oversize[o.url] = { bytes: o.bytes, at: new Date((o.now ?? Date.now)()).toISOString() }; await writeJsonAtomic(xTrendingMediaIndexPath(channelRoot), index, { mkdir: true }); }); } export type AdoptedMedia = { sha256: string; bytes: number; // The library already held these bytes: this name is now a link to them. deduped: boolean; // The name shares its bytes with the store (false: the file system refused // the link, and the file stays an ordinary copy). linked: boolean; }; // A FILE JUST CAPTURED, TAKEN INTO THE STORE: hashed, and either linked to the // blob the library already holds for that content (its own bytes dropped) or // made the blob. `url` is the address it came from, when known. export async function adoptXTrendingMedia( channelRoot: string, o: { postId: string; name: string; url?: string; now?: () => number }, ): Promise { checked(o.postId, o.name); const file = path.join(postCaptureDir(xTrendingPostsMediaDir(channelRoot), o.postId), o.name); const { sha256, bytes } = await fileDigest(file); await ensureXTrendingMediaIgnore(channelRoot); return withJsonFileLock(xTrendingMediaIndexPath(channelRoot), async () => { const index = await readXTrendingMediaIndex(channelRoot); const have = index.blobs[sha256]; const ext = have?.ext ?? extOf(o.name); const blob = blobPath(channelRoot, sha256, ext); await mkdir(path.dirname(blob), { recursive: true }); await sweepLinkTemps(path.dirname(file)); const [fileStat, blobStat] = await Promise.all([stat(file), stat(blob).catch(() => null)]); let deduped = false; let linked: boolean; if (blobStat && sameFile(fileStat, blobStat)) { linked = true; } else if (blobStat && blobStat.size !== bytes) { // A blob under this hash's name that is not this size is not these // bytes (cut short, or changed under the store): never linked onto. // The file stays its own copy, and the index does not claim it. return { sha256, bytes, deduped: false, linked: false }; } else if (blobStat) { // The library holds these bytes: this name becomes a link to them. linked = await linkOver(blob, file); deduped = linked; } else { // New content (or a blob somebody removed): this file is the blob. linked = await linkOver(file, blob); } const entry = (index.blobs[sha256] ??= { bytes, ext, addedAt: new Date((o.now ?? Date.now)()).toISOString(), urls: [], posts: {}, }); note(entry, o.postId, o.name, o.url); if (o.url) delete index.oversize[o.url]; await writeJsonAtomic(xTrendingMediaIndexPath(channelRoot), index, { mkdir: true }); return { sha256, bytes, deduped, linked }; }); } // A BLOB THE LIBRARY HOLDS, GIVEN TO ANOTHER POST: `name` in the post's // capture directory becomes a link to it — no fetch, no copy. Null when the // store no longer has the blob (the caller fetches), or the link is refused. export async function linkXTrendingMedia( channelRoot: string, o: { postId: string; name: string; sha256: string; url?: string }, ): Promise<{ bytes: number } | null> { checked(o.postId, o.name); if (!SHA.test(o.sha256)) return null; return withJsonFileLock(xTrendingMediaIndexPath(channelRoot), async () => { const index = await readXTrendingMediaIndex(channelRoot); const entry = index.blobs[o.sha256]; if (!entry) return null; const blob = blobPath(channelRoot, o.sha256, entry.ext); const blobStat = await stat(blob).catch(() => null); if (!blobStat?.isFile()) return null; // The index's size for it, or it is not the file the index means. if (entry.bytes > 0 && blobStat.size !== entry.bytes) return null; const dir = postCaptureDir(xTrendingPostsMediaDir(channelRoot), o.postId); await mkdir(dir, { recursive: true }); await sweepLinkTemps(dir); if (!(await linkOver(blob, path.join(dir, o.name)))) return null; note(entry, o.postId, o.name, o.url); await writeJsonAtomic(xTrendingMediaIndexPath(channelRoot), index, { mkdir: true }); return { bytes: blobStat.size }; }); } export type RemovedCapture = { // Names removed from the post's capture directory. files: number; // Blobs no other post carried, removed with it, and their size. blobsFreed: number; bytesFreed: number; // Blobs this post carried that another post still does: left alone. blobsKept: number; }; // ONE POST'S CAPTURE, REMOVED: its directory's files (through removeMediaFile) // and the directory; and each blob it carried, ONLY when no other post carries // it and nothing else links to it. Media another post still uses is never // deleted: its bytes stay under that post's name and in the store. // (Its door is the purge of dropped posts: lib/xTrending/purge.ts.) // // REFUSED WHILE A CAPTURE OF THE LIBRARY IS QUEUED OR RUNNING (`captureInFlight`, // which the caller answers from its job registry — required, so no door can // forget it): a capture writes these same directories outside the lock. export const CAPTURE_IN_FLIGHT = "A capture of this library is queued or running: remove a post's capture once it has finished (its job is on /jobs)."; export async function removeXTrendingPostCapture( channelRoot: string, postId: string, o: { captureInFlight: () => boolean | Promise }, ): Promise { const { files, blobsFreed, bytesFreed, blobsKept } = await removeXTrendingPostCaptures(channelRoot, [postId], o); return { files, blobsFreed, bytesFreed, blobsKept }; } // SEVERAL POSTS' CAPTURES, REMOVED TOGETHER (lane posts-library: the purge of // dropped posts) — or, with `dryRun`, COUNTED AND NOT TOUCHED, by the same // walk, so what a dry run says is what the removal does. Taken together // because a blob two of these posts share, and no other, goes with them: one // post at a time would call it kept twice. // // posts of the ids, those with a capture directory // ownBytes the bytes of their files that are no blob's link (a shot, the // record): freed with the directory // bytesFreed the blobs no other post carries and nothing else links to export type RemovedCaptures = RemovedCapture & { posts: number; ownBytes: number }; export async function removeXTrendingPostCaptures( channelRoot: string, postIds: ReadonlyArray, o: { captureInFlight: () => boolean | Promise; dryRun?: boolean; // Asked INSIDE the index's lock, immediately before the first file goes // (never on a dry run): a sentence refuses the removal, and nothing is // touched. The purge re-reads the judgements here, so a post kept between // the count and the removal is not removed. guard?: () => Promise; }, ): Promise { for (const postId of postIds) if (!POST_ID.test(postId)) throw new Error(`"${postId}" is not a post id`); const dry = o.dryRun === true; if (!dry && (await o.captureInFlight())) throw new Error(CAPTURE_IN_FLIGHT); const ids = new Set(postIds); return withJsonFileLock(xTrendingMediaIndexPath(channelRoot), async () => { const out: RemovedCaptures = { posts: 0, files: 0, ownBytes: 0, blobsFreed: 0, bytesFreed: 0, blobsKept: 0 }; // The index FIRST: one that cannot be read stops this before a file goes. const index = await readXTrendingMediaIndex(channelRoot); if (!dry && o.guard) { const refused = await o.guard(); if (refused) throw new Error(refused); } // How many names of these captures link to each inode (a dry run takes // them off a blob's link count, as the removal would). const links = new Map(); for (const postId of ids) { const dir = postCaptureDir(xTrendingPostsMediaDir(channelRoot), postId); const names = await readdir(dir).catch(() => null); if (names === null) continue; out.posts++; for (const name of names) { const st = await lstat(path.join(dir, name)).catch(() => null); if (!st) continue; if (st.isDirectory()) { if (!dry) await rm(path.join(dir, name), { recursive: true, force: true }); } else { links.set(st.ino, (links.get(st.ino) ?? 0) + 1); if (st.nlink <= 1) out.ownBytes += st.size; if (!dry) await removeMediaFile(dir, name); } out.files++; } if (!dry) await rmdir(dir).catch(() => {}); } let changed = false; for (const [sha, entry] of Object.entries(index.blobs)) { if (!Object.keys(entry.posts).some((p) => ids.has(p))) continue; const others = Object.keys(entry.posts).filter((p) => !ids.has(p)).length; if (!dry) { for (const p of Object.keys(entry.posts)) if (ids.has(p)) delete entry.posts[p]; changed = true; } if (others > 0) { out.blobsKept++; continue; } const blob = blobPath(channelRoot, sha, entry.ext); const st = await stat(blob).catch(() => null); // A link the index does not know of (a name copied by hand, an index // that lost a post): the bytes are still somebody's, so the blob stays. const left = st ? (dry ? st.nlink - (links.get(st.ino) ?? 0) : st.nlink) : 0; if (st && left > 1) { out.blobsKept++; continue; } if (st) { if (!dry) { await rm(blob, { force: true }); await rmdir(path.dirname(blob)).catch(() => {}); } out.bytesFreed += st.size; } if (!dry) delete index.blobs[sha]; out.blobsFreed++; } if (changed) await writeJsonAtomic(xTrendingMediaIndexPath(channelRoot), index, { mkdir: true }); return out; }); }