206 lines · 11.4 KB · TypeScriptRaw
/** * A book's own file fills its empty columns in the object (src/book_file.ts): * an EPUB built here, kept in the media as an upload is, read by range, its * package read by the one OPF rule (crates/cotton-rules opf.rs as WASM). The * vectors are the rule's own, the ones cargo and the fetcher read. Every book * and file is invented. */import { env, runInDurableObject, SELF } from "cloudflare:test";import { describe, expect, it, vi } from "vitest";import vectors from "../../../crates/cotton-rules/vectors/opf.json";import { RETRY_MS } from "../src/book_file.ts";import type { Business } from "../src/business.ts";import { tryRule } from "../src/rules/index.ts";import { Store } from "../src/store.ts";import { runStepJob } from "../src/jobs/step_job.ts";import { ADMIN, DATABASE_ID, http, personalObject, BOOKS_OPEN } from "./personal.ts";const OPFS = import.meta.glob("../../../crates/cotton-rules/vectors/opf/*.opf", { eager: true, query: "?raw", import: "default" }) as Record<string, string>;const opfOf = (file: string): string => OPFS[`../../../crates/cotton-rules/vectors/opf/${file}`]!;const stub = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug));const text = (words: string) => new TextEncoder().encode(words);async function deflated(bytes: Uint8Array): Promise<Uint8Array> { return new Uint8Array(await new Response(new Blob([bytes]).stream().pipeThrough(new CompressionStream("deflate-raw"))).arrayBuffer());}/** A zip of `files`, each stored (method 0) or deflated (8), as an EPUB packs them. Its CRCs are left none: the object never checks them. */async function zip(files: [string, Uint8Array, 0 | 8][]): Promise<Uint8Array> { const parts: Uint8Array[] = []; const central: Uint8Array[] = []; let at = 0; for (const [name, bytes, method] of files) { const data = method === 8 ? await deflated(bytes) : bytes; const n = text(name); const local = new DataView(new ArrayBuffer(30)); local.setUint32(0, 0x04034b50, true); local.setUint16(4, 20, true); local.setUint16(8, method, true); local.setUint32(18, data.byteLength, true); local.setUint32(22, bytes.byteLength, true); local.setUint16(26, n.byteLength, true); const dir = new DataView(new ArrayBuffer(46)); dir.setUint32(0, 0x02014b50, true); dir.setUint16(4, 20, true); dir.setUint16(6, 20, true); dir.setUint16(10, method, true); dir.setUint32(20, data.byteLength, true); dir.setUint32(24, bytes.byteLength, true); dir.setUint16(28, n.byteLength, true); dir.setUint32(42, at, true); parts.push(new Uint8Array(local.buffer), n, data); central.push(new Uint8Array(dir.buffer), n); at += 30 + n.byteLength + data.byteLength; } const size = central.reduce((sum, p) => sum + p.byteLength, 0); const end = new DataView(new ArrayBuffer(22)); end.setUint32(0, 0x06054b50, true); end.setUint16(8, files.length, true); end.setUint16(10, files.length, true); end.setUint32(12, size, true); end.setUint32(16, at, true); const all = [...parts, ...central, new Uint8Array(end.buffer)]; const out = new Uint8Array(all.reduce((sum, p) => sum + p.byteLength, 0)); let o = 0; for (const p of all) { out.set(p, o); o += p.byteLength; } return out;}const CONTAINER = `<?xml version="1.0"?><container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container"><rootfiles><rootfile full-path="OPS/package.opf" media-type="application/oebps-package+xml"/></rootfiles></container>`;/** An EPUB whose container names OPS/package.opf holding `opf` (and a decoy package it does not name). */async function epub(opf: string): Promise<Uint8Array> { return zip([ ["mimetype", text("application/epub+zip"), 0], ["META-INF/container.xml", text(CONTAINER), 8], ["OPS/decoy.opf", text("<package><metadata><dc:publisher xmlns:dc='d'>Not This Press</dc:publisher></metadata></package>"), 8], ["OPS/package.opf", text(opf), 8], ]);}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("");}/** `bytes` kept in the media as an upload keeps a book; answers the row's key. */async function keep(slug: string, bytes: Uint8Array): Promise<string> { const name = `books/${await sha(bytes)}.epub`; await env.MEDIA.put(`${slug}/${name}`, bytes, { httpMetadata: { contentType: "application/epub+zip" } }); return `${DATABASE_ID}/${name}`;}async function create(slug: string, credential: string, data: Record<string, unknown>): Promise<string> { const res = await http<{ made?: { id: string } }>(slug, "POST", "/v1/act", { act: "create", args: { table: "book", data } }, { authorization: `Bearer ${credential}` }); expect(res.status, JSON.stringify(res.body)).toBe(200); return res.body.made!.id;}async function book(slug: string, id: string): Promise<Record<string, unknown>> { return runInDurableObject(stub(slug), (_i, state) => new Store(state.storage.sql, () => new Date()).get("book", id)!.data);}async function pass(slug: string, now: number) { return runInDurableObject(stub(slug), (instance: Business) => instance.bookFilePass(now));}describe("a book's own file", () => { it("reads every vector as cotton-rules does: the WASM is the rule", () => { for (const v of vectors as { file: string; answer: unknown }[]) { expect(tryRule("book.opf", { opf: opfOf(v.file) }), v.file).toEqual({ ok: v.answer }); } expect(tryRule("book.container", { xml: CONTAINER })).toEqual({ ok: { opf_path: "OPS/package.opf" } }); }); it("fills a new book's empty columns from the package its container names, off the request, and leaves what was written", async () => { const slug = "book-file-fill"; const { credential } = await personalObject(slug, BOOKS_OPEN); const file = await keep(slug, await epub(opfOf("epub3-whole.opf"))); const id = await create(slug, credential, { title: "My Own Name For It", publisher: "Held Press", file, status: "want_to_read" }); await vi.waitFor(async () => expect((await book(slug, id)).author).toBe("Irena Valcourt, Mirel Okafor"), { timeout: 10_000, interval: 100 }); expect(await book(slug, id)).toMatchObject({ title: "My Own Name For It", publisher: "Held Press", description: "An orchard of glass & light.\n\nSecond part\nline", subjects: "Fiction, Orchards", isbn: "9780000000019", doi: "10.5555/lantern.2026", ol_work: "OL1234W", ol_edition: "OL5678M", language: "en-GB", year: "1911", series: "Glass Seasons", series_number: 2, format: "epub", }); const changes = await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<{ via: string }>("SELECT via FROM change WHERE record_id = ? ORDER BY id", id).toArray()); expect(changes.map((c) => c.via)).toContain("book_file"); // Each column it filled says so in filled_from, and nothing it did not fill. expect(JSON.parse((await book(slug, id)).filled_from as string)).toEqual( Object.fromEntries(["author", "description", "subjects", "isbn", "doi", "ol_work", "ol_edition", "language", "year", "series", "series_number"].map((k) => [k, "opf"])), ); // Read once for its file: a later pass reads nothing. expect(await pass(slug, Date.now() + 2 * RETRY_MS)).toMatchObject({ filled: 0, nothing: 0, unreadable: 0, absent: 0, failed: 0 }); }); it("reads a book whose file came after it once the hour has passed, and never again a file that is no EPUB", async () => { const slug = "book-file-late"; const { credential } = await personalObject(slug, BOOKS_OPEN); const bytes = await epub(opfOf("standard-ebooks.opf")); const file = `${DATABASE_ID}/books/${await sha(bytes)}.epub`; const late = await create(slug, credential, { title: "The Copper Heron", file, status: "want_to_read" }); const broken = await create(slug, credential, { title: "Broken", file: await keep(slug, text("no zip at all, only words")), status: "want_to_read" }); await vi.waitFor(async () => { const seen = await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<{ outcome: string }>("SELECT outcome FROM book_file_seen ORDER BY id").toArray()); expect(seen.map((s) => s.outcome).sort()).toEqual(["absent", "unreadable"]); }, { timeout: 10_000, interval: 100 }); expect(await book(slug, late)).not.toHaveProperty("author"); await keep(slug, bytes); expect(await pass(slug, Date.now())).toMatchObject({ filled: 0, absent: 0, unreadable: 0 }); expect(await pass(slug, Date.now() + RETRY_MS + 1)).toMatchObject({ filled: 1, unreadable: 0 }); expect(await book(slug, late)).toMatchObject({ author: "Odile Fenwright", series: "The Delta Cycle", series_number: 3, publisher: "Standard Ebooks", language: "en-GB" }); expect(await book(slug, broken)).not.toHaveProperty("author"); }); it("stamps nothing when the package fills nothing the book left empty", async () => { const slug = "book-file-nothing"; const { credential } = await personalObject(slug, BOOKS_OPEN); const file = await keep(slug, await epub(opfOf("epub2-calibre.opf"))); const held = { title: "Held Whole", author: "Someone Else", description: "Mine.", isbn: "9780000000026", series: "My Own", series_number: 9, year: "2001" }; const id = await create(slug, credential, { ...held, file, status: "want_to_read" }); await vi.waitFor(async () => { const seen = await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<{ outcome: string }>("SELECT outcome FROM book_file_seen").toArray()); expect(seen.map((s) => s.outcome)).toEqual(["nothing"]); }, { timeout: 10_000, interval: 100 }); expect(await book(slug, id)).toMatchObject(held); expect(await book(slug, id)).not.toHaveProperty("filled_from"); });});// JOBS OUT M3 (assets/design/shared/JOBS-OUT.md): the book files' pass as a step job beside the account object.describe("JOBS OUT M3: a book's own file read by a step job", { timeout: 120_000 }, () => { const door = (slug: string, path: string, init: RequestInit) => SELF.fetch(`https://jobs.internal/b/${slug}${path}`, init); it("on: neither the write nor the alarm reads the file; the run fills the book through the door", async () => { const slug = "book-file-job"; const { credential } = await personalObject(slug, BOOKS_OPEN); expect((await http(slug, "PUT", "/v1/admin/business", { jobs: { book_files: "on" } }, ADMIN)).status).toBe(200); const file = await keep(slug, await epub(opfOf("epub3-whole.opf"))); const id = await create(slug, credential, { title: "My Own Name For It", file, status: "want_to_read" }); await runInDurableObject(stub(slug), async (instance: Business) => { await (instance as unknown as { bookFileRunning: Promise<void> | null }).bookFileRunning; await instance.alarm(); }); expect((await book(slug, id)).author ?? null, "the object left the file to the job").toBeNull(); const sent = await runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<{ sent_at: number | null }>("SELECT sent_at FROM step_job WHERE kind = 'book_files'").toArray()[0]?.sent_at ?? null); expect(sent, "a run was put on the queue").not.toBeNull(); const message = await runInDurableObject(stub(slug), (instance: Business) => instance.stepJobMessage("book_files")); expect(await runStepJob({ door }, message)).toBe("ran"); expect((await book(slug, id)).author).toBe("Irena Valcourt, Mirel Okafor"); });});