Cotton code
89 lines · 5.2 KB · TypeScriptRaw
import { env, runInDurableObject, SELF } from "cloudflare:test";import { describe, expect, it } from "vitest";import type { Business } from "../src/business.ts";import { ADMIN, DATABASE_ID, http, personalObject, put } from "./personal.ts";const PNG = Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAACAAAAAYCAIAAAAUMWhjAAAAJElEQVR4nGM4EaBBU8QwasGoBaMWjFowasGoBaMWjFowNCwAAOj5wC7/fbJHAAAAAElFTkSuQmCC"), (c) => c.charCodeAt(0));const sha = (n: number): string => n.toString(16).padStart(64, "0");interface Answer {  folder: string;  applied: boolean;  read: number;  in_folder: number;  missing: number;  binned: number;  kept_in_use: number;  referred: { sighting: number; face: number; album_item: number; duplicate: number };  next: string | null;}async function prune(slug: string, body: Record<string, unknown>): Promise<Answer> {  const res = await http<Answer>(slug, "POST", "/v1/admin/photos/prune", body, ADMIN);  expect(res.status, JSON.stringify(res.body)).toBe(200);  return res.body;}/** Every page, from the first to the last, summed. */async function whole(slug: string, body: Record<string, unknown>): Promise<Answer & { calls: number }> {  const sum = { read: 0, in_folder: 0, missing: 0, binned: 0, kept_in_use: 0, referred: { sighting: 0, face: 0, album_item: 0, duplicate: 0 }, calls: 0 };  let after: string | null = null;  let last: Answer;  do {    last = await prune(slug, { ...body, after });    sum.calls++;    for (const k of ["read", "in_folder", "missing", "binned", "kept_in_use"] as const) sum[k] += last[k];    for (const k of Object.keys(sum.referred) as (keyof Answer["referred"])[]) sum.referred[k] += last.referred[k];    after = last.next;  } while (after !== null);  return { ...last, ...sum };}/** RULE (owner, 21 Nov 2026): the photo records of WhatsApp pictures that never came up go to the bin, one key folder at a time, so the phones stop asking; a photo he took himself is never touched by a prune of another folder, and nothing is erased. */describe("the photo prune", () => {  const slug = "photo-prune";  it("counts, then bins only the missing photos of the folder named, a page at a time, leaving what refers to them", async () => {    const { credential } = await personalObject(slug);    // One picture of a chat is in the bucket (laid by the owner's phone: a token writes no chat file); the chat's others    // are not, nor are the library's own photos.    const held = `${DATABASE_ID}/messages/thread-a/${sha(1)}.png`;    const res = await SELF.fetch(`https://example.test/b/${slug}/v1/media/${held}`, { method: "PUT", headers: { authorization: `Bearer ${credential}`, "content-type": "image/png", "content-length": String(PNG.length) }, body: PNG });    expect(res.status, await res.clone().text()).toBe(201);    const rows: Record<string, unknown>[] = [];    for (let i = 1; i <= 12; i++) rows.push({ ref: `m${i}`, table: "photo", data: { key: `${DATABASE_ID}/messages/thread-a/${sha(i)}.png`, sha256: sha(i), taken_at: "2024-03-01T10:00:00Z" } });    for (let i = 100; i < 105; i++) rows.push({ ref: `p${i}`, table: "photo", data: { key: `${DATABASE_ID}/photos/${sha(i)}.jpg`, sha256: sha(i), taken_at: "2025-01-01T10:00:00Z" } });    rows.push({ table: "sighting", data: { record_kind: "photo", record_id: "@m2", source: "whatsapp", source_id: "s2", photo_id: "@m2" } });    rows.push({ table: "face", data: { record_kind: "photo", record_id: "@m3", source: "apple", source_id: "f3", x: 0.1, y: 0.1, w: 0.2, h: 0.2, photo_id: "@m3" } });    rows.push({ table: "person", data: { full_name: "Asha", avatar_photo_id: "@m4" } });    const ids = await put(slug, rows);    const dry = await whole(slug, { folder: "messages", limit: 5 });    expect(dry.calls, "17 photos five a page").toBe(4);    expect(dry).toMatchObject({ applied: false, read: 17, in_folder: 12, binned: 0 });    const heldNow = 1;    expect(dry.missing).toBe(12 - heldNow);    expect(dry.kept_in_use, "a person's avatar is in use").toBe(1);    expect(dry.referred.sighting).toBe(1);    expect(dry.referred.face).toBe(1);    const photo = (ref: string): Promise<Record<string, unknown>> =>      runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (instance: Business) => (instance as unknown as { store: { get(t: string, id: string): { data: Record<string, unknown> } | null } }).store.get("photo", ids[ref]!)?.data ?? {});    expect((await photo("m5")).trashed_at ?? null, "a dry run bins nothing").toBeNull();    const applied = await whole(slug, { folder: "messages", limit: 5, apply: true });    expect(applied.binned).toBe(12 - heldNow - 1);    expect(typeof (await photo("m5")).trashed_at).toBe("string");    expect((await photo("m4")).trashed_at ?? null, "the avatar stays").toBeNull();    expect((await photo("p100")).trashed_at ?? null, "the library's own photo is another folder's").toBeNull();    expect((await photo("m1")).trashed_at ?? null, "a picture the bucket holds stays").toBeNull();    const again = await whole(slug, { folder: "messages", apply: true });    expect(again.binned, "a binned photo is not binned again").toBe(0);  });  it("refuses a folder that is not one", async () => {    const res = await http(slug, "POST", "/v1/admin/photos/prune", { folder: "../x" }, ADMIN);    expect(res.status).toBe(400);  });});