Cotton code
245 lines · 16.2 KB · TypeScriptRaw
/** * JOBS OUT M1 (assets/design/shared/JOBS-OUT.md (d), "How the rest move: step jobs"): a step job beside the account * object. Its queue message names one account, one kind and a nonce; the consumer calls the object's door * `POST /v1/jobs/step/<kind>` again and again, each call one bounded step in an ordinary request (never the alarm). * Each kind has its own per-account switch, off by default; off, the object runs the work exactly as before. * M1's kind: media_drop, the R2 folders an erase left (`dropMedia`), which ran on every alarm and after every request. */import { env, runInDurableObject, SELF } from "cloudflare:test";import { describe, expect, it } from "vitest";import type { Business } from "../src/business.ts";import { runStepJob, type StepJobMessage } from "../src/jobs/step_job.ts";import { mintJobToken } from "../src/jobs/token.ts";import stepJobSource from "../src/jobs/step_job.ts?raw";import type { Fetcher } from "../src/artwork.ts";import { Store } from "../src/store.ts";import { ADMIN, BOOKS_OPEN, DATABASE_ID, FILMS_OPEN, http, PERSONAL_TABLES, PERSONAL_TOOLS, personalObject } from "./personal.ts";const stub = (slug: string) => env.BUSINESS.get(env.BUSINESS.idFromName(slug));/** The object's store, for what only a test reaches: the list of folders an erase left. */const storeOf = (instance: Business) => (instance as unknown as { store: { dropMediaLater(folder: string): void; mediaToDrop(): string[] } }).store;const door = (slug: string, path: string, init: RequestInit) => SELF.fetch(`https://jobs.internal/b/${slug}${path}`, init);const messageOf = (slug: string, kind = "media_drop") => runInDurableObject(stub(slug), (instance: Business) => instance.stepJobMessage(kind));const jobRow = (slug: string) => runInDurableObject(stub(slug), (_i, state) => state.storage.sql.exec<Record<string, SqlStorageValue>>("SELECT * FROM step_job").toArray());/** A film folder an erase left: its file in R2, its key on the object's list to drop. */async function leftFolder(slug: string, name: string): Promise<string> {  await env.MEDIA.put(`${slug}/films/${name}/master.m3u8`, "#EXTM3U\n");  await runInDurableObject(stub(slug), (instance: Business) => storeOf(instance).dropMediaLater(`${DATABASE_ID}/films/${name}/`));  return `${slug}/films/${name}/master.m3u8`;}async function switched(slug: string, on: boolean): Promise<Record<string, string>> {  const { credential } = await personalObject(slug, {});  if (on) {    const r = await http(slug, "PUT", "/v1/admin/business", { jobs: { media_drop: "on" } }, ADMIN);    expect(r.status, JSON.stringify(r.body)).toBe(200);  }  return { authorization: `Bearer ${credential}` };}describe("JOBS OUT M1: media upkeep as a step job beside the account object", { timeout: 120_000 }, () => {  it("is switched per account and per kind by the admin alone; off is the default", async () => {    const slug = "step-job-switch";    const phone = await switched(slug, false);    expect((await http(slug, "PUT", "/v1/admin/business", { jobs: { media_drop: "on" } }, phone)).status).toBe(403);    expect((await http(slug, "PUT", "/v1/admin/business", { jobs: { media_drop: "yes" } }, ADMIN)).status).toBe(400);    expect((await http(slug, "PUT", "/v1/admin/business", { jobs: { no_such_job: "on" } }, ADMIN)).status).toBe(400);    expect((await http(slug, "PUT", "/v1/admin/business", { jobs: { media_drop: "on" } }, ADMIN)).status).toBe(200);    expect((await http(slug, "PUT", "/v1/admin/business", { jobs: { media_drop: null } }, ADMIN)).status).toBe(200);  });  it("off: a request drops a left folder itself, as before", async () => {    const slug = "step-job-off";    const phone = await switched(slug, false);    const file = await leftFolder(slug, "off-film");    await http(slug, "GET", "/v1/sync", undefined, phone);    expect(await env.MEDIA.head(file)).toBeNull();  });  it("on: neither a request nor the alarm drops it; the object puts a run on the queue and the run drops it through the door", async () => {    const slug = "step-job-on";    const phone = await switched(slug, true);    const file = await leftFolder(slug, "on-film");    await http(slug, "GET", "/v1/sync", undefined, phone);    await runInDurableObject(stub(slug), (instance: Business) => instance.alarm());    expect(await env.MEDIA.head(file), "the object left it to the job").not.toBeNull();    const [row] = await jobRow(slug);    expect(row).toMatchObject({ kind: "media_drop", run: null });    expect(row!.sent_at, "a run was put on the queue").not.toBeNull();    expect(await runStepJob({ door }, await messageOf(slug))).toBe("ran");    expect(await env.MEDIA.head(file)).toBeNull();    const [after] = await jobRow(slug);    expect(after!.run, "the run ended").toBeNull();    expect(after!.due_at, "nothing left: no next run").toBeNull();    expect(await runInDurableObject(stub(slug), (instance: Business) => storeOf(instance).mediaToDrop())).toEqual([]);  });  it("one message begins one run; a credential for another kind, an old generation, or with the switch off opens nothing", async () => {    const slug = "step-job-door";    await switched(slug, true);    await leftFolder(slug, "door-film");    const message = await messageOf(slug);    expect(await runStepJob({ door }, message)).toBe("ran");    expect(await runStepJob({ door }, message), "the same message again").toBe("gone");    const [row] = await jobRow(slug);    const forged = await mintJobToken(env.JOB_TOKEN_KEY, { v: 1, slug, kind: "step:media_drop", account: "media_drop", gen: "not-the-generation", nonce: String(row!.nonce ?? "x"), exp: Date.now() + 60_000 });    expect(await runStepJob({ door }, { ...message, token: forged })).toBe("gone");    const noScheme = await door(slug, "/v1/jobs/step/media_drop", { method: "POST" });    expect(noScheme.status).toBe(401);    await leftFolder(slug, "door-film-2");    const next = await messageOf(slug);    await http(slug, "PUT", "/v1/admin/business", { jobs: { media_drop: null } }, ADMIN);    expect(await runStepJob({ door }, next), "switched off").toBe("gone");    expect(await jobRow(slug)).toEqual([]);  });  it("the alarm's watchdog asks again for a run the queue lost", async () => {    const slug = "step-job-watchdog";    const phone = await switched(slug, true);    await leftFolder(slug, "lost-film");    await http(slug, "GET", "/v1/sync", undefined, phone);    await runInDurableObject(stub(slug), (_i, state) => void state.storage.sql.exec("UPDATE step_job SET due_at = ?, sent_at = ?", Date.now() - 3_600_000, Date.now() - 3_600_000));    await runInDurableObject(stub(slug), (instance: Business) => instance.alarm());    const [row] = await jobRow(slug);    expect(Number(row!.sent_at)).toBeGreaterThan(Date.now() - 60_000);  });  it("job code reaches no object, store or binding: only its door", () => {    const text = stepJobSource as string;    for (const i of [...text.matchAll(/from "([^"]+)"/g)].map((m) => m[1])) expect(["./token.ts"], `step_job imports ${i}`).toContain(i);    expect(text).not.toMatch(/env\.(BUSINESS|MEDIA|DIRECTORY|JOB_TOKEN_KEY)|SqlStorage|storage\./);  });});// ── JOBS OUT M2: artwork ─────────────────────────────────────────────────const JPEG = Uint8Array.from(atob("/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAP//////////////////////////////////////////////////////////////////////////////////////wgALCAABAAEBAREA/8QAFBABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQABPxA="), (c) => c.charCodeAt(0));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));/** Open Library as the artwork tests stub it: one search, one cover; counts what was asked. */function openLibrary(asked: string[]): Fetcher {  return async (url) => {    asked.push(url);    if (url.startsWith("https://openlibrary.org/search.json?")) return Response.json({ docs: [{ key: "/works/OL27482W", title: "The Hobbit", cover_i: 14627509 }] });    if (url.startsWith("https://covers.openlibrary.org/b/id/")) return new Response(JPEG, { headers: { "content-type": "image/jpeg" } });    return new Response("not stubbed", { status: 599 });  };}async function bookWaitingForCover(slug: string, on: boolean, asked: string[]): Promise<{ id: string; phone: Record<string, string> }> {  const { credential } = await personalObject(slug, { arrival: true, ...BOOKS_OPEN, open: [...BOOKS_OPEN.open, ...FILMS_OPEN.open] });  expect((await http(slug, "PUT", "/v1/admin/definitions", { tools: PERSONAL_TOOLS, tables: WITH_ISBN, flavour: { flavour: "personal" } }, ADMIN)).status).toBe(200);  if (on) expect((await http(slug, "PUT", "/v1/admin/business", { jobs: { artwork: "on" } }, ADMIN)).status).toBe(200);  // The test Worker fetches no outside site (ARTWORK off): this object's engine is handed the stub instead.  await runInDurableObject(stub(slug), (instance: Business) => void ((instance as unknown as { artworkFetch: Fetcher | null }).artworkFetch = openLibrary(asked)));  const phone = { authorization: `Bearer ${credential}` };  const made = await http<{ made?: { id: string } }>(slug, "POST", "/v1/act", { act: "create", args: { table: "book", data: { title: "The Hobbit", author: "J.R.R. Tolkien", isbn: "978-0-261-10334-4" } } }, phone);  expect(made.status, JSON.stringify(made.body)).toBe(200);  return { id: made.body.made!.id, phone };}const coverOf = (slug: string, id: string) => runInDurableObject(stub(slug), (_i, state) => (new Store(state.storage.sql, () => new Date()).get("book", id)!.data.cover as string | undefined) ?? null);describe("JOBS OUT M2: artwork as a step job", { timeout: 120_000 }, () => {  it("off: the write's own pass fills the cover, as before", async () => {    const slug = "step-art-off";    const asked: string[] = [];    const { id } = await bookWaitingForCover(slug, false, asked);    await runInDurableObject(stub(slug), async (instance: Business) => {      await (instance as unknown as { artworkRunning: Promise<void> | null }).artworkRunning;    });    expect(await coverOf(slug, id)).toBe(`${DATABASE_ID}/photos/${[...new Uint8Array(await crypto.subtle.digest("SHA-256", JPEG))].map((b) => b.toString(16).padStart(2, "0")).join("")}.jpg`);  });  it("on: neither the write nor the alarm fetches a picture; the run fills the cover through the door", async () => {    const slug = "step-art-on";    const asked: string[] = [];    const { id } = await bookWaitingForCover(slug, true, asked);    await runInDurableObject(stub(slug), async (instance: Business) => {      await (instance as unknown as { artworkRunning: Promise<void> | null }).artworkRunning;      await instance.alarm();    });    expect(asked, "the object asked no outside site").toEqual([]);    expect(await coverOf(slug, id)).toBeNull();    const row = (await jobRow(slug)).find((r) => r.kind === "artwork");    expect(row?.sent_at, "a run was put on the queue").not.toBeNull();    expect(await runStepJob({ door }, await messageOf(slug, "artwork"))).toBe("ran");    expect(asked.length).toBe(2);    expect(await coverOf(slug, id)).not.toBeNull();    const after = (await jobRow(slug)).find((r) => r.kind === "artwork");    expect(after!.due_at, "nothing left: no next run").toBeNull();  });});export type { StepJobMessage };// ── JOBS OUT W1..: the alarm's sweeps as step jobs ───────────────────────const changeCount = (slug: string) => runInDurableObject(stub(slug), (_i, state) => Number(state.storage.sql.exec("SELECT count(*) AS n FROM change").one().n));/** A personal object whose change log holds `n` todos' changes, aged past the row cap's 7-day floor, its window 3 rows. */async function longLog(slug: string, n: number, kind: string | null): Promise<Record<string, string>> {  const { credential } = await personalObject(slug, { open: ["todo", "todo_recurrence"] });  const phone = { authorization: `Bearer ${credential}` };  if (kind) expect((await http(slug, "PUT", "/v1/admin/business", { jobs: { [kind]: "on" } }, ADMIN)).status).toBe(200);  for (let i = 0; i < n; i++) expect((await http(slug, "POST", "/v1/act", { act: "create", args: { table: "todo", data: { title: `Invented errand ${i}` } } }, phone)).status).toBe(200);  await runInDurableObject(stub(slug), (_i, state) => void state.storage.sql.exec("UPDATE change SET at = ?", new Date(Date.now() - 8 * 86_400_000).toISOString()));  expect((await http(slug, "PUT", "/v1/admin/business", { change_rows: 3 }, ADMIN)).status).toBe(200);  return phone;}describe("JOBS OUT W1: the change log's trim as a step job", { timeout: 120_000 }, () => {  it("on: the alarm trims nothing; the run trims the log to its window, then rests", async () => {    const slug = "step-w1-on";    await longLog(slug, 6, "changes");    await runInDurableObject(stub(slug), (instance: Business) => instance.alarm());    expect(await changeCount(slug), "the alarm left the log to the job").toBeGreaterThan(3);    expect(await runStepJob({ door }, await messageOf(slug, "changes"))).toBe("ran");    expect(await changeCount(slug)).toBe(3);    const [row] = (await jobRow(slug)).filter((r) => r.kind === "changes");    expect(Number(row!.rest_until), "nothing left: it rests before it is asked for again").toBeGreaterThan(Date.now());    await runInDurableObject(stub(slug), (instance: Business) => instance.alarm());    expect((await jobRow(slug)).find((r) => r.kind === "changes")!.due_at, "a resting kind is not put on the queue").toBeNull();  });});describe("JOBS OUT W2: the act log's trim as a step job", { timeout: 120_000 }, () => {  it("on: the alarm trims nothing; the run lets the lines older than the window go, then rests", async () => {    const slug = "step-w2-on";    await personalObject(slug, {});    expect((await http(slug, "PUT", "/v1/admin/business", { jobs: { acts: "on" } }, ADMIN)).status).toBe(200);    const old = () => runInDurableObject(stub(slug), (_i, state) => Number(state.storage.sql.exec("SELECT count(*) AS n FROM acts WHERE at < '2026-07-01'").one().n));    await runInDurableObject(stub(slug), (_i, state) => {      for (let i = 0; i < 30; i++) state.storage.sql.exec("INSERT INTO acts (id, at, person_id, act, args, outcome) VALUES (?, '2026-06-01T00:00:00.000Z', NULL, 'create', '{}', 'done')", `invented-act-${i}`);      // The trim walks the log oldest first by rowid: every line is made old, as a log a season old is.      state.storage.sql.exec("UPDATE acts SET at = '2026-06-01T00:00:00.000Z'");    });    const lines = await old();    expect(lines).toBeGreaterThanOrEqual(30);    await runInDurableObject(stub(slug), (instance: Business) => instance.alarm());    expect(await old(), "the alarm left the log to the job").toBe(lines);    expect(await runStepJob({ door }, await messageOf(slug, "acts"))).toBe("ran");    expect(await old()).toBe(0);    expect(Number((await jobRow(slug)).find((r) => r.kind === "acts")!.rest_until)).toBeGreaterThan(Date.now());  });});describe("JOBS OUT W4: the alarm's timed sweeps (todos' next, windows' and asks' end, secrets past their until) as a step job", { timeout: 120_000 }, () => {  it("on: the alarm sweeps nothing; the run sweeps, then rests (a window past its end does not wait out the rest)", async () => {    const slug = "step-w4-on";    await personalObject(slug, {});    expect((await http(slug, "PUT", "/v1/admin/business", { jobs: { sweeps: "on" } }, ADMIN)).status).toBe(200);    const hits = () => runInDurableObject(stub(slug), (_i, state) => Number(state.storage.sql.exec("SELECT count(*) AS n FROM secret_hit").one().n));    await runInDurableObject(stub(slug), (_i, state) => void state.storage.sql.exec("INSERT INTO secret_hit (who, at) VALUES ('invented', ?)", Date.now() - 3 * 86_400_000));    await runInDurableObject(stub(slug), (instance: Business) => instance.alarm());    expect(await hits(), "the alarm left the sweep to the job").toBe(1);    const [row] = (await jobRow(slug)).filter((r) => r.kind === "sweeps");    expect(row!.sent_at, "the watchdog put a run on the queue").not.toBeNull();    expect(await runStepJob({ door }, await messageOf(slug, "sweeps"))).toBe("ran");    expect(await hits()).toBe(0);    expect(Number((await jobRow(slug)).find((r) => r.kind === "sweeps")!.rest_until)).toBeGreaterThan(Date.now());  });});