/** * The photo prune (owner, 21 Nov 2026): bins the photo records whose original * the bucket does not hold, one key folder at a time, so the phones stop * asking for pictures that never came up (most of the WhatsApp pictures an * import named). It BINS — `trashed_at`, the mark delete_record sets — so * restore_from_bin brings any of them back whole; it never erases. * * `POST /v1/admin/photos/prune { folder, after?, limit?, apply? }`, bounded: * one call reads at most `limit` photo rows (at most 500) after `after` in id * order, asks the bucket about those of the folder 25 at a time, and answers * `next` (null at the end) to ask again with. Without `apply` it only counts. * * A photo's folder is its key's segment after the database id * (`<db>/photos/<sha>.jpg` is `photos`, `<db>/messages/<thread>/<sha>.jpg` is * `messages`). * * What refers to a photo is left as it is, so a photo brought back from the * bin is whole again — and counted, so the owner sees it: * - a sighting (`photo_id`: where it was seen, the chat it came with), a face * (`photo_id`), an album entry (`record_id`), a duplicate pair (`keep_id`, * `copy_id`) are counted by kind; * - a photo that is a person's avatar (`avatar_photo_id`) or an event's * picture (`picture_photo_id`) is NOT binned — it is in use where the person * put it — and counted as `kept_in_use`; * - a message's attachment list is in its sealed body: the server cannot see * it, so a message keeps naming its picture and a phone keeps its own * memory of keys the object answered 404 for. */importtype { Engine, Outcome } from"./engine.ts";import { refuse } from"./http.ts";importtype { Store } from"./store.ts";exportconst PRUNE_MOST = 500;/** What one call reads when it names no limit: a page of bins stays one short transaction. */exportconst PRUNE_PAGE = 200;const HEAD_AT_ONCE = 25;exportinterfacePruneAnswer { folder: string; applied: boolean;/** Photo rows read this call, of any folder; and those of the folder, not binned already. */ read: number; in_folder: number;/** Of those, the ones whose original the bucket lacks. */ missing: number; binned: number; kept_in_use: number;/** What refers to the missing photos, by kind, left as it is. */ referred: { sighting: number; face: number; album_item: number; duplicate: number }; next: string | null;}/** The segment of a media key after its database id, or null for a key of another shape. */exportfunction folderOf(key: unknown, database: string): string | null {if (typeof key !== "string" || !key.startsWith(`${database}/`)) returnnull;const rest = key.slice(database.length + 1);const at = rest.indexOf("/");return at > 0 ? rest.slice(0, at) : null;}/** The bucket's own key of a row's media key (`<slug>/<rest>`, as src/media.ts bucketKey stores it). */function stored(key: string, database: string, slug: string): string {return`${slug}/${key.slice(database.length + 1)}`;}function linked(store: Store, table: string, column: string, ids: string[]): number {if (!ids.length) return0;return store.countLinks(table, column, ids);}exportinterfacePruneDeps { store: Store; bucket: R2Bucket; database: string; slug: string;/** Runs one write of the call's bins, in one transaction and one version. */ write: (fn: (engine: Engine, version: number, outcome: Outcome) => void) => void; now: string;}exportasyncfunction prunePhotos(deps: PruneDeps, args: Record<string, unknown>): Promise<PruneAnswer> {const { store, database } = deps;const folder = args.folder;if (typeof folder !== "string" || !/^[a-z0-9_-]+$/.test(folder)) refuse(400, "bad_request", "folder is a key folder: photos, messages, …");const after = args.after === undefined || args.after === null ? "" : args.after;if (typeof after !== "string") refuse(400, "bad_request", "after is the next an earlier call answered");const limit = args.limit === undefined ? PRUNE_PAGE : args.limit;if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1 || limit > PRUNE_MOST) refuse(400, "bad_request", `limit is 1 to ${PRUNE_MOST}`);const apply = args.apply === true;// The page's keys and bin marks alone: a photo's body (embeddings, a preview) is never read for a count.const rows = store.slimPage("photo", after, limit, ["key", "trashed_at"]);const mine = rows.filter((row) => folderOf(row.data.key, database) === folder && !binned(row));const missing: { id: string; data: Record<string, unknown> }[] = [];for (let i = 0; i < mine.length; i += HEAD_AT_ONCE) {const batch = mine.slice(i, i + HEAD_AT_ONCE);const held = awaitPromise.all(batch.map((row) => deps.bucket.head(stored(String(row.data.key), database, deps.slug)))); batch.forEach((row, j) => held[j] || missing.push(row)); }const ids = missing.map((row) => row.id);const inUse = newSet([...store.linkSources("person", "avatar_photo_id", ids), ...store.linkSources("event", "picture_photo_id", ids)]);const going = missing.filter((row) => !inUse.has(row.id));const goingIds = going.map((row) => row.id);const referred = { sighting: linked(store, "sighting", "photo_id", goingIds), face: linked(store, "face", "photo_id", goingIds), album_item: store.countWhereIn("album_item", ["record_id"], goingIds), duplicate: store.countWhereIn("duplicate", ["keep_id", "copy_id"], goingIds), };if (apply && going.length) { deps.write((engine, version, outcome) => {for (const row of going) {const now = store.get("photo", row.id);if (now && !binned(now)) engine.update(now, { trashed_at: deps.now }, version, outcome); } }); }return { folder, applied: apply, read: rows.length, in_folder: mine.length, missing: missing.length, binned: apply ? going.length : 0, kept_in_use: missing.length - going.length, referred, next: rows.length === limit ? rows[rows.length - 1]!.id : null, };}function binned(row: { data: Record<string, unknown> }): boolean {returntypeof row.data.trashed_at === "string" && row.data.trashed_at !== "";}