diff --git a/AGENTS.md b/AGENTS.md index 7c9bf66..9d3b742 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -102,8 +102,9 @@ preflight CLI entry with a module cycle (exit 13), before publication. Keep both signed tags immutable and retain their releases as failed attempts. `@pegma/storage-dynamodb@0.4.5` is now a [qualified trusted runtime](https://github.com/pegma-dev/storage-core/releases/tag/v0.4.5), -retaining exact Core `0.4.0`. D1 `0.4.6` is the unpublished candidate for optional -concurrent keyed-read batching; its default remains `readBatchSize: 1`. +retaining exact Core `0.4.0`. Published D1 `0.4.6` provides opt-in keyed-read +batching. D1 `0.4.7` is the unpublished candidate adding whole-partition reads +to that queue; its default remains `readBatchSize: 1`. Its own review, release qualification and host Free-plan acceptance remain separate gates. See `docs/RELEASING.md` and the D1 package README. The port offers keyed access, diff --git a/README.md b/README.md index eaf08cf..d3d0dc6 100644 --- a/README.md +++ b/README.md @@ -219,10 +219,10 @@ and what you decode is what the last writer decided. | `@pegma/storage-cloudflare-d1` | available; passes the same conformance run | | `@pegma/storage-dynamodb` | available; passes the same conformance run | -Published versions are Core `0.4.0`, Azure Tables `0.4.0`, D1 `0.4.1` and the +Published versions are Core `0.4.0`, Azure Tables `0.4.0`, D1 `0.4.6` and the [qualified DynamoDB `0.4.5` runtime](https://github.com/pegma-dev/storage-core/releases/tag/v0.4.5). -D1 `0.4.6` remains an unpublished candidate for optional concurrent keyed-read -batching, with direct reads still the default; see its +D1 `0.4.7` is the unpublished candidate for optional concurrent keyed and +whole-partition read batching, with direct reads still the default; see its [package README](packages/storage-cloudflare-d1/README.md). This candidate does not establish a released adapter or live Workers Free host acceptance. diff --git a/docs/AWS_ADAPTER.md b/docs/AWS_ADAPTER.md index 4a415b9..0c61d6f 100644 --- a/docs/AWS_ADAPTER.md +++ b/docs/AWS_ADAPTER.md @@ -86,8 +86,9 @@ runtime pins it exactly. `0.4.2` is registration-only metadata under `bootstrap` not a usable adapter release. The qualified `0.4.5` runtime completed the reviewed signed-source and trusted-publisher flow. Existing repository-wide tags `v0.4.0`, `v0.4.1`, failed `v0.4.3` and failed -`v0.4.4` must never be reused. The separate D1 `0.4.6` candidate remains -unpublished and requires its own review and release qualification. +`v0.4.4` must never be reused. D1 `0.4.6` is published; the separate D1 +`0.4.7` mixed-read batching candidate remains unpublished and requires its own +review and release qualification. Unprivileged validation runs the full gates on Node 22 and 24 before preparation. Preparation depends on that validation and signed-release identity checks; it diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 86dae99..7060bcc 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -7,10 +7,11 @@ below is an explicit first-package exception, not a runtime release path. ## Current versions and source ownership -Core and Azure are published at `0.4.0`; D1 at `0.4.1`. DynamoDB `0.4.5` is the +Core and Azure are published at `0.4.0`; D1 at `0.4.6`. DynamoDB `0.4.5` is the qualified trusted runtime; `0.4.2` remains published registration-only metadata. -D1 `0.4.6` is the current unpublished candidate for optional concurrent keyed-read -batching. Its release and host request-budget acceptance remain separate gates. +D1 `0.4.7` is the current unpublished candidate for optional concurrent keyed and +whole-partition read batching. Its release and host request-budget acceptance +remain separate gates. The `v0.4.3` release attempt failed its npm-version check before preparation: no runtime archive was produced or published. Its signed tag remains immutable; preserve the release as a failed attempt. The `v0.4.4` @@ -27,7 +28,7 @@ reused the original prepared artifact and made no new npm uploads. The accepted belongs to attempt 1, whose visibility check failed; final registry cryptographic, source and isolated public-consumer verification completed during recovery. -For D1 `0.4.6`, schema 2 selects only the new D1 source artifact and must reuse +For D1 `0.4.7`, schema 2 selects only the new D1 source artifact and must reuse the original qualified Core `0.4.0`, Azure `0.4.0` and DynamoDB `0.4.5` registry archives. Unselected workspace builds are not substitutes for those bytes. The reviewed reuse policy must bind their original source and writer identities. @@ -37,8 +38,9 @@ no Core or host upgrade is implied. Versions are independently assigned but release tags share a repository-wide namespace. Never reuse or move a tag/version, including failed publication or -registration versions. DynamoDB `v0.4.5` is qualified; the next D1 release is -planned as `v0.4.6` and requires its own current-head review and release gates. +registration versions. DynamoDB `v0.4.5` and D1 `v0.4.6` are qualified; the next +D1 release is planned as `v0.4.7` and requires its own current-head review and +release gates. A release run uses the workflow at its tagged commit, as documented in [workflow triggers](https://docs.github.com/en/actions/concepts/workflows-and-actions/workflows#workflow-triggers) @@ -75,12 +77,12 @@ record; never install it for a backend/host proof or describe it as the latest runtime. Inspect actual registry bytes/dist-tags afterward. No GitHub v0.4.2 release is needed. -For the D1 `0.4.6` candidate, verify trusted publishing and package/account +For the D1 `0.4.7` candidate, verify trusted publishing and package/account restrictions again. After its reviewed source passes full gates and merges, -create and verify its signed annotated `v0.4.6` tag on `origin/main`; create its +create and verify its signed annotated `v0.4.7` tag on `origin/main`; create its GitHub release only when this configuration is complete. Do not move or reuse the signed `v0.4.3` or `v0.4.4` tags; retain their releases as failed attempts. -Never manually publish the real `0.4.6` artifact +Never manually publish the real `0.4.7` artifact first: immutable bytes with missing trusted provenance cannot later be repaired by a skip. Registration `0.4.2` remains immutable and explicitly outside runtime qualification. @@ -173,7 +175,7 @@ It imports public roots, executes published Core conformance against DynamoDB Local, and proves real StorageError/ConcurrencyError identity with Core `0.4.0`. The fixture is local synthetic backend evidence, not a deployed AWS claim. -For D1 `0.4.6`, that generic consumer proves only a D1 import; its DynamoDB +For D1 `0.4.7`, that generic consumer proves only a D1 import; its DynamoDB conformance run does not exercise the D1 adapter. Before merge or publication, owner acceptance additionally requires an isolated selected D1 tarball plus genuine canonical registry Core `0.4.0`, with no aliases, overrides or workspace diff --git a/package.json b/package.json index 6d825d5..3e97722 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,7 @@ "devDependencies": { "@cloudflare/vitest-pool-workers": "^0.18.8", "@cloudflare/workers-types": "^5.20260727.1", - "@pegma/storage-cloudflare-d1": "workspace:0.4.6", + "@pegma/storage-cloudflare-d1": "workspace:0.4.7", "@types/node": "^26.1.1", "azurite": "^3.36.0", "prettier": "^3.9.6", diff --git a/packages/storage-cloudflare-d1/README.md b/packages/storage-cloudflare-d1/README.md index 8882e1f..53e0f4b 100644 --- a/packages/storage-cloudflare-d1/README.md +++ b/packages/storage-cloudflare-d1/README.md @@ -3,10 +3,11 @@ Cloudflare D1 adapter for [`@pegma/storage-core`](https://www.npmjs.com/package/@pegma/storage-core). -The published release remains `0.4.1`. This source is the unpublished `0.4.6` -candidate for optional concurrent keyed-read batching and retains exact Core -`0.4.0`. Its review, registry qualification and complete host request-budget -acceptance remain pending; source tests alone do not establish live Free usage. +Published `0.4.6` provides optional concurrent keyed-read batching. This source +targets unpublished `0.4.7`, extending that queue to whole-partition reads while +retaining exact Core `0.4.0`. Its review, registry qualification and complete host +request-budget acceptance remain pending; source tests alone do not establish +live Free usage. It stores every collection in one D1 database and one `RECORDS` data table. The physical partition key is `:` and the row key is @@ -83,11 +84,11 @@ Replicated or session-based reads are incompatible with this adapter. Even a session that starts on the primary may use replicas for subsequent reads, so the adapter deliberately does not use the Sessions API. -## Optional concurrent keyed-read batching +## Optional concurrent read batching -The default `readBatchSize: 1` retains direct keyed reads. To coalesce -concurrent public `get` and `getVersioned` calls, opt in when constructing a -Store inside the request: +The default `readBatchSize: 1` retains direct keyed and partition reads. To +coalesce concurrent public `get`, `getVersioned`, `list` and `listVersioned` +calls, opt in when constructing a Store inside the request: ```ts const store = createCloudflareD1Store({ @@ -98,7 +99,7 @@ const store = createCloudflareD1Store({ `readBatchSize` must be a safe integer from 1 through 512. This is an adapter tuning bound, not a Cloudflare batch-size limit. Calls queued together are -sent as at most that many prepared keyed statements in one real D1 batch. +sent as at most that many prepared read statements in one real D1 batch. There is at most one read batch in flight per Store, and a partial batch runs without waiting for more calls. Collection handles on that Store share the queue; separate Store instances do not. Use a request-scoped Store rather @@ -106,7 +107,9 @@ than sharing the queue across Worker requests. `readBatchSize` bounds each D1 batch, not the total pending read requests. The adapter has no total pending-queue cap. Callers must bound their concurrent -read waves and the Store's lifetime within the request. +read waves and the Store's lifetime within the request. Partition lists still +return every live row: the batch bound counts statements, not result rows or +bytes. Batching does not paginate or truncate a list. Only calls that actually reach storage concurrently can coalesce. Finish asynchronous key preparation before starting a parallel read wave if the @@ -115,8 +118,8 @@ There is no caching or same-key deduplication, and each caller decodes its own value. A batch failure rejects all reads in that batch; later calls can recover without an automatic fallback to individual requests. -Writes, internal optimistic reads, partition lists, scans and transactions -keep their existing paths. Batching does not add snapshot or read/write +Writes, internal optimistic reads, scans and transactions keep their existing +paths. Batching does not add snapshot or read/write ordering guarantees: retain version checks and current-state fences. A new read after an awaited write still reads the direct primary binding. diff --git a/packages/storage-cloudflare-d1/package.json b/packages/storage-cloudflare-d1/package.json index f4ad426..d453f3e 100644 --- a/packages/storage-cloudflare-d1/package.json +++ b/packages/storage-cloudflare-d1/package.json @@ -1,6 +1,6 @@ { "name": "@pegma/storage-cloudflare-d1", - "version": "0.4.6", + "version": "0.4.7", "description": "Cloudflare D1 adapter for @pegma/storage-core.", "license": "MIT", "type": "module", diff --git a/packages/storage-cloudflare-d1/src/index.test.ts b/packages/storage-cloudflare-d1/src/index.test.ts index 2167857..e14d7a8 100644 --- a/packages/storage-cloudflare-d1/src/index.test.ts +++ b/packages/storage-cloudflare-d1/src/index.test.ts @@ -107,12 +107,16 @@ function observedDatabase(hooks: ReadBatchHooks = {}) { const readBatchSizes: number[] = []; let preparations = 0; let directKeyReads = 0; + let directPartitionReads = 0; let schemaBatches = 0; let activeReadBatches = 0; let maximumReadBatches = 0; const keyed = (sql: string) => sql.trimStart().startsWith("SELECT") && sql.includes("WHERE partition_key = ? AND row_key = ?"); + const partitionRead = (sql: string) => + sql.trimStart().startsWith("SELECT") && + sql.includes("WHERE partition_key = ? AND deleted = 0"); const wrap = ( original: D1PreparedStatement, sql: string, @@ -125,6 +129,7 @@ function observedDatabase(hooks: ReadBatchHooks = {}) { if (property === "first" || property === "all" || property === "run") { return (...args: unknown[]) => { if (keyed(sql)) directKeyReads += 1; + if (partitionRead(sql)) directPartitionReads += 1; return Reflect.apply(method, target, args); }; } @@ -143,7 +148,9 @@ function observedDatabase(hooks: ReadBatchHooks = {}) { const actual = statements.map((statement) => originals.get(statement)); if (actual.some((item) => item === undefined)) throw new Error("Unobserved prepared statement."); - const read = actual.every((item) => keyed(item!.sql)); + const read = actual.every( + (item) => keyed(item!.sql) || partitionRead(item!.sql), + ); if (!read) { if (actual[0]?.sql.trimStart().startsWith("CREATE")) { schemaBatches += 1; @@ -178,6 +185,7 @@ function observedDatabase(hooks: ReadBatchHooks = {}) { readBatchSizes, preparations: () => preparations, directKeyReads: () => directKeyReads, + directPartitionReads: () => directPartitionReads, schemaBatches: () => schemaBatches, maximumReadBatches: () => maximumReadBatches, }; @@ -880,6 +888,361 @@ describe("D1 opt-in keyed read batching", () => { }); }); +describe("D1 mixed keyed and partition reads", () => { + it.each([undefined, 1])( + "retains direct keyed and partition calls for readBatchSize %s", + async (readBatchSize) => { + await collection().put(widget("one")); + const observed = observedDatabase(); + const records = createCloudflareD1Store({ + database: observed.database, + createSchemaIfMissing: false, + ...(readBatchSize === undefined ? {} : { readBatchSize }), + }).collection(widgets); + const [value, versioned, values, versions] = await bounded( + Promise.all([ + records.get({ partition: "tools", id: "one" }), + records.getVersioned({ partition: "tools", id: "one" }), + records.list("tools"), + records.listVersioned("tools"), + ]), + ); + expect(value).toEqual(widget("one")); + expect(versioned).toEqual({ value: widget("one"), version: "1" }); + expect(values).toEqual([widget("one")]); + expect(versions).toEqual([{ value: widget("one"), version: "1" }]); + expect(observed.directKeyReads()).toBe(2); + expect(observed.directPartitionReads()).toBe(2); + expect(observed.readBatchSizes).toEqual([]); + }, + ); + + it("coalesces three keyed reads and one whole partition read into one real batch", async () => { + const otherWidgets = { ...widgets, name: "d1_mixed_other_widgets" }; + const seed = freshStore(); + await seed.collection(widgets).put(widget("one", "first collection")); + await seed.collection(widgets).put(widget("two")); + await seed.collection(widgets).put(widget("removed")); + await seed + .collection(widgets) + .delete({ partition: "tools", id: "removed" }); + await seed.collection(otherWidgets).put(widget("one", "other collection")); + await env.DB.prepare( + "UPDATE RECORDS SET version = ? WHERE partition_key = ? AND row_key = ?", + ) + .bind("9007199254740993", "d1_targeted_widgets:tools", "one") + .run(); + const observed = observedDatabase(); + const store = createCloudflareD1Store({ + database: observed.database, + createSchemaIfMissing: false, + readBatchSize: 512, + }); + const records = store.collection(widgets); + const others = store.collection(otherWidgets); + const [first, other, removed, rows] = await bounded( + Promise.all([ + records.getVersioned({ partition: "tools", id: "one" }), + others.get({ partition: "tools", id: "one" }), + records.getVersioned({ partition: "tools", id: "removed" }), + records.listVersioned("tools"), + ]), + ); + expect(first).toEqual({ + value: widget("one", "first collection"), + version: "9007199254740993", + }); + expect(other).toEqual(widget("one", "other collection")); + expect(removed).toBeNull(); + expect(rows).toHaveLength(2); + expect(rows).toEqual( + expect.arrayContaining([ + { + value: widget("one", "first collection"), + version: "9007199254740993", + }, + { value: widget("two"), version: "1" }, + ]), + ); + expect(observed.readBatchSizes).toEqual([4]); + expect(observed.directKeyReads()).toBe(0); + expect(observed.directPartitionReads()).toBe(0); + if (first === null) throw new Error("Missing genuine keyed version."); + await records.put(widget("one", "updated")); + expect( + await records.putIfUnchanged(widget("one", "stale"), first.version), + ).toBe(false); + const [latest, empty, values] = await bounded( + Promise.all([ + records.getVersioned({ partition: "tools", id: "one" }), + others.listVersioned("empty"), + records.list("tools"), + ]), + ); + expect(latest).toEqual({ + value: widget("one", "updated"), + version: "9007199254740994", + }); + expect(empty).toEqual([]); + expect(values).toHaveLength(2); + expect(values).toEqual( + expect.arrayContaining([widget("one", "updated"), widget("two")]), + ); + expect(observed.readBatchSizes).toEqual([4, 3]); + expect(observed.maximumReadBatches()).toBe(1); + }); + + it("counts mixed statements rather than returned rows against the batch bound", async () => { + const populated = [widget("one"), widget("two"), widget("three")]; + for (const value of populated) await collection().put(value); + const observed = observedDatabase(); + const records = createCloudflareD1Store({ + database: observed.database, + createSchemaIfMissing: false, + readBatchSize: 2, + }).collection(widgets); + const [missing, versions, otherMissing, values, stillMissing] = + await bounded( + Promise.all([ + records.get({ partition: "tools", id: "absent" }), + records.listVersioned("tools"), + records.getVersioned({ partition: "other", id: "absent" }), + records.list("tools"), + records.get({ partition: "tools", id: "absent" }), + ]), + ); + expect([missing, otherMissing, stillMissing]).toEqual([null, null, null]); + expect(versions).toHaveLength(populated.length); + expect(versions).toEqual( + expect.arrayContaining( + populated.map((value) => ({ value, version: "1" })), + ), + ); + expect(values).toHaveLength(populated.length); + expect(values).toEqual(expect.arrayContaining(populated)); + expect(observed.readBatchSizes).toEqual([2, 2, 1]); + expect(observed.directKeyReads()).toBe(0); + expect(observed.directPartitionReads()).toBe(0); + expect(observed.maximumReadBatches()).toBe(1); + }); + + it("settles mixed transport failures and recovers without direct fallback", async () => { + await collection().put(widget("one")); + const failure = new Error("Synthetic mixed read transport failure."); + const observed = observedDatabase({ + afterReadBatch(call, results) { + if (call === 1) throw failure; + return results; + }, + }); + const records = createCloudflareD1Store({ + database: observed.database, + createSchemaIfMissing: false, + readBatchSize: 512, + }).collection(widgets); + const outcomes = await bounded( + Promise.allSettled([ + records.get({ partition: "tools", id: "one" }), + records.listVersioned("tools"), + ]), + ); + expect(outcomes.map((result) => result.status)).toEqual([ + "rejected", + "rejected", + ]); + for (const outcome of outcomes) + if (outcome.status === "rejected") expect(outcome.reason).toBe(failure); + expect( + await bounded( + Promise.all([ + records.get({ partition: "tools", id: "one" }), + records.listVersioned("tools"), + ]), + ), + ).toEqual([widget("one"), [{ value: widget("one"), version: "1" }]]); + expect(observed.readBatchSizes).toEqual([2, 2]); + expect(observed.directKeyReads()).toBe(0); + expect(observed.directPartitionReads()).toBe(0); + }); + + it.each(["codec", "json"] as const)( + "confines a partition %s failure to its caller in a mixed batch", + async (fault) => { + await collection().put(widget("one")); + const failure = new Error("Synthetic partition decoder failure."); + const broken = { + ...widgets, + codec: { + ...widgets.codec, + decode(record: Parameters[0]): Widget { + if (fault === "codec") throw failure; + return widgets.codec.decode(record); + }, + }, + }; + const observed = observedDatabase({ + afterReadBatch(call, results) { + if (fault !== "json" || call !== 1) return results; + return results.map((result, index) => + index !== 1 + ? result + : { + ...result, + results: result.results.map((row) => ({ + ...(row as Record), + record_json: "{", + })), + }, + ); + }, + }); + const store = createCloudflareD1Store({ + database: observed.database, + createSchemaIfMissing: false, + readBatchSize: 512, + }); + const [keyed, failed, listed] = await bounded( + Promise.allSettled([ + store.collection(widgets).get({ partition: "tools", id: "one" }), + store.collection(broken).listVersioned("tools"), + store.collection(widgets).list("tools"), + ]), + ); + expect(failed.status).toBe("rejected"); + if (failed.status === "rejected") { + if (fault === "codec") expect(failed.reason).toBe(failure); + else expect(failed.reason).toBeInstanceOf(SyntaxError); + } + if (keyed.status !== "fulfilled" || listed.status !== "fulfilled") + throw new Error("Valid mixed readers were rejected."); + expect(keyed.value).toEqual(widget("one")); + expect(listed.value).toEqual([widget("one")]); + expect(keyed.value).not.toBe(listed.value[0]); + expect(observed.readBatchSizes).toEqual([3]); + expect(observed.directPartitionReads()).toBe(0); + }, + ); + + describe.each(["mixed", "partition-only"] as const)( + "%s partition transport validation", + (composition) => { + it.each([ + "short", + "extra", + "sparse", + "null-slot", + "rows-not-array", + "sparse-row", + "null-row", + "missing-version", + "empty-version", + "numeric-version", + "missing-json-field", + "null-json-field", + "invalid-json-field", + ] as const)( + "rejects %s after a real D1 response and recovers without fallback", + async (fault) => { + await collection().put(widget("one")); + let faultApplied = false; + const observed = observedDatabase({ + afterReadBatch(call, results) { + if (call !== 1) return results; + faultApplied = true; + // Copy the genuine backend response before changing its transport + // shape. Stored rows and the forwarding binding remain untouched. + const changed = results.map((result) => ({ + ...result, + results: [...result.results], + })); + if (fault === "short") return changed.slice(1); + if (fault === "extra") return [...changed, changed[1]!]; + if (fault === "sparse") + return new Array>(changed.length); + const partition = changed[1]; + if (partition === undefined) + throw new Error("Missing genuine partition result."); + if (fault === "null-slot") { + expect(Reflect.set(changed, 1, null)).toBe(true); + } else if (fault === "rows-not-array") { + expect(Reflect.set(partition, "results", null)).toBe(true); + } else if (fault === "sparse-row") { + expect(Reflect.deleteProperty(partition.results, "0")).toBe( + true, + ); + } else if (fault === "null-row") { + expect(Reflect.set(partition.results, 0, null)).toBe(true); + } else { + const original = partition.results[0]; + if (original === null || typeof original !== "object") + throw new Error("Missing genuine partition row."); + const row = { ...original }; + partition.results[0] = row; + if (fault === "missing-version") { + expect(Reflect.deleteProperty(row, "version")).toBe(true); + } else if (fault === "empty-version") { + expect(Reflect.set(row, "version", "")).toBe(true); + } else if (fault === "numeric-version") { + expect(Reflect.set(row, "version", 1)).toBe(true); + } else if (fault === "missing-json-field") { + expect(Reflect.deleteProperty(row, "record_json")).toBe(true); + } else { + expect( + Reflect.set( + row, + "record_json", + fault === "null-json-field" ? null : 7, + ), + ).toBe(true); + } + } + return changed; + }, + }); + const records = createCloudflareD1Store({ + database: observed.database, + createSchemaIfMissing: false, + readBatchSize: 512, + }).collection(widgets); + const first = () => + composition === "mixed" + ? records.get({ partition: "tools", id: "one" }) + : records.list("tools"); + const outcomes = await bounded( + Promise.allSettled([first(), records.listVersioned("tools")]), + ); + expect(faultApplied).toBe(true); + expect(outcomes.map((result) => result.status)).toEqual([ + "rejected", + "rejected", + ]); + for (const outcome of outcomes) { + if (outcome.status !== "rejected") + throw new Error("Malformed batch settled a reader successfully."); + expect(outcome.reason).toBeInstanceOf(StorageError); + if (fault === "short" || fault === "extra") + expect(outcome.reason.message).toBe( + `D1 returned an invalid ${composition === "mixed" ? "mixed-read" : "partition-read"} batch.`, + ); + } + expect( + await bounded( + Promise.all([first(), records.listVersioned("empty")]), + ), + ).toEqual([ + composition === "mixed" ? widget("one") : [widget("one")], + [], + ]); + expect(observed.readBatchSizes).toEqual([2, 2]); + expect(observed.directKeyReads()).toBe(0); + expect(observed.directPartitionReads()).toBe(0); + expect(observed.maximumReadBatches()).toBe(1); + }, + ); + }, + ); +}); + describe("D1 schema initialization", () => { it("is shared by stores over the same direct binding", async () => { let schemaBatches = 0; diff --git a/packages/storage-cloudflare-d1/src/index.ts b/packages/storage-cloudflare-d1/src/index.ts index a99d964..5590ebb 100644 --- a/packages/storage-cloudflare-d1/src/index.ts +++ b/packages/storage-cloudflare-d1/src/index.ts @@ -308,8 +308,8 @@ export interface CloudflareD1StoreOptions { readonly createSchemaIfMissing?: boolean; /** - * Coalesce concurrent public get/getVersioned calls into read-only batches. - * Defaults to 1, retaining direct keyed reads. Must be an integer from 1 + * Coalesce concurrent public keyed and partition reads into read-only batches. + * Defaults to 1, retaining direct reads. Must be an integer from 1 * through 512. Larger values suit bounded small records, not arbitrary rows. * * This limits each physical batch, not the total pending queue. Opt-in @@ -320,12 +320,20 @@ export interface CloudflareD1StoreOptions { readonly readBatchSize?: number; } -interface PendingRead { - readonly partition: string; - readonly id: string; - readonly resolve: (row: PhysicalRow | null) => void; - readonly reject: (reason: unknown) => void; -} +type PendingRead = + | { + readonly kind: "keyed"; + readonly partition: string; + readonly id: string; + readonly resolve: (row: PhysicalRow | null) => void; + readonly reject: (reason: unknown) => void; + } + | { + readonly kind: "partition"; + readonly partition: string; + readonly resolve: (rows: RecordRow[]) => void; + readonly reject: (reason: unknown) => void; + }; function recordRow(row: PhysicalRow | null): RecordRow | null { return row === null || row.deleted === 1 || row.record_json === null @@ -334,41 +342,73 @@ function recordRow(row: PhysicalRow | null): RecordRow | null { } /** - * Batch results are positional: validate every slot and row before assigning - * any result to its caller. These runtime shape checks are opt-in only. - * Direct first() keeps its existing typed-binding behavior; - * SELECT_ONE's cast and the STRICT schema enforce these row types in real D1. + * Validate all transport slots before resolving any caller. JSON and collection + * codecs still run separately in each public reader, after this shared batch. + * Direct first/all calls retain their existing typed-binding behavior. */ -function batchRows( - results: CloudflareD1Result[], - expected: number, -): (PhysicalRow | null)[] { - if (!Array.isArray(results) || results.length !== expected) { - throw new StorageError("D1 returned an invalid keyed-read batch."); +function batchSettlements( + results: CloudflareD1Result[], + jobs: readonly PendingRead[], +): (() => void)[] { + if (!Array.isArray(results) || results.length !== jobs.length) { + const kind = jobs.every((job) => job.kind === "keyed") + ? "keyed-read" + : jobs.every((job) => job.kind === "partition") + ? "partition-read" + : "mixed-read"; + throw new StorageError(`D1 returned an invalid ${kind} batch.`); } - return Array.from(results, (result) => { + return Array.from(results, (result, index) => { + const job = jobs[index]!; if ( result === null || typeof result !== "object" || - !Array.isArray(result.results) || - result.results.length > 1 + !Array.isArray(result.results) ) { - throw new StorageError("D1 returned an invalid keyed-read result."); + throw new StorageError(`D1 returned an invalid ${job.kind}-read result.`); } - if (result.results.length === 0) return null; - const row = result.results[0]; - if ( - row === undefined || - row === null || - typeof row !== "object" || - typeof row.version !== "string" || - row.version.length === 0 || - (row.deleted !== 0 && row.deleted !== 1) || - (row.record_json !== null && typeof row.record_json !== "string") - ) { - throw new StorageError("D1 returned an invalid keyed-read row."); + if (job.kind === "keyed") { + const resolve = job.resolve; + if (result.results.length > 1) + throw new StorageError("D1 returned an invalid keyed-read result."); + if (result.results.length === 0) return () => resolve(null); + const row: unknown = result.results[0]; + if ( + row === null || + typeof row !== "object" || + !("version" in row) || + typeof row.version !== "string" || + row.version.length === 0 || + !("deleted" in row) || + (row.deleted !== 0 && row.deleted !== 1) || + !("record_json" in row) || + (row.record_json !== null && typeof row.record_json !== "string") + ) { + throw new StorageError("D1 returned an invalid keyed-read row."); + } + const physical: PhysicalRow = { + record_json: row.record_json, + version: row.version, + deleted: row.deleted, + }; + return () => resolve(physical); } - return row; + const rows = Array.from(result.results, (row: unknown): RecordRow => { + if ( + row === null || + typeof row !== "object" || + !("version" in row) || + typeof row.version !== "string" || + row.version.length === 0 || + !("record_json" in row) || + typeof row.record_json !== "string" + ) { + throw new StorageError("D1 returned an invalid partition-read row."); + } + return { record_json: row.record_json, version: row.version }; + }); + const resolve = job.resolve; + return () => resolve(rows); }); } @@ -557,15 +597,15 @@ export function createCloudflareD1Store( while (pendingReads.length > 0) { const jobs = pendingReads.splice(0, readBatchSize); try { - const results = await database.batch( + const results = await database.batch( jobs.map((job) => - database.prepare(SELECT_ONE).bind(job.partition, job.id), + job.kind === "keyed" + ? database.prepare(SELECT_ONE).bind(job.partition, job.id) + : database.prepare(SELECT_PARTITION).bind(job.partition), ), ); - const rows = batchRows(results, jobs.length); - for (const [index, job] of jobs.entries()) { - job.resolve(rows[index]!); - } + const settlements = batchSettlements(results, jobs); + for (const settle of settlements) settle(); } catch (error) { for (const job of jobs) job.reject(error); } @@ -582,7 +622,15 @@ export function createCloudflareD1Store( ): Promise { await ensureSchema(); return new Promise((resolve, reject) => { - pendingReads.push({ partition, id, resolve, reject }); + pendingReads.push({ kind: "keyed", partition, id, resolve, reject }); + scheduleReadBatch(); + }); + } + + async function queuedPartitionRead(partition: string): Promise { + await ensureSchema(); + return new Promise((resolve, reject) => { + pendingReads.push({ kind: "partition", partition, resolve, reject }); scheduleReadBatch(); }); } @@ -635,6 +683,10 @@ export function createCloudflareD1Store( async function listVersioned( partition: string, ): Promise[]> { + if (readBatchSize > 1) { + const rows = await queuedPartitionRead(partitionKey(partition)); + return rows.map(decodeRow); + } await ensureSchema(); const result = await database .prepare(SELECT_PARTITION) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 4f31ed4..fce9968 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -15,7 +15,7 @@ importers: specifier: ^5.20260727.1 version: 5.20260727.1 '@pegma/storage-cloudflare-d1': - specifier: workspace:0.4.6 + specifier: workspace:0.4.7 version: link:packages/storage-cloudflare-d1 '@types/node': specifier: ^26.1.1 diff --git a/tests/release-packages.test.ts b/tests/release-packages.test.ts index 2cf4699..898ddae 100644 --- a/tests/release-packages.test.ts +++ b/tests/release-packages.test.ts @@ -97,7 +97,7 @@ describe("release package metadata", () => { expect(manifests.map(({ name, version }) => ({ name, version }))).toEqual([ { name: "@pegma/storage-core", version: "0.4.0" }, { name: "@pegma/storage-azure-tables", version: "0.4.0" }, - { name: "@pegma/storage-cloudflare-d1", version: "0.4.6" }, + { name: "@pegma/storage-cloudflare-d1", version: "0.4.7" }, { name: "@pegma/storage-dynamodb", version: "0.4.5" }, ]); for (const adapter of manifests.slice(1)) { @@ -917,7 +917,7 @@ describe("selected-source schema2 archives", () => { }, { name: "@pegma/storage-cloudflare-d1", - version: "0.4.6", + version: "0.4.7", publish: true, }, { name: "@pegma/storage-dynamodb", version: "0.4.5", publish: false },