// THE PURGE OF DROPPED POSTS' CAPTURES (lane posts-library): the one door to // removeXTrendingPostCaptures (lib/xTrending/mediaStore.ts). // // WHAT IS TAKEN: the captures (trending/posts-media//) of posts whose // judgement IN FORCE is drop BY THE OPERATOR — their own entry, or their // thread's — in one topic or the whole library, or of the ids named among // them. AN AGENT'S DROP IS A SUGGESTION AND IS NEVER PURGED: those posts are // counted (`agentDropped`) and left alone. Never a post marked later, kept or // undecided. A blob another post still carries is left; the judgements, the // posts and the reads stay; what a media address was found over the cap is // not forgotten. // // A POST GONE FROM THE PAGE IS SAID SO. For a post a trending page no longer // shows, the capture is the only copy the library has, and keeping the post // again may capture nothing: the answer names those posts (`gone`) and its // sentence says the removal cannot be undone. "Keeping it again captures it // again" is said only of the others. // // TWO STEPS. A dry run counts what would go and answers `confirm`, a digest of // the library's slug and the exact ids. The removal must carry that digest: if // the set has changed since (a post dropped or kept, a capture added), it is // refused and nothing is removed, so what goes is what was shown. THE SET IS // READ AGAIN INSIDE THE MEDIA INDEX'S LOCK, immediately before the first file // goes: a judgement written between the check and the removal refuses it too. // // Refused while a capture of the library is queued or running (the caller // answers that from its job registry). SERVER-ONLY (node:fs). import { createHash } from "node:crypto"; import { stat } from "node:fs/promises"; import path from "node:path"; import { removeXTrendingPostCaptures } from "./mediaStore"; import { listXTrending, readXTrendingMembership, xTrendingPostsMediaDir } from "./store"; export const X_TRENDING_PURGE_MAX_IDS = 5000; export type XTrendingPurgeAsk = { slug: string; topic?: string; ids?: ReadonlyArray; dryRun: boolean; confirm?: string; captureInFlight: () => boolean | Promise; }; export type XTrendingPurgeResult = { dryRun: boolean; // The posts the operator dropped that have a capture: what is (or would be) removed. posts: number; ids: string[]; files: number; // Everything freed: the blobs no other post carries, and the captures' own // files (shots, records). bytes: number; blobsFreed: number; // Blobs another post still carries: left alone. blobsKept: number; // Of `ids`, the posts gone from the page, with when a page stopped showing // each: their capture is the only copy. gone: Array<{ id: string; at: string }>; // Posts of the scope an AGENT dropped that have a capture: never removed. agentDropped: number; // Ids named that are not posts the operator dropped, in the scope. skipped: Array<{ id: string; reason: string }>; confirm: string; // A dry run only: a capture of the library is queued or running, so the // removal would be refused now. captureInFlight?: boolean; sentence: string; }; export function xTrendingPurgeConfirm(slug: string, ids: ReadonlyArray): string { return createHash("sha256").update(JSON.stringify([slug, [...ids].sort()])).digest("hex").slice(0, 16); } export function formatPurgeBytes(n: number): string { if (n < 1024) return `${n} B`; if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`; if (n < 1024 * 1024 * 1024) return `${(n / (1024 * 1024)).toFixed(1)} MB`; return `${(n / (1024 * 1024 * 1024)).toFixed(2)} GB`; } export const PURGE_SET_CHANGED = (now: number) => `The dropped posts with a capture have changed since the dry run (${now} now): nothing was removed. Run the dry run again and confirm what it shows.`; const when = (iso: string) => { const d = new Date(iso); return Number.isNaN(d.getTime()) ? iso : `${d.toISOString().slice(0, 10)} ${d.toISOString().slice(11, 16)} UTC`; }; const n = (k: number, one: string, many = `${one}s`) => `${k} ${k === 1 ? one : many}`; // What the answer says, in one place: the page, `pnpm ops` and `umtool // library` print it as it is. export function purgeSentence(r: Pick): string { const agent = r.agentDropped ? ` ${n(r.agentDropped, "post")} an agent dropped ${r.agentDropped === 1 ? "is" : "are"} left alone: a purge takes the operator's drops only.` : ""; if (r.posts === 0) return `No post the operator dropped has a capture: nothing to remove.${agent}`; const what = `the capture${r.posts === 1 ? "" : "s"} of ${n(r.posts, "dropped post")}: ${n(r.files, "file")}, ${formatPurgeBytes(r.bytes)}`; const kept = r.blobsKept ? ` ${n(r.blobsKept, "media file")} another post still uses ${r.blobsKept === 1 ? "is" : "are"} left.` : ""; const g = r.gone.length; const others = r.posts - g; if (!r.dryRun) { const lost = g ? ` ${g === r.posts ? (g === 1 ? "It was" : "They were") : `${g} of them ${g === 1 ? "was" : "were"}`} gone from the page: ${g === 1 ? "that copy" : "those copies"} cannot be had again.` : ""; return `Removed ${what}.${kept} The judgements stay.${lost}${agent}`; } const first = [...r.gone].sort((a, b) => (a.at < b.at ? -1 : 1))[0]; const only = g === 0 ? "" : g === 1 ? ` ${r.posts === 1 ? "It is" : "1 of them is"} gone from the page: this is the only copy: X no longer showed this post at ${when(first.at)}; removing it cannot be undone.` : ` ${g === r.posts ? "They are" : `${g} of them are`} gone from the page: these are the only copies: X no longer showed these posts (the first at ${when(first.at)}); removing them cannot be undone.`; const again = others === 0 ? "" : g === 0 ? ` Keeping ${r.posts === 1 ? "it" : "one of them"} again captures it again.` : ` Keeping ${others === 1 ? "the other one" : `one of the other ${others}`} again captures it again.`; const waits = r.captureInFlight ? " A capture of this library is queued or running: the removal waits for it." : ""; return `Would remove ${what}.${kept} The judgements stay.${only}${again}${agent}${waits}`; } export async function purgeXTrendingDropped(channelRoot: string, ask: XTrendingPurgeAsk): Promise<{ ok: true; result: XTrendingPurgeResult } | { ok: false; error: string }> { if (ask.ids && ask.ids.length > X_TRENDING_PURGE_MAX_IDS) return { ok: false, error: `"ids" holds at most ${X_TRENDING_PURGE_MAX_IDS} post ids` }; if (ask.ids && !ask.ids.every((id) => typeof id === "string" && /^\d+$/.test(id))) return { ok: false, error: `"ids" is a list of post ids` }; const scope = ask.topic ? { topic: ask.topic } : {}; const captured = async (id: string) => (await stat(path.join(xTrendingPostsMediaDir(channelRoot), id)).catch(() => null))?.isDirectory() === true; // THE SET, read from the judgements as they stand: asked for the count, and // again inside the lock before a file goes. const read = async () => { const [mine, agents, membership] = await Promise.all([ listXTrending(channelRoot, { ...scope, ids: true, filter: { state: "drop", by: "operator" } }), listXTrending(channelRoot, { ...scope, ids: true, filter: { state: "drop", by: "agent" } }), readXTrendingMembership(channelRoot), ]); const dropped = new Set(mine.ids ?? []); const byAgent = new Set(agents.ids ?? []); const skipped: XTrendingPurgeResult["skipped"] = []; let wanted = [...dropped]; if (ask.ids) { wanted = []; for (const id of new Set(ask.ids)) { if (dropped.has(id)) wanted.push(id); else skipped.push({ id, reason: byAgent.has(id) ? "an agent dropped it: a purge takes the operator's drops only" : ask.topic ? "not a post the operator dropped in that topic" : "not a post the operator dropped" }); } } const ids: string[] = []; for (const id of wanted) if (await captured(id)) ids.push(id); ids.sort(); let agentDropped = 0; for (const id of byAgent) if ((!ask.ids || ask.ids.includes(id)) && (await captured(id))) agentDropped++; const gone = ids.flatMap((id) => (membership[id]?.gone ? [{ id, at: membership[id].gone!.at }] : [])); return { ids, skipped, agentDropped, gone }; }; const set = await read(); const confirm = xTrendingPurgeConfirm(ask.slug, set.ids); if (!ask.dryRun && ask.confirm !== confirm) return { ok: false, error: PURGE_SET_CHANGED(set.ids.length) }; const inFlight = ask.dryRun ? await ask.captureInFlight() : false; let removed; try { removed = await removeXTrendingPostCaptures(channelRoot, set.ids, { captureInFlight: ask.captureInFlight, dryRun: ask.dryRun, guard: async () => { const now = await read(); return xTrendingPurgeConfirm(ask.slug, now.ids) === confirm ? null : PURGE_SET_CHANGED(now.ids.length); }, }); } catch (err) { return { ok: false, error: (err as Error).message }; } const result: Omit = { dryRun: ask.dryRun, posts: set.ids.length, ids: set.ids, files: removed.files, bytes: removed.bytesFreed + removed.ownBytes, blobsFreed: removed.blobsFreed, blobsKept: removed.blobsKept, gone: set.gone, agentDropped: set.agentDropped, skipped: set.skipped, confirm, ...(ask.dryRun && inFlight ? { captureInFlight: true as const } : {}), }; return { ok: true, result: { ...result, sentence: purgeSentence(result) } }; }