/** * The open films seed (scripts/films-seed-open.ts) against a fake object that * answers the routes the seed uses as the Worker does (src/media.ts' parts, * /v1/act, /mcp list_records, /v1/definitions), with the prepared MP4s * stood in by small files: what it makes, sends and leaves, and that a * second run changes nothing. */ import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; import film from "../../../../crates/cotton-core/kits/personal/tables/film.json"; import { FILMS, notesOf, parseArgs, plan, playerOf, seed, SeedRefusal, type Deps, type OpenFilm, type Prepared } from "../films-seed-open.ts"; const DB = "11111111-1111-4111-8111-111111111111"; const TOKEN = `ctn_${DB}_secret`; /** The kit's film table with a file column its slip plays from: what the seed writes into. */ const PLAYING = film; /** A table without playback, independent of whether the shipped kit plays films. */ const NO_PLAYER = { ...film, columns: film.columns.filter(c => c.key !== "file"), slip: { ...film.slip, player: null } }; type Row = { id: string; data: Record }; /** The object as the seed meets it; `fills` are the titles its artwork engine finds a poster for. */ class FakeObject { rows: Row[] = []; media = new Map(); uploads = new Map }>(); acts: string[] = []; asked: string[] = []; next = 1; private readonly table: Record; private readonly fills: Set; constructor(table: Record, fills: Set) { this.table = table; this.fills = fills; } readonly fetch = (async (input: string | URL | Request, init?: RequestInit): Promise => { const url = new URL(String(input)); const method = init?.method ?? "GET"; this.asked.push(`${method} ${url.pathname}${url.search}`); if (url.host === "posters.test") return new Response(new Uint8Array([1, 2, 3]), { headers: { "content-type": "image/jpeg" } }); if (init && (init.headers as Record).authorization !== `Bearer ${TOKEN}`) return new Response("who", { status: 401 }); const body = init?.body; const json = (): Record => JSON.parse(String(body)) as Record; if (url.pathname === "/b/me/v1/definitions") return Response.json({ business: { database_id: DB }, tables: [this.table] }); if (url.pathname === "/b/me/mcp") { const call = json() as { params: { name: string; arguments: { page: number } } }; expect(call.params.name).toBe("list_records"); return Response.json({ result: { isError: false, content: [{ text: JSON.stringify({ records: this.rows.map((r) => ({ id: r.id, data: { ...r.data } })), next_page: null }) }] } }); } if (url.pathname === "/b/me/v1/act") { const { act, args } = json() as { act: string; args: { table: string; id?: string; data: Record } }; this.acts.push(act); if (act === "create") { const id = `film-${this.next++}`; this.rows.push({ id, data: { ...args.data } }); // The engine, off the write: a poster where the source knows one. if (this.fills.has(String(args.data.title))) this.rows.at(-1)!.data.poster = `${DB}/photos/engine.jpg`; return Response.json({ made: { id } }); } Object.assign(this.rows.find((r) => r.id === args.id)!.data, args.data); return Response.json({ ok: true }); } if (url.pathname.startsWith("/b/me/v1/media/")) { const key = decodeURIComponent(url.pathname.slice("/b/me/v1/media/".length)); if (method === "POST" && url.searchParams.has("uploads")) { const { size } = json() as { size: number }; if (this.media.get(key)?.length === size) return Response.json({ stored: false, bytes: size }); const id = `u${this.uploads.size + 1}`; this.uploads.set(id, { key, parts: new Map() }); return Response.json({ upload: id }, { status: 201 }); } const upload = url.searchParams.get("upload"); if (method === "PUT" && upload) { const part = Number(url.searchParams.get("part")); this.uploads.get(upload)!.parts.set(part, new Uint8Array(body as Uint8Array)); return Response.json({ part, etag: `e${part}` }); } if (method === "POST" && upload) { const { parts } = json() as { parts: { part: number; etag: string }[] }; const held = this.uploads.get(upload)!; const whole = Buffer.concat(parts.map((p) => held.parts.get(p.part)!)); this.media.set(held.key, new Uint8Array(whole)); return Response.json({ stored: true, bytes: whole.length }, { status: 201 }); } if (method === "PUT") { this.media.set(key, new Uint8Array(body as Uint8Array)); return Response.json({ stored: true }, { status: 201 }); } } return new Response(`nothing answers ${method} ${url.pathname}`, { status: 404 }); }) as typeof fetch; } /** The four films, their official posters on a host the fake answers. */ const SMALL: OpenFilm[] = FILMS.map((f) => ({ ...f, poster: `https://posters.test/${f.slug}.jpg` })); function deps(object: FakeObject): Deps & { prepared: string[] } { const dir = mkdtempSync(join(tmpdir(), "films-seed-")); const prepared: string[] = []; return { prepared, fetch: object.fetch, partBytes: 4, sleep: async () => {}, prepare: async (f: OpenFilm): Promise => { prepared.push(f.slug); const path = join(dir, `${f.slug}.mp4`); writeFileSync(path, `film:${f.slug}`); return { path, type: "video/mp4", ext: "mp4", size: readFileSync(path).length, sha256: f.slug.padEnd(64, "0"), minutes: 10 }; }, }; } const ARGS = { base: "https://object.test/b/me", token: TOKEN, cache: "/unused", waitSeconds: 0 }; describe("the open films seed", () => { it("names the four Blender open movies, each from download.blender.org with its licence, and says both in the row's review", () => { expect(FILMS.map((f) => [f.title, f.year])).toEqual([ ["Big Buck Bunny", "2008"], ["Sintel", "2010"], ["Tears of Steel", "2012"], ["Elephants Dream", "2006"], ]); for (const f of FILMS) { expect(f.url).toMatch(/^https:\/\/download\.blender\.org\//); expect(f.licence).toMatch(/^CC BY \d\.\d$/); expect(notesOf(f)).toContain(f.licence); expect(notesOf(f)).toContain(f.url); } }); it("refuses a film table whose slip plays from no file column before anything is downloaded", async () => { expect(() => playerOf(NO_PLAYER)).toThrow(SeedRefusal); expect(() => playerOf(null)).toThrow(/no film table/); expect(playerOf(PLAYING)).toBe("file"); const object = new FakeObject(NO_PLAYER, new Set()); const d = deps(object); await expect(seed(ARGS, () => {}, d, SMALL)).rejects.toThrow(/names no player column/); expect(d.prepared).toEqual([]); expect(object.media.size).toBe(0); }); it("sends each film in parts, makes its row with the file and no poster, and uploads the official poster only where the engine filled none", async () => { const object = new FakeObject(PLAYING, new Set(["Big Buck Bunny", "Sintel", "Tears of Steel"])); const lines: string[] = []; const runs = await seed(ARGS, (l) => lines.push(l), deps(object), SMALL); expect(runs.map((r) => [r.title, r.sent, r.row, r.poster])).toEqual([ ["Big Buck Bunny", true, "made", "filled by the engine"], ["Sintel", true, "made", "filled by the engine"], ["Tears of Steel", true, "made", "filled by the engine"], ["Elephants Dream", true, "made", "official poster uploaded"], ]); const bunny = object.rows.find((r) => r.data.title === "Big Buck Bunny")!; const key = `${DB}/videos/${"big-buck-bunny".padEnd(64, "0")}.mp4`; expect(bunny.data).toMatchObject({ year: "2008", kind: "film", status: "want_to_watch", director: "Sacha Goedegebure", minutes: 10, file: key }); expect(bunny.data.review).toBe(notesOf(FILMS[0]!)); // Made with no poster: the engine's is the only one. expect(object.asked.filter((a) => a.startsWith("PUT /b/me/v1/media/") && !a.includes("upload="))).toHaveLength(1); expect(new TextDecoder().decode(object.media.get(key))).toBe("film:big-buck-bunny"); // "film:big-buck-bunny" is 19 bytes: five parts of four. expect(object.uploads.get("u1")!.parts.size).toBe(5); const dream = object.rows.find((r) => r.data.title === "Elephants Dream")!; expect(dream.data.poster).toMatch(new RegExp(`^${DB}/photos/[0-9a-f]{64}\\.jpg$`)); expect(lines.join("\n")).toContain("the official poster https://posters.test/elephants-dream.jpg was uploaded"); }); it("changes nothing on a second run", async () => { const object = new FakeObject(PLAYING, new Set(FILMS.map((f) => f.title))); await seed(ARGS, () => {}, deps(object), SMALL); const rows = JSON.stringify(object.rows); const acts = object.acts.length; const media = object.media.size; const again = await seed(ARGS, () => {}, deps(object), SMALL); expect(again.map((r) => [r.sent, r.row, r.poster])).toEqual(FILMS.map(() => [false, "kept", "was there"])); expect(object.acts.length).toBe(acts); expect(object.media.size).toBe(media); expect(JSON.stringify(object.rows)).toBe(rows); }); it("finds a film already in Films by its title in any case, gives it the file when it has none, and leaves one holding another", () => { const f = FILMS[1]!; const key = `${DB}/videos/x.mp4`; expect(plan(f, [{ id: "a", data: { title: "sintel ", year: "2010" } }], "file", key, 15)).toEqual({ give: { id: "a", data: { file: key } } }); expect(plan(f, [{ id: "a", data: { title: "Sintel" } }], "file", key, 15)).toEqual({ give: { id: "a", data: { file: key } } }); expect(plan(f, [{ id: "a", data: { title: "Sintel", year: "2010", file: key } }], "file", key, 15)).toEqual({ keep: "a" }); expect(plan(f, [{ id: "a", data: { title: "Sintel", year: "2010", file: "other" } }], "file", key, 15)).toEqual({ taken: "a" }); expect(plan(f, [{ id: "a", data: { title: "Sintel", year: "1999" } }], "file", key, 15)).toHaveProperty("make"); }); it("reads its token from the file it is named, from where the command was run, and refuses what it cannot use", () => { const dir = mkdtempSync(join(tmpdir(), "films-seed-args-")); writeFileSync(join(dir, "token"), `${TOKEN}\n`); expect(parseArgs(["--base", "http://127.0.0.1:8787/b/x/", "--token-file", "token", "--wait", "5"], dir)).toMatchObject({ base: "http://127.0.0.1:8787/b/x", token: TOKEN, waitSeconds: 5 }); writeFileSync(join(dir, "bad"), "nope"); expect(() => parseArgs(["--base", "http://x", "--token-file", "bad"], dir)).toThrow(/no ctn_ token/); expect(() => parseArgs(["--token-file", "token"], dir)).toThrow(/--base/); expect(() => parseArgs(["--base", "http://x"], dir)).toThrow(/--token-file/); expect(() => parseArgs(["--base", "http://x", "--token-file", "token", "--reset"], dir)).toThrow(/unknown flag/); }); });