Cotton code
148 lines · 10.3 KB · TypeScriptRaw
/** * The size cap per object (owner, 26 Oct 2026): past it a write is refused * with `object_full` and a sentence, while sync and reads still answer. The * real caps are 9.5 GB of SQLite (under Cloudflare's hard 10 GB, coordinator 22 Nov * 2026) and 50 GB of media; a test lowers them on the * one object it fills. */import { env, runInDurableObject, SELF } from "cloudflare:test";import { describe, expect, it } from "vitest";import { DATABASE_CAP_BYTES, DATABASE_WARN_FRACTION, MEDIA_CAP_BYTES, type Business } from "../src/business.ts";import { ADMIN, DATABASE_ID, http, NOTES_OPEN, personalObject, tool } from "./personal.ts";function lower(slug: string, caps: Partial<Business["caps"]>): Promise<void> {  return runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (instance: Business) => {    Object.assign(instance.caps, caps);  });}const PNG = Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAACAAAAAYCAIAAAAUMWhjAAAAJElEQVR4nGM4EaBBU8QwasGoBaMWjFowasGoBaMWjFowNCwAAOj5wC7/fbJHAAAAAElFTkSuQmCC"), (c) => c.charCodeAt(0));function putMedia(slug: string, key: string, token: string, body: Uint8Array): Promise<Response> {  return SELF.fetch(`https://example.test/b/${slug}/v1/media/${key}`, { method: "PUT", headers: { authorization: `Bearer ${token}`, "content-type": "image/png", "content-length": String(body.length) }, body });}describe("the size cap per object", () => {  it("is 9.5 GB of SQLite, under Cloudflare's 10 GB however a GB is counted, and 50 GB of media", () => {    expect(DATABASE_CAP_BYTES).toBe(9_500_000_000);    expect(DATABASE_CAP_BYTES).toBeLessThan(10 * 1000 ** 3);    expect(DATABASE_WARN_FRACTION).toBe(0.8);    expect(MEDIA_CAP_BYTES).toBe(50 * 1024 ** 3);  });  it("refuses a write act, an import batch and an MCP write on a full database, and still syncs and reads", async () => {    const SLUG = "caps-full";    const { credential, owner } = await personalObject(SLUG, NOTES_OPEN);    const auth = { authorization: `Bearer ${credential}` };    const before = await http(SLUG, "POST", "/v1/act", { act: "create", args: { table: "note", data: { title: "before it filled" } } }, auth);    expect(before.status, JSON.stringify(before.body)).toBe(200);    await lower(SLUG, { database: 1 });    const act = await http<{ code: string; message: string }>(SLUG, "POST", "/v1/act", { act: "create", args: { table: "note", data: { title: "after" } } }, auth);    expect(act).toMatchObject({ status: 413, body: { code: "object_full" } });    expect(act.body.message).toBe("This database has reached its size limit: it still syncs and reads, but takes nothing new.");    const batch = { workspaceId: DATABASE_ID, channel: "whatsapp", dm: { label: "A Friend", phone: "919800000001" }, messages: [{ direction: "in", body: "hi", sentAt: "2026-10-01T10:00:00.000Z", externalId: "wa-1" }] };    expect(await http(SLUG, "POST", "/v1/import/messages", batch, auth)).toMatchObject({ status: 413, body: { code: "object_full" } });    expect(await http(SLUG, "POST", "/v1/admin/import", { rows: [{ table: "note", data: { title: "seed" } }] }, ADMIN)).toMatchObject({ status: 413, body: { code: "object_full" } });    const mcp = await tool(SLUG, owner, "create_record", { table: "note", data: { title: "by mcp" } });    expect(mcp.isError).toBe(true);    expect(mcp.content[0]!.text).toMatch(/size limit/);    const sync = await http<{ rows: { table: string; data: { title?: string } }[] }>(SLUG, "GET", "/v1/sync?since=0", undefined, auth);    expect(sync.status).toBe(200);    expect(sync.body.rows.filter((r) => r.table === "note").map((r) => r.data.title)).toEqual(["before it filled"]);    expect((await tool(SLUG, owner, "list_records", { table: "note" })).isError).toBe(false);  });  it("says from 80% of the cap how full the database is, on a pass's last page and in storage_summary, and nothing below", async () => {    const SLUG = "caps-filling";    const { credential, owner } = await personalObject(SLUG, NOTES_OPEN);    const auth = { authorization: `Bearer ${credential}` };    type Room = { room?: { bytes: number; cap: number; used: number } };    const quiet = await http<Room>(SLUG, "GET", "/v1/sync?since=0", undefined, auth);    expect(quiet.status).toBe(200);    expect(quiet.body).not.toHaveProperty("room");    const bytes = await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(SLUG)), (_i, state) => state.storage.sql.databaseSize);    await lower(SLUG, { database: Math.floor(bytes / 0.85) });    const filling = await http<Room>(SLUG, "GET", "/v1/sync?since=0", undefined, auth);    expect(filling.body.room).toMatchObject({ cap: Math.floor(bytes / 0.85) });    expect(filling.body.room!.used).toBeGreaterThanOrEqual(0.8);    expect(filling.body.room!.used).toBeLessThan(1);    const summary = JSON.parse((await tool(SLUG, owner, "storage_summary", {})).content[0]!.text) as { database: { warning?: string } };    expect(summary.database.warning).toMatch(/^The database is (8\d|9\d)% full: new records are refused once it reaches its cap\.$/);    // Still writes below the cap.    expect((await http(SLUG, "POST", "/v1/act", { act: "create", args: { table: "note", data: { title: "still room" } } }, auth)).status).toBe(200);    await lower(SLUG, { database: 1 });    const full = JSON.parse((await tool(SLUG, owner, "storage_summary", {})).content[0]!.text) as { database: { warning?: string } };    expect(full.database.warning).toBe("The database is full: it takes nothing new until something is removed.");  });  it("counts media on every PUT, refuses past the cap, and recounts from the bucket", async () => {    const SLUG = "caps-media";    // The owner's device PUTs a person's photos (an assistant's token may not: AVATAR SEAL 3).    const { credential: owner } = await personalObject(SLUG, NOTES_OPEN);    const key = (n: number) => `${DATABASE_ID}/photos/${String(n).repeat(64)}.png`;    await lower(SLUG, { media: PNG.length * 2 });    expect((await putMedia(SLUG, key(1), owner, PNG)).status).toBe(201);    expect(await (await putMedia(SLUG, key(1), owner, PNG)).json(), "the same bytes again add nothing").toEqual({ stored: false, bytes: PNG.length });    expect((await putMedia(SLUG, key(2), owner, PNG)).status).toBe(201);    const third = await putMedia(SLUG, key(3), owner, PNG);    expect(third.status).toBe(413);    expect(await third.json()).toMatchObject({ code: "object_full" });    // A read still answers.    expect((await SELF.fetch(`https://example.test/b/${SLUG}/v1/media/${key(1)}`, { headers: { authorization: `Bearer ${owner}` } })).status).toBe(200);    const recount = await http<{ media_bytes: number }>(SLUG, "POST", "/v1/admin/media/recount", {}, ADMIN);    expect(recount, JSON.stringify(recount.body)).toMatchObject({ status: 200, body: { media_bytes: PNG.length * 2 } });  });  it("holds an account to its own media limit, and back to the default", async () => {    const SLUG = "caps-own";    // The owner's device lays the photos (a token writes no sealed kind: AVATAR SEAL 4); the assistant reads the summary.    const { credential, owner } = await personalObject(SLUG, NOTES_OPEN);    const key = (n: number) => `${DATABASE_ID}/photos/${String(n).repeat(64)}.png`;    const summary = async () => JSON.parse((await tool(SLUG, owner, "storage_summary", {})).content[0]!.text) as { media: { cap: number } };    const budget = PNG.length;    await lower(SLUG, { media: budget });    expect((await summary()).media.cap, "the default, with no limit of its own").toBe(budget);    expect((await putMedia(SLUG, key(1), credential, PNG)).status).toBe(201);    const full = await putMedia(SLUG, key(2), credential, PNG);    expect(full.status, "the default refuses").toBe(413);    const refusal = await full.json();    expect(refusal).toMatchObject({ code: "object_full" });    const raised = await http(SLUG, "POST", "/v1/admin/media/cap", { bytes: budget * 3 }, ADMIN);    expect(raised, JSON.stringify(raised.body)).toMatchObject({ status: 200, body: { cap: budget * 3, default_cap: budget, media_bytes: budget } });    expect((await summary()).media.cap, "the size answer says the account's own limit").toBe(budget * 3);    expect((await putMedia(SLUG, key(2), credential, PNG)).status, "the raised limit lets it through").toBe(201);    expect(await http(SLUG, "POST", "/v1/admin/media/recount", {}, ADMIN)).toMatchObject({ status: 200, body: { cap: budget * 3 } });    expect(await http(SLUG, "POST", "/v1/admin/media/cap", { bytes: null }, ADMIN)).toMatchObject({ status: 200, body: { cap: budget } });    expect((await summary()).media.cap).toBe(budget);    const again = await putMedia(SLUG, key(3), credential, PNG);    expect(again.status, "back on the default, it refuses again").toBe(413);    expect(await again.json(), "in the same words").toEqual(refusal);  });  it("refuses a media limit that is no whole number of bytes, below the default or above 8 TiB", async () => {    const SLUG = "caps-bad";    await personalObject(SLUG, NOTES_OPEN);    for (const bytes of [MEDIA_CAP_BYTES - 1, 8 * 1024 ** 4 + 1, MEDIA_CAP_BYTES + 0.5, String(MEDIA_CAP_BYTES), true, undefined]) {      expect(await http(SLUG, "POST", "/v1/admin/media/cap", { bytes }, ADMIN), String(bytes)).toMatchObject({ status: 400, body: { code: "bad_request" } });    }    expect((await http(SLUG, "POST", "/v1/admin/media/cap", { bytes: 8 * 1024 ** 4 }, ADMIN)).status, "8 TiB itself is allowed").toBe(200);    expect((await http(SLUG, "POST", "/v1/admin/media/cap", { bytes: MEDIA_CAP_BYTES }, ADMIN)).status, "the default itself is allowed").toBe(200);  });  it("takes the limit from the admin token only (ROUTES-AUDIT 18), on a personal account only", async () => {    const SLUG = "caps-who";    const { credential } = await personalObject(SLUG, NOTES_OPEN);    expect((await http(SLUG, "POST", "/v1/admin/media/cap", { bytes: MEDIA_CAP_BYTES }, { authorization: `Bearer ${credential}` })).status, "a phone's credential is not the authority").toBe(403);    expect((await http(SLUG, "POST", "/v1/admin/media/cap", { bytes: MEDIA_CAP_BYTES })).status).toBe(403);    const BUSINESS = "caps-business";    expect((await http(BUSINESS, "PUT", "/v1/admin/business", { name: "A Shop", kind: "business" }, ADMIN)).status).toBe(200);    expect(await http(BUSINESS, "POST", "/v1/admin/media/cap", { bytes: MEDIA_CAP_BYTES }, ADMIN)).toMatchObject({ status: 404, body: { code: "not_personal" } });  });});