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
54 changes: 53 additions & 1 deletion pkgs/id/hosted-worker/src/user-do.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,41 @@ function json(body: unknown, status = 200): Response {
});
}

function ceilingExceeded(headroom: number): FailClosed {
return new FailClosed(
413,
"ceiling_exceeded",
`storage ceiling exceeded: value is larger than the ${headroom} bytes of headroom; reads and export remain available`,
);
}

/** Reads a request body as text, giving up as soon as it exceeds
* `limit` bytes so an oversized body is never buffered whole. */
async function readTextUpTo(req: Request, limit: number): Promise<string | null> {
if (!req.body) return "";
const reader = req.body.getReader();
const decoder = new TextDecoder();
const chunks: Uint8Array[] = [];
let total = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) break;
total += value.byteLength;
if (total > limit) {
await reader.cancel();
return null;
}
chunks.push(value);
}
const bytes = new Uint8Array(total);
let offset = 0;
for (const chunk of chunks) {
bytes.set(chunk, offset);
offset += chunk.byteLength;
}
return decoder.decode(bytes);
}

export class UserDO {
private state: DOState;
private ready: Promise<void>;
Expand Down Expand Up @@ -145,6 +180,14 @@ export class UserDO {
}
}

/** The largest value (bytes) a KV PUT over `priorBytes` of existing
* data can carry and still pass assertWritable; null = no ceiling. */
private kvHeadroom(priorBytes: number): number | null {
const ceiling = this.ceilingBytes();
if (ceiling === null) return null;
return ceiling - this.usage().storage_bytes + priorBytes;
}

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 @@ -287,11 +330,20 @@ 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);
const headroom = this.kvHeadroom(priorBytes);
let value: string | null;
if (headroom === null) {
value = await req.text();
} else {
const declared = req.headers.get("content-length");
if (declared !== null && Number(declared) > headroom) throw ceilingExceeded(headroom);
value = await readTextUpTo(req, headroom);
if (value === null) throw ceilingExceeded(headroom);
}
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",
Expand Down
29 changes: 29 additions & 0 deletions pkgs/id/hosted-worker/test/usage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,35 @@ test("at cap: writes fail closed, reads and export succeed, delete recovers head
assert.equal(put3.status, 200, "headroom recovered after delete");
});

test("kv PUT over headroom is refused early on declared length, and by a capped read when chunked", async () => {
const { doA } = makeDO({ USER_CEILING_BYTES: "10" });
const declared = await doA.fetch(routed("/v1/kv/big", { method: "PUT", body: "12345678901" }));
assert.equal(declared.status, 413);
assert.equal(((await declared.json()) as { error: string }).error, "ceiling_exceeded");

const chunkedBody = new ReadableStream({
start(c) {
c.enqueue(new TextEncoder().encode("12345"));
c.enqueue(new TextEncoder().encode("678901"));
c.close();
},
});
const chunked = await doA.fetch(
routed("/v1/kv/big", { method: "PUT", body: chunkedBody, duplex: "half" } as RequestInit),
);
assert.equal(chunked.status, 413);
assert.equal(((await chunked.json()) as { error: string }).error, "ceiling_exceeded");
assert.equal((await getUsage(doA)).storage_bytes, 0, "no refused write is stored");
});

test("kv overwrite headroom counts the prior value", async () => {
const { doA } = makeDO({ USER_CEILING_BYTES: "10" });
assert.equal((await doA.fetch(routed("/v1/kv/k1", { method: "PUT", body: "123456" }))).status, 200);
assert.equal((await doA.fetch(routed("/v1/kv/k1", { method: "PUT", body: "1234567890" }))).status, 200);
assert.equal((await doA.fetch(routed("/v1/kv/k1", { method: "PUT", body: "12345678901" }))).status, 413);
assert.equal((await getUsage(doA)).storage_bytes, 10);
});

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");
Expand Down