From 685f3fcf659919bd1c0f4570e3c889c4995df52d Mon Sep 17 00:00:00 2001 From: fleet lane code-b Date: Sat, 14 Nov 2026 10:48:08 -0600 Subject: [PATCH] feat(id): hosted Worker slice B - metering, ceilings, export-at-cap (#9955) Usage is derived from the tables on every read (requests, kv/blob counts and bytes), so metering cannot drift. A USER_CEILING_BYTES ceiling fails writes closed with 413 ceiling_exceeded (kv PUT gates on the overwrite delta, blob PUT on new-reference size; a deduped re-PUT does not double-charge). At cap the object stays read-only and exportable: GET /v1/export serves kv + blob references + usage, and deletes (incl. a new kv DELETE) stay available to recover headroom. Malformed ceiling config fails writes closed. Local verification only. --- pkgs/id/hosted-worker/package.json | 2 +- pkgs/id/hosted-worker/smoke/smoke.mjs | 32 +++-- pkgs/id/hosted-worker/src/user-do.ts | 97 +++++++++++++ pkgs/id/hosted-worker/test/usage.test.ts | 171 +++++++++++++++++++++++ pkgs/id/hosted-worker/wrangler.test.toml | 6 + 5 files changed, 299 insertions(+), 9 deletions(-) create mode 100644 pkgs/id/hosted-worker/test/usage.test.ts diff --git a/pkgs/id/hosted-worker/package.json b/pkgs/id/hosted-worker/package.json index 1e5c639db..c95184b77 100644 --- a/pkgs/id/hosted-worker/package.json +++ b/pkgs/id/hosted-worker/package.json @@ -6,7 +6,7 @@ "scripts": { "dev": "wrangler dev", "typecheck": "tsc --noEmit", - "test": "node --test test/routing.test.ts test/blobs.test.ts", + "test": "node --test test/routing.test.ts test/blobs.test.ts test/usage.test.ts", "smoke": "node smoke/smoke.mjs" }, "devDependencies": { diff --git a/pkgs/id/hosted-worker/smoke/smoke.mjs b/pkgs/id/hosted-worker/smoke/smoke.mjs index 333c11a47..d50675b4a 100644 --- a/pkgs/id/hosted-worker/smoke/smoke.mjs +++ b/pkgs/id/hosted-worker/smoke/smoke.mjs @@ -100,27 +100,43 @@ async function waitUp(port, tries) { // Slice A (#9954): blob round-trip via reference indirection, // user isolation by hash, dedup, reference-only delete. + // Fresh bindings per run: wrangler dev persists DO/R2 state + // under .wrangler/state, and a previous run's references for + // the fixed A/B bindings would (correctly) still resolve. + const hex32 = () => Array.from({ length: 32 }, () => "0123456789abcdef"[Math.floor(Math.random() * 16)]).join(""); + const BA = hex32(); + const BB = hex32(); const blob = (name, binding, j, hash) => "/v1/blobs" + (hash ? "/" + hash : "") + "?name=" + name + "&binding=" + binding + "&jurisdiction=" + j; const bytes = "hosted blob bytes"; - r = await fetch(base + blob(A, A, "us"), { method: "PUT", body: bytes }); + r = await fetch(base + blob(BA, BA, "us"), { method: "PUT", body: bytes }); const putBody = await r.json(); check("PUT blob on A", r.status === 200 && putBody.size === bytes.length && /^[0-9a-f]{64}$/.test(putBody.hash), JSON.stringify(putBody)); const hash = putBody.hash; - r = await fetch(base + blob(A, A, "us", hash)); + r = await fetch(base + blob(BA, BA, "us", hash)); check("GET blob on A round-trips", r.status === 200 && (await r.text()) === bytes); - r = await fetch(base + blob(B, B, "us", hash)); + r = await fetch(base + blob(BB, BB, "us", hash)); check("B cannot read A's blob by hash (isolation)", r.status === 404); - r = await fetch(base + blob(B, B, "us"), { method: "PUT", body: bytes }); + r = await fetch(base + blob(BB, BB, "us"), { method: "PUT", body: bytes }); const putB = await r.json(); check("PUT same bytes on B dedups to the same hash", r.status === 200 && putB.hash === hash && putB.deduped === true, JSON.stringify(putB)); - r = await fetch(base + blob(B, B, "us", hash)); + r = await fetch(base + blob(BB, BB, "us", hash)); check("GET blob on B via its own reference", r.status === 200 && (await r.text()) === bytes); - r = await fetch(base + blob(A, A, "us", hash), { method: "DELETE" }); + r = await fetch(base + blob(BA, BA, "us", hash), { method: "DELETE" }); check("DELETE blob reference on A", r.status === 200); - r = await fetch(base + blob(A, A, "us", hash)); + r = await fetch(base + blob(BA, BA, "us", hash)); check("A can no longer read after delete", r.status === 404); - r = await fetch(base + blob(B, B, "us", hash)); + r = await fetch(base + blob(BB, BB, "us", hash)); check("B still reads after A's delete (shared bytes kept)", r.status === 200); + + // Slice B (#9955): the usage read path reports live metering + // and the configured ceiling. + const usageUrl = (name, binding, j) => "/v1/usage?name=" + name + "&binding=" + binding + "&jurisdiction=" + j; + r = await fetch(base + usageUrl(BB, BB, "us")); + const usage = await r.json(); + check("usage reports metering + ceiling", r.status === 200 && usage.blob_count === 1 && usage.blob_bytes === bytes.length && usage.ceiling_bytes === 1073741824 && usage.requests > 0 && usage.at_cap === false, JSON.stringify(usage)); + r = await fetch(base + "/v1/export?name=" + BB + "&binding=" + BB + "&jurisdiction=us"); + const exp = await r.json(); + check("export carries the user's blobs and kv", r.status === 200 && Array.isArray(exp.blobs) && exp.blobs.length === 1 && exp.usage.storage_bytes >= bytes.length, JSON.stringify(exp).slice(0, 160)); } finally { await stopDev(dev); } } diff --git a/pkgs/id/hosted-worker/src/user-do.ts b/pkgs/id/hosted-worker/src/user-do.ts index 3e63cad62..402a4e945 100644 --- a/pkgs/id/hosted-worker/src/user-do.ts +++ b/pkgs/id/hosted-worker/src/user-do.ts @@ -40,6 +40,10 @@ interface DOState { } interface Env { BLOBS?: R2BucketLike; + /** Slice B (#9955): per-user storage ceiling in bytes, as a + * string var. Absent/empty = no ceiling. A malformed value + * fails writes closed (see ceilingBytes). */ + USER_CEILING_BYTES?: string; } function json(body: unknown, status = 200): Response { @@ -79,6 +83,57 @@ export class UserDO { }); } + /** The configured storage ceiling in bytes; null = no ceiling. + * A malformed value is a configuration error: writes fail + * closed rather than silently running unceilinged. */ + private ceilingBytes(): number | null { + const raw = this.env.USER_CEILING_BYTES; + if (raw === undefined || raw === "") return null; + const n = Number(raw); + if (!Number.isInteger(n) || n < 0) { + throw new FailClosed(500, "ceiling_misconfigured", "USER_CEILING_BYTES is not a non-negative integer; writes fail closed"); + } + return n; + } + + /** Usage accounting, derived from the tables on every read so + * the numbers can never drift from the data they describe. + * blob_bytes counts bytes referenced by THIS user (a deduped + * blob referenced by two users counts toward both — the + * reference is what each user's storage pays for). */ + private usage() { + const sql = this.state.storage.sql; + const kv = sql.exec("SELECT COUNT(*) AS n, COALESCE(SUM(LENGTH(value)), 0) AS bytes FROM kv").toArray()[0]; + const blobs = sql.exec("SELECT COUNT(*) AS n, COALESCE(SUM(size), 0) AS bytes FROM blobs").toArray()[0]; + const kvBytes = Number(kv.bytes); + const blobBytes = Number(blobs.bytes); + return { + requests: Number(this.meta("requests") ?? "0"), + kv_count: Number(kv.n), + kv_bytes: kvBytes, + blob_count: Number(blobs.n), + blob_bytes: blobBytes, + storage_bytes: kvBytes + blobBytes, + }; + } + + /** Fail a write closed when it would push storage over the + * ceiling. Reads, export, and deletes never call this: at cap + * the object is read-only + exportable, and deletes are how a + * user recovers headroom. */ + private assertWritable(deltaBytes: number) { + const ceiling = this.ceilingBytes(); + if (ceiling === null) return; + const after = this.usage().storage_bytes + deltaBytes; + if (after > ceiling) { + throw new FailClosed( + 413, + "ceiling_exceeded", + `storage ceiling exceeded: ${after} bytes would exceed the ${ceiling}-byte ceiling; reads and export remain available`, + ); + } + } + private meta(key: string): string | null { const rows = this.state.storage.sql.exec("SELECT value FROM meta WHERE key = ?", key).toArray(); return rows.length === 0 ? null : String(rows[0].value); @@ -125,7 +180,36 @@ export class UserDO { await this.ready; try { const { bindingId, jurisdiction } = this.guard(req); + this.state.storage.sql.exec( + "INSERT INTO meta (key, value) VALUES ('requests', '1') ON CONFLICT(key) DO UPDATE SET value = CAST(value AS INTEGER) + 1", + ); const url = new URL(req.url); + if (url.pathname === "/v1/usage" && req.method === "GET") { + const usage = this.usage(); + const ceiling = this.ceilingBytes(); + return json({ + binding_id: bindingId, + jurisdiction, + ...usage, + ceiling_bytes: ceiling, + at_cap: ceiling !== null && usage.storage_bytes >= ceiling, + }); + } + if (url.pathname === "/v1/export" && req.method === "GET") { + // Export stays available at cap by design (#3811): it is + // a read, and it is how a capped user gets their data out. + const kvRows = this.state.storage.sql.exec("SELECT key, value FROM kv ORDER BY key").toArray(); + const blobRows = this.state.storage.sql + .exec("SELECT hash, size, created_at FROM blobs ORDER BY hash") + .toArray(); + return json({ + binding_id: bindingId, + jurisdiction, + usage: this.usage(), + kv: Object.fromEntries(kvRows.map((r) => [String(r.key), String(r.value)])), + blobs: blobRows.map((r) => ({ hash: String(r.hash), size: Number(r.size), created_at: String(r.created_at) })), + }); + } if (url.pathname === "/v1/state" && req.method === "GET") { return json({ binding_id: bindingId, @@ -143,6 +227,8 @@ export class UserDO { // Content-addressed dedup: identical bytes are stored // once, whoever uploads them; the reference row below is // what grants THIS user access. + const priorRef = this.state.storage.sql.exec("SELECT hash FROM blobs WHERE hash = ?", hash).toArray(); + this.assertWritable(priorRef.length === 0 ? bytes.byteLength : 0); const existing = await bucket.head(hash); if (!existing) await bucket.put(hash, bytes); this.state.storage.sql.exec( @@ -191,6 +277,9 @@ export class UserDO { const kvMatch = url.pathname.match(/^\/v1\/kv\/([A-Za-z0-9._-]{1,128})$/); if (kvMatch && req.method === "PUT") { const value = await req.text(); + const prior = this.state.storage.sql.exec("SELECT LENGTH(value) AS n FROM kv WHERE key = ?", kvMatch[1]).toArray(); + const priorBytes = prior.length === 0 ? 0 : Number(prior[0].n); + this.assertWritable(new TextEncoder().encode(value).byteLength - priorBytes); this.state.storage.sql.exec( "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", kvMatch[1], @@ -203,6 +292,14 @@ export class UserDO { if (rows.length === 0) return json({ error: "not_found" }, 404); return json({ key: kvMatch[1], value: String(rows[0].value) }); } + if (kvMatch && req.method === "DELETE") { + // Deletes only shrink usage, so they stay available at + // cap — they are how a capped user recovers headroom. + const rows = this.state.storage.sql.exec("SELECT key FROM kv WHERE key = ?", kvMatch[1]).toArray(); + if (rows.length === 0) return json({ error: "not_found" }, 404); + this.state.storage.sql.exec("DELETE FROM kv WHERE key = ?", kvMatch[1]); + return json({ key: kvMatch[1], deleted: true }); + } return json({ error: "not_found" }, 404); } catch (e) { if (e instanceof FailClosed) return json({ error: e.code, message: e.message }, e.status); diff --git a/pkgs/id/hosted-worker/test/usage.test.ts b/pkgs/id/hosted-worker/test/usage.test.ts new file mode 100644 index 000000000..fdac4d7af --- /dev/null +++ b/pkgs/id/hosted-worker/test/usage.test.ts @@ -0,0 +1,171 @@ +// Slice B of #3811 (#9955): metering accuracy, at-cap behavior +// (write rejected, read + export succeed), and recovery via +// delete. Same harness style as blobs.test.ts: the real UserDO +// against in-memory SQLite and an in-memory bucket. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { DatabaseSync } from "node:sqlite"; +import { UserDO, HDR_BINDING, HDR_JURISDICTION, HDR_ROUTED } from "../src/user-do.ts"; + +const A = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + +function fakeSql() { + const db = new DatabaseSync(":memory:"); + return { + exec(query: string, ...params: unknown[]) { + const stmt = db.prepare(query); + if (/^\s*select/i.test(query)) { + const rows = stmt.all(...(params as never[])) as Record[]; + return { toArray: () => rows }; + } + stmt.run(...(params as never[])); + return { toArray: () => [] as Record[] }; + }, + }; +} + +function fakeBucket() { + const objects = new Map(); + return { + objects, + async head(key: string) { + const v = objects.get(key); + return v ? { size: v.byteLength } : null; + }, + async get(key: string) { + const v = objects.get(key); + if (!v) return null; + return { + size: v.byteLength, + body: new ReadableStream({ + start(c) { + c.enqueue(v); + c.close(); + }, + }), + }; + }, + async put(key: string, value: ArrayBuffer | Uint8Array) { + objects.set(key, value instanceof Uint8Array ? value : new Uint8Array(value)); + }, + async delete(key: string) { + objects.delete(key); + }, + }; +} + +function makeDO(env: Record = {}) { + const bucket = fakeBucket(); + const state = { + id: { name: A }, + storage: { sql: fakeSql() }, + blockConcurrencyWhile: async (fn: () => Promise): Promise => fn(), + }; + return { doA: new UserDO(state as never, { BLOBS: bucket, ...env } as never), bucket }; +} + +function routed(path: string, init: RequestInit = {}): Request { + const headers = new Headers(init.headers); + headers.set(HDR_BINDING, A); + headers.set(HDR_JURISDICTION, "us"); + headers.set(HDR_ROUTED, "restricted"); + return new Request("https://do" + path, { ...init, headers }); +} + +interface Usage { + requests: number; + kv_count: number; + kv_bytes: number; + blob_count: number; + blob_bytes: number; + storage_bytes: number; + ceiling_bytes: number | null; + at_cap: boolean; +} + +async function getUsage(d: UserDO): Promise { + const r = await d.fetch(routed("/v1/usage")); + assert.equal(r.status, 200); + return (await r.json()) as Usage; +} + +test("metering is accurate across kv and blob writes", async () => { + const { doA } = makeDO(); + await doA.fetch(routed("/v1/kv/k1", { method: "PUT", body: "12345" })); + await doA.fetch(routed("/v1/kv/k2", { method: "PUT", body: "1234567" })); + const blob = new TextEncoder().encode("blobbytes!"); + await doA.fetch(routed("/v1/blobs", { method: "PUT", body: blob })); + const u = await getUsage(doA); + assert.equal(u.kv_count, 2); + assert.equal(u.kv_bytes, 12); + assert.equal(u.blob_count, 1); + assert.equal(u.blob_bytes, 10); + assert.equal(u.storage_bytes, 22); + assert.equal(u.ceiling_bytes, null); + assert.equal(u.at_cap, false); + // 3 writes + this usage read were all counted as requests. + assert.equal(u.requests, 4); + // Overwriting a key re-meters by delta, not by addition. + await doA.fetch(routed("/v1/kv/k1", { method: "PUT", body: "xy" })); + const u2 = await getUsage(doA); + assert.equal(u2.kv_bytes, 9); + assert.equal(u2.storage_bytes, 19); +}); + +test("at cap: writes fail closed, reads and export succeed, delete recovers headroom", async () => { + const { doA } = makeDO({ USER_CEILING_BYTES: "10" }); + const put1 = await doA.fetch(routed("/v1/kv/k1", { method: "PUT", body: "123456" })); + assert.equal(put1.status, 200); + const put2 = await doA.fetch(routed("/v1/kv/k2", { method: "PUT", body: "12345" })); + assert.equal(put2.status, 413); + assert.equal(((await put2.json()) as { error: string }).error, "ceiling_exceeded"); + + const blobPut = await doA.fetch(routed("/v1/blobs", { method: "PUT", body: new TextEncoder().encode("12345") })); + assert.equal(blobPut.status, 413, "blob writes are ceilinged too"); + + const read = await doA.fetch(routed("/v1/kv/k1")); + assert.equal(read.status, 200, "reads continue at cap"); + assert.equal(((await read.json()) as { value: string }).value, "123456"); + + const exp = await doA.fetch(routed("/v1/export")); + assert.equal(exp.status, 200, "export remains available at cap"); + const expBody = (await exp.json()) as { kv: Record; usage: Usage }; + assert.equal(expBody.kv.k1, "123456"); + assert.equal(expBody.usage.storage_bytes, 6); + + const u = await getUsage(doA); + assert.equal(u.at_cap, false, "6 of 10 bytes used is not at cap"); + const del = await doA.fetch(routed("/v1/kv/k1", { method: "DELETE" })); + assert.equal(del.status, 200, "deletes stay available at cap"); + const put3 = await doA.fetch(routed("/v1/kv/k2", { method: "PUT", body: "12345" })); + assert.equal(put3.status, 200, "headroom recovered after delete"); +}); + +test("a deduped re-PUT of the same blob does not double-charge", async () => { + const { doA } = makeDO({ USER_CEILING_BYTES: "10" }); + const blob = new TextEncoder().encode("0123456789"); + assert.equal((await doA.fetch(routed("/v1/blobs", { method: "PUT", body: blob }))).status, 200); + assert.equal((await doA.fetch(routed("/v1/blobs", { method: "PUT", body: blob }))).status, 200); + const u = await getUsage(doA); + assert.equal(u.blob_count, 1); + assert.equal(u.blob_bytes, 10); +}); + +test("export carries kv, blob references, and usage", async () => { + const { doA } = makeDO(); + await doA.fetch(routed("/v1/kv/note", { method: "PUT", body: "hi" })); + await doA.fetch(routed("/v1/blobs", { method: "PUT", body: new TextEncoder().encode("data") })); + const exp = await doA.fetch(routed("/v1/export")); + const body = (await exp.json()) as { + binding_id: string; + kv: Record; + blobs: { hash: string; size: number }[]; + usage: Usage; + }; + assert.equal(body.binding_id, A); + assert.deepEqual(body.kv, { note: "hi" }); + assert.equal(body.blobs.length, 1); + assert.equal(body.blobs[0].size, 4); + assert.match(body.blobs[0].hash, /^[0-9a-f]{64}$/); + assert.equal(body.usage.storage_bytes, 6); +}); diff --git a/pkgs/id/hosted-worker/wrangler.test.toml b/pkgs/id/hosted-worker/wrangler.test.toml index 76b9aefd6..cd61b7d66 100644 --- a/pkgs/id/hosted-worker/wrangler.test.toml +++ b/pkgs/id/hosted-worker/wrangler.test.toml @@ -23,3 +23,9 @@ new_sqlite_classes = ["UserDO"] [[r2_buckets]] binding = "BLOBS" bucket_name = "id-hosted-blobs-test" + +# Slice B (#9955): a generous ceiling for the harness so the usage +# read path reports a configured ceiling without tripping it; the +# at-cap behavior itself is proven in test/usage.test.ts. +[vars] +USER_CEILING_BYTES = "1073741824"