Cotton code
244 lines · 15.1 KB · TypeScriptRaw
/** * The artwork engine (src/artwork.ts): a book's cover from Open Library, a * film's poster from Wikidata and Commons, kept as the object's media and * named in the row — through a fetch stubbed here, so a case says exactly * what each source answered and counts what was asked. */import { env, runInDurableObject, SELF } from "cloudflare:test";import { describe, expect, it } from "vitest";import { RETRY_MS, type Fetcher } from "../src/artwork.ts";import type { Business } from "../src/business.ts";import { Store } from "../src/store.ts";import { openArrivalFile } from "./arrival_keys.ts";import { ADMIN, DATABASE_ID, http, personalObject, PERSONAL_TABLES, PERSONAL_TOOLS, BOOKS_OPEN, FILMS_OPEN } from "./personal.ts";const stub = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug));/** A real 1×1 JPEG's bytes, and a PNG's, as a source would answer them. */const JPEG = Uint8Array.from(atob("/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAP//////////////////////////////////////////////////////////////////////////////////////wgALCAABAAEBAREA/8QAFBABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQABPxA="), (c) => c.charCodeAt(0));const PNG = Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAACAAAAAYCAIAAAAUMWhjAAAAJElEQVR4nGM4EaBBU8QwasGoBaMWjFowasGoBaMWjFowNCwAAOj5wC7/fbJHAAAAAElFTkSuQmCC"), (c) => c.charCodeAt(0));type Answer = { json: unknown } | { bytes: Uint8Array; type: string } | { status: number };/** A fetch that answers by the first matching URL prefix, and keeps every URL it was asked. */class Sources {  readonly asked: string[] = [];  private readonly answers: [string, Answer][];  constructor(answers: [string, Answer][]) {    this.answers = answers;  }  readonly fetch: Fetcher = async (url) => {    this.asked.push(url);    const hit = this.answers.find(([prefix]) => url.startsWith(prefix))?.[1];    if (!hit) return new Response("not stubbed", { status: 599 });    if ("json" in hit) return Response.json(hit.json);    if ("bytes" in hit) return new Response(hit.bytes, { headers: { "content-type": hit.type } });    return new Response("no", { status: hit.status });  };}async function pass(slug: string, sources: Sources) {  return runInDurableObject(stub(slug), (instance: Business) => instance.artworkPass(sources.fetch));}async function row(slug: string, table: string, id: string): Promise<Record<string, unknown>> {  return runInDurableObject(stub(slug), (_i, state) => new Store(state.storage.sql, () => new Date()).get(table, id)!.data);}async function write(slug: string, credential: string, act: "create" | "update", args: Record<string, unknown>): Promise<string> {  const res = await http<{ made?: { id: string } }>(slug, "POST", "/v1/act", { act, args }, { authorization: `Bearer ${credential}` });  expect(res.status, JSON.stringify(res.body)).toBe(200);  return res.body.made?.id ?? String(args.id);}async function media(slug: string, owner: string, key: string): Promise<Response> {  return SELF.fetch(`https://example.test/b/${slug}/v1/media/${key}`, { headers: { authorization: `Bearer ${owner}` } });}async function sha(bytes: Uint8Array): Promise<string> {  return [...new Uint8Array(await crypto.subtle.digest("SHA-256", bytes))].map((b) => b.toString(16).padStart(2, "0")).join("");}/** The kit's tables, the book's with an ISBN column, as an owner who keeps ISBNs would define it. */const WITH_ISBN = PERSONAL_TABLES.map((t) =>  t.id === "book" ? { ...t, seal: null, columns: [...(t.columns as Record<string, unknown>[]), { key: "isbn", name: "ISBN", type: "text" }] } : t,);const COVERS = "https://covers.openlibrary.org/b/id/";const SEARCH = "https://openlibrary.org/search.json?";const WIKI = "https://www.wikidata.org/w/api.php?";describe("the artwork engine", () => {  it("keeps no cover in the clear while no phone has handed over the arrival key, and fills it once one has", async () => {    const { credential } = await personalObject("art-no-arrival", BOOKS_OPEN);    const id = await write("art-no-arrival", credential, "create", { table: "book", data: { title: "Piranesi", author: "Susanna Clarke" } });    const sources = new Sources([      [SEARCH, { json: { docs: [{ key: "/works/OL20893680W", title: "Piranesi", cover_i: 10519395 }] } }],      [COVERS, { bytes: PNG, type: "image/png" }],    ]);    expect(await pass("art-no-arrival", sources)).toMatchObject({ filled: 0, failed: 1 });    expect((await row("art-no-arrival", "book", id)).cover ?? null).toBeNull();    const key = `${DATABASE_ID}/photos/${await sha(PNG)}.png`;    expect((await media("art-no-arrival", credential, key)).status).toBe(404);  });  it("finds a book's cover by its ISBN, keeps it as the object's media and names it in the row", async () => {    const { credential } = await personalObject("art-isbn", { arrival: true, ...BOOKS_OPEN, open: [...BOOKS_OPEN.open, ...FILMS_OPEN.open] });    const defs = await http("art-isbn", "PUT", "/v1/admin/definitions", { tools: PERSONAL_TOOLS, tables: WITH_ISBN, flavour: { flavour: "personal" } }, ADMIN);    expect(defs.status, JSON.stringify(defs.body)).toBe(200);    const id = await write("art-isbn", credential, "create", { table: "book", data: { title: "The Hobbit", author: "J.R.R. Tolkien", isbn: "978-0-261-10334-4" } });    const sources = new Sources([      [SEARCH, { json: { docs: [{ key: "/works/OL27482W", title: "The Hobbit", cover_i: 14627509 }] } }],      [COVERS, { bytes: JPEG, type: "image/jpeg" }],    ]);    expect(await pass("art-isbn", sources)).toEqual({ filled: 1, missing: 0, failed: 0, more: false });    const search = new URL(sources.asked[0]!);    expect(search.searchParams.get("isbn")).toBe("9780261103344");    expect(search.searchParams.has("title")).toBe(false);    expect(sources.asked[1]).toBe(`${COVERS}14627509-L.jpg?default=false`);    const key = `${DATABASE_ID}/photos/${await sha(JPEG)}.jpg`;    expect((await row("art-isbn", "book", id)).cover).toBe(key);    const kept = await media("art-isbn", credential, key);    expect(kept.status).toBe(200);    // Kept sealed at arrival (R6 with R2): the bucket holds no picture, and a device holding the arrival key opens the JPEG.    expect(kept.headers.get("content-type")).toBe("application/vnd.cotton.f1");    const stored = new Uint8Array(await kept.arrayBuffer());    expect(new TextDecoder().decode(stored.subarray(0, 4))).toBe("CTA1");    expect(await openArrivalFile(stored, key)).toEqual(JPEG);    // Filled, it is not asked again.    const again = new Sources([]);    expect(await pass("art-isbn", again)).toEqual({ filled: 0, missing: 0, failed: 0, more: false });    expect(again.asked).toEqual([]);  });  it("finds a book with no ISBN by its title and author, taking the first match that has a cover", async () => {    const { credential } = await personalObject("art-title", { arrival: true, ...BOOKS_OPEN, open: [...BOOKS_OPEN.open, ...FILMS_OPEN.open] });    const id = await write("art-title", credential, "create", { table: "book", data: { title: "Piranesi", author: "Susanna Clarke" } });    const sources = new Sources([      [SEARCH, { json: { docs: [{ key: "/works/OL1W", title: "Piranesi (notes)" }, { key: "/works/OL20893680W", title: "Piranesi", cover_i: 10519395 }] } }],      [COVERS, { bytes: PNG, type: "image/png" }],    ]);    expect(await pass("art-title", sources)).toMatchObject({ filled: 1 });    const search = new URL(sources.asked[0]!);    expect([search.searchParams.get("title"), search.searchParams.get("author"), search.searchParams.has("isbn")]).toEqual(["Piranesi", "Susanna Clarke", false]);    expect(sources.asked[1]).toBe(`${COVERS}10519395-L.jpg?default=false`);    expect((await row("art-title", "book", id)).cover).toBe(`${DATABASE_ID}/photos/${await sha(PNG)}.png`);  });  it("finds a film's poster on Wikidata, the film of the row's year and not a namesake", async () => {    const { credential } = await personalObject("art-film", { arrival: true, ...BOOKS_OPEN, open: [...BOOKS_OPEN.open, ...FILMS_OPEN.open] });    const id = await write("art-film", credential, "create", { table: "film", data: { title: "Sintel", year: "2010", kind: "film", status: "want_to_watch" } });    const sources = new Sources([      [        `${WIKI}action=wbsearchentities`,        {          json: {            search: [              { id: "Q140032367", description: "Artist in music and art" },              { id: "Q67185169", description: "main character from Sintel (2010 film)" },              { id: "Q99", description: "1999 short film" },              { id: "Q925587", description: "2010 computer-generated short film" },            ],          },        },      ],      [        `${WIKI}action=wbgetentities`,        {          json: {            entities: {              Q140032367: { claims: { P31: [{ mainsnak: { datavalue: { value: { id: "Q5" } } } }], P18: [{ mainsnak: { datavalue: { value: "Someone.jpg" } } }] } },              Q67185169: { claims: { P31: [{ mainsnak: { datavalue: { value: { id: "Q15632617" } } } }], P18: [{ mainsnak: { datavalue: { value: "Sintel character.png" } } }] } },              Q99: { claims: { P31: [{ mainsnak: { datavalue: { value: { id: "Q24862" } } } }], P3383: [{ mainsnak: { datavalue: { value: "Other poster.jpg" } } }], P577: [{ mainsnak: { datavalue: { value: { time: "+1999-01-01T00:00:00Z" } } } }] } },              Q925587: {                claims: {                  P31: [{ mainsnak: { datavalue: { value: { id: "Q17517379" } } } }],                  P3383: [{ mainsnak: { datavalue: { value: "Sintel poster.jpg" } } }],                  P18: [{ mainsnak: { datavalue: { value: "Sintel Poster Paintover clean.jpg" } } }],                  P577: [{ mainsnak: { datavalue: { value: { time: "+2010-09-27T00:00:00Z" } } } }],                },              },            },          },        },      ],      ["https://commons.wikimedia.org/wiki/Special:FilePath/", { bytes: JPEG, type: "image/jpeg" }],    ]);    expect(await pass("art-film", sources)).toEqual({ filled: 1, missing: 0, failed: 0, more: false });    expect(new URL(sources.asked[0]!).searchParams.get("search")).toBe("Sintel");    expect(new URL(sources.asked[1]!).searchParams.get("ids")).toBe("Q140032367|Q67185169|Q99|Q925587");    expect(sources.asked[2]).toBe("https://commons.wikimedia.org/wiki/Special:FilePath/Sintel_poster.jpg?width=1000");    expect((await row("art-film", "film", id)).poster).toBe(`${DATABASE_ID}/photos/${await sha(JPEG)}.jpg`);  });  it("remembers a film it found nothing for and does not ask again until its title changes", async () => {    const { credential } = await personalObject("art-miss", { arrival: true, ...BOOKS_OPEN, open: [...BOOKS_OPEN.open, ...FILMS_OPEN.open] });    const id = await write("art-miss", credential, "create", { table: "film", data: { title: "Paper Comets", year: "2016" } });    const nothing = (): Sources => new Sources([[`${WIKI}action=wbsearchentities`, { json: { search: [] } }]]);    const first = nothing();    expect(await pass("art-miss", first)).toEqual({ filled: 0, missing: 1, failed: 0, more: false });    expect(first.asked).toHaveLength(1);    // Asked nothing again: not by the next pass, nor after a change to what it is not looked up by.    const second = nothing();    expect(await pass("art-miss", second)).toEqual({ filled: 0, missing: 0, failed: 0, more: false });    await write("art-miss", credential, "update", { table: "film", id, data: { status: "watched", rating: 4 } });    expect(await pass("art-miss", second)).toEqual({ filled: 0, missing: 0, failed: 0, more: false });    expect(second.asked).toEqual([]);    // Its title corrected, it is looked up once more.    await write("art-miss", credential, "update", { table: "film", id, data: { title: "Paper Comet" } });    const third = nothing();    expect(await pass("art-miss", third)).toMatchObject({ missing: 1 });    expect(new URL(third.asked[0]!).searchParams.get("search")).toBe("Paper Comet");    expect((await row("art-miss", "film", id)).poster).toBeUndefined();  });  it("leaves a row that has its picture untouched, and asks nothing for it", async () => {    const { credential } = await personalObject("art-held", { arrival: true, ...BOOKS_OPEN, open: [...BOOKS_OPEN.open, ...FILMS_OPEN.open] });    const cover = `${DATABASE_ID}/photos/${"ab".repeat(32)}.jpg`;    const book = await write("art-held", credential, "create", { table: "book", data: { title: "Piranesi", author: "Susanna Clarke", cover } });    const film = await write("art-held", credential, "create", { table: "film", data: { title: "Sintel", poster: cover } });    const sources = new Sources([]);    expect(await pass("art-held", sources)).toEqual({ filled: 0, missing: 0, failed: 0, more: false });    expect(sources.asked).toEqual([]);    expect((await row("art-held", "book", book)).cover).toBe(cover);    expect((await row("art-held", "film", film)).poster).toBe(cover);  });  it("marks a source that did not answer as failed and asks it again only after a day", async () => {    const { credential } = await personalObject("art-fail", { arrival: true, ...BOOKS_OPEN, open: [...BOOKS_OPEN.open, ...FILMS_OPEN.open] });    const id = await write("art-fail", credential, "create", { table: "book", data: { title: "Piranesi" } });    const down = new Sources([[SEARCH, { status: 503 }]]);    expect(await pass("art-fail", down)).toEqual({ filled: 0, missing: 0, failed: 1, more: false });    expect(await pass("art-fail", down)).toEqual({ filled: 0, missing: 0, failed: 0, more: false });    expect(down.asked).toHaveLength(1);    // A day on, the alarm's pass asks again.    await runInDurableObject(stub("art-fail"), (_i, state) => state.storage.sql.exec("UPDATE artwork_seen SET at = at - ?", RETRY_MS));    const up = new Sources([      [SEARCH, { json: { docs: [{ key: "/works/OL20893680W", cover_i: 10519395 }] } }],      [COVERS, { bytes: JPEG, type: "image/jpeg" }],    ]);    expect(await pass("art-fail", up)).toMatchObject({ filled: 1 });    expect((await row("art-fail", "book", id)).cover).toBe(`${DATABASE_ID}/photos/${await sha(JPEG)}.jpg`);  });  it("keeps nothing that is not a picture", async () => {    const { credential } = await personalObject("art-not-picture", { arrival: true, ...BOOKS_OPEN, open: [...BOOKS_OPEN.open, ...FILMS_OPEN.open] });    const id = await write("art-not-picture", credential, "create", { table: "book", data: { title: "Piranesi" } });    const sources = new Sources([      [SEARCH, { json: { docs: [{ key: "/works/OL20893680W", cover_i: 10519395 }] } }],      [COVERS, { bytes: new TextEncoder().encode("<html>"), type: "text/html" }],    ]);    expect(await pass("art-not-picture", sources)).toEqual({ filled: 0, missing: 0, failed: 1, more: false });    expect((await row("art-not-picture", "book", id)).cover).toBeUndefined();  });  it("is not set going by a write where the object is told to fetch nothing (this pool)", async () => {    const { credential } = await personalObject("art-off", { arrival: true, ...BOOKS_OPEN, open: [...BOOKS_OPEN.open, ...FILMS_OPEN.open] });    const id = await write("art-off", credential, "create", { table: "book", data: { title: "Piranesi" } });    expect(await runInDurableObject(stub("art-off"), (instance: Business) => instance.artworkPass())).toBeNull();    expect((await row("art-off", "book", id)).cover).toBeUndefined();  });});