Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pkgs/id/hosted-worker/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
32 changes: 24 additions & 8 deletions pkgs/id/hosted-worker/smoke/smoke.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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); }
}

Expand Down
97 changes: 97 additions & 0 deletions pkgs/id/hosted-worker/src/user-do.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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,
Expand All @@ -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(
Expand Down Expand Up @@ -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],
Expand All @@ -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);
Expand Down
171 changes: 171 additions & 0 deletions pkgs/id/hosted-worker/test/usage.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>[];
return { toArray: () => rows };
}
stmt.run(...(params as never[]));
return { toArray: () => [] as Record<string, unknown>[] };
},
};
}

function fakeBucket() {
const objects = new Map<string, Uint8Array>();
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<string, unknown> = {}) {
const bucket = fakeBucket();
const state = {
id: { name: A },
storage: { sql: fakeSql() },
blockConcurrencyWhile: async <T,>(fn: () => Promise<T>): Promise<T> => 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<Usage> {
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<string, string>; 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<string, string>;
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);
});
6 changes: 6 additions & 0 deletions pkgs/id/hosted-worker/wrangler.test.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"