import test from "node:test"; import assert from "node:assert/strict"; import { D1_MAX_SQL_STATEMENT_BYTES, D1_QUERY_MAX_BODY_BYTES, JSON_STRING_WORST_CASE_EXPANSION, STORAGE_RESOURCE_NAME_MAX_BODY_BYTES, } from "../resource-limits.js"; test("the recorded D1 statement limit is Cloudflare's documented 100,000 bytes", () => { assert.equal(D1_MAX_SQL_STATEMENT_BYTES, 100_000); }); test("a resource-name body is bounded at 64 KiB", () => { assert.equal(STORAGE_RESOURCE_NAME_MAX_BODY_BYTES, 64 * 1024); }); test("a D1 query body is bounded at 1 MiB", () => { assert.equal(D1_QUERY_MAX_BODY_BYTES, 1024 * 1024); }); // The guard. D1_QUERY_MAX_BODY_BYTES is a flat number rather than a computed // expression, so nothing but this test holds it to the arithmetic that makes it // safe. If D1 ever raises its statement limit above 163,840 bytes, the worst-case // wire form of a legal statement exceeds 1 MiB and the route would begin rejecting // correct queries with nothing to signal why. This fails first instead. test("the D1 query body limit clears the worst-case wire form of a legal statement", () => { const worstCaseLegalBody = JSON_STRING_WORST_CASE_EXPANSION * D1_MAX_SQL_STATEMENT_BYTES + STORAGE_RESOURCE_NAME_MAX_BODY_BYTES; assert.ok( D1_QUERY_MAX_BODY_BYTES > worstCaseLegalBody, `D1_QUERY_MAX_BODY_BYTES (${D1_QUERY_MAX_BODY_BYTES}) must exceed the largest legal wire body (${worstCaseLegalBody}), or legal queries are rejected`, ); }); // The escape ceiling is the reason the bound is not simply D1's 100,000. Pin the // factor against the runtime rather than restating the literal: a single ASCII // control byte serializes to the six characters \uXXXX, which is the worst ratio a // JSON string can reach over bytes. test("the JSON worst-case expansion is the six-character \\uXXXX escape", () => { assert.equal(JSON_STRING_WORST_CASE_EXPANSION, 6); // Written as an escape rather than a literal control byte: a raw 0x01 in source // is invisible in most editors and diffs. const oneControlByte = "\u0001"; assert.equal(Buffer.byteLength(oneControlByte), 1); // minus the two quotes JSON.stringify wraps the string in assert.equal(JSON.stringify(oneControlByte).length - 2, JSON_STRING_WORST_CASE_EXPANSION); });