Open History to see the last commit
1import { DatabaseSync } from 'node:sqlite'
2import { describe, expect, it } from 'vitest'
3import { IR } from '../../db/src'
4import { SQLiteCorePersistenceAdapter } from '../../db-sqlite-persistence-core/src'
5import { createCloudflareDOSQLiteDriver } from '../src/do-driver'
6
7// Cloudflare caps each Durable Object SQL query at 100 bound parameters.
8const MAX_BOUND_PARAMETERS = 100
9
10function toSqliteBinding(value: unknown): string | number | bigint | null {
11 if (value === null || value === undefined) return null
12 if (typeof value === `boolean`) return value ? 1 : 0
13 if (
14 typeof value === `string` ||
15 typeof value === `number` ||
16 typeof value === `bigint`
17 ) {
18 return value
19 }
20 return String(value)
21}
22
23function createLimitedHost(nativeTransaction = false) {
24 const database = new DatabaseSync(`:memory:`)
25 const boundParameterCounts: Array<number> = []
26 const sqlStorage = {
27 exec: (sql: string, ...params: ReadonlyArray<unknown>) => {
28 boundParameterCounts.push(params.length)
29 if (params.length > MAX_BOUND_PARAMETERS) {
30 throw new Error(`host parameter limit exceeded`)
31 }
32 const statement = database.prepare(sql)
33 const bindings = params.map(toSqliteBinding)
34 if (statement.columns().length > 0) {
35 return statement.all(...bindings).map((row) => ({ ...row }))
36 }
37 statement.run(...bindings)
38 return []
39 },
40 }
41 const driver = createCloudflareDOSQLiteDriver(
42 nativeTransaction
43 ? { storage: { sql: sqlStorage, transaction: async (fn) => fn() } }
44 : { sql: sqlStorage },
45 )
46 return {
47 adapter: new SQLiteCorePersistenceAdapter({ driver }),
48 boundParameterCounts,
49 close: () => database.close(),
50 }
51}
52
53describe(`Cloudflare Durable Object replacement batching`, () => {
54 it.each([25, 26, 205])(
55 `persists %i replacement rows within the host parameter limit`,
56 async (rowCount) => {
57 const { adapter, boundParameterCounts, close } = createLimitedHost()
58 const collectionId = `cloudflare-batch-${rowCount}`
59 const keys = Array.from(
60 { length: rowCount },
61 (_, index) => `row-${index}`,
62 )
63
64 try {
65 await adapter.applyCommittedTx(collectionId, {
66 txId: `replacement`,
67 term: 1,
68 seq: 1,
69 rowVersion: 1,
70 truncate: true,
71 mutations: keys.map((key) => ({
72 type: `insert` as const,
73 key,
74 value: { id: key },
75 })),
76 })
77
78 const snapshot = await adapter.loadResumeSnapshot(collectionId)
79 expect(snapshot.rows.map(({ key }) => key).sort()).toEqual(
80 [...keys].sort(),
81 )
82 expect(snapshot.keySet).toEqual({ status: `consistent` })
83 expect(Math.max(...boundParameterCounts)).toBe(MAX_BOUND_PARAMETERS)
84 } finally {
85 close()
86 }
87 },
88 )
89
90 /**
91 * A root DO driver declares the host's 100-binding limit. loadSubset uses
92 * the transaction driver, so that nested driver must carry the same limit.
93 * The independent row model is the set of IDs named by the chosen clauses;
94 * the 100/101 pair distinguishes the host cap from a legacy 999 fallback.
95 * The controlled storage throws before executing any over-limit statement.
96 * This is a Node receiving seam, not a native Cloudflare runtime receipt.
97 */
98 it.each([
99 [`savepoint`, `eq`],
100 [`savepoint`, `in`],
101 [`native`, `eq`],
102 [`native`, `in`],
103 ] as const)(
104 `keeps %s transaction %s predicates within the host limit`,
105 async (mode, kind) => {
106 const { adapter, boundParameterCounts, close } = createLimitedHost(
107 mode === `native`,
108 )
109 const collectionId = `cloudflare-predicate-${kind}`
110 try {
111 await adapter.applyCommittedTx(collectionId, {
112 txId: `seed`,
113 term: 1,
114 seq: 1,
115 rowVersion: 1,
116 mutations: [
117 { type: `insert`, key: `target`, value: { id: `target` } },
118 { type: `insert`, key: `miss`, value: { id: `miss` } },
119 ],
120 })
121
122 for (const clauseCount of [100, 101]) {
123 const requestedIds = [
124 `target`,
125 ...Array.from(
126 { length: clauseCount - 1 },
127 (_, index) => `absent-${index}`,
128 ),
129 ]
130 const where = new IR.Func(
131 `or`,
132 requestedIds.map(
133 (id) =>
134 new IR.Func(kind, [
135 new IR.PropRef([`id`]),
136 new IR.Value(kind === `in` ? [id] : id),
137 ]),
138 ),
139 )
140 const attemptStart = boundParameterCounts.length
141 const rows = await adapter.loadSubset(collectionId, { where })
142 expect(rows.map((row) => row.key)).toEqual([`target`])
143 expect(
144 Math.max(...boundParameterCounts.slice(attemptStart)),
145 ).toBeLessThanOrEqual(MAX_BOUND_PARAMETERS)
146 }
147 } finally {
148 close()
149 }
150 },
151 )
152
153 it.each([25, 26, 205])(
154 `persists %i ordinary rows with metadata in bounded host calls`,
155 async (rowCount) => {
156 const { adapter, boundParameterCounts, close } = createLimitedHost()
157 const collectionId = `cloudflare-ordinary-${rowCount}`
158 const keys = Array.from(
159 { length: rowCount },
160 (_, index) => `row-${index}`,
161 )
162
163 try {
164 await adapter.loadResumeSnapshot(collectionId)
165 boundParameterCounts.length = 0
166 await adapter.applyCommittedTx(collectionId, {
167 txId: `ordinary`,
168 term: 1,
169 seq: 1,
170 rowVersion: 1,
171 mutations: keys.map((key) => ({
172 type: `insert` as const,
173 key,
174 value: { id: key },
175 })),
176 rowMetadataMutations: keys.map((key) => ({
177 type: `set` as const,
178 key,
179 value: { source: `ordinary` },
180 })),
181 collectionMetadataMutations: keys.map((key) => ({
182 type: `set` as const,
183 key,
184 value: { source: `ordinary` },
185 })),
186 })
187 const writeCalls = boundParameterCounts.length
188 const maxBindings = Math.max(...boundParameterCounts)
189 const snapshot = await adapter.loadResumeSnapshot(collectionId)
190
191 expect(snapshot.rows.map(({ key }) => key).sort()).toEqual(
192 [...keys].sort(),
193 )
194 expect(snapshot.rows.map(({ metadata }) => metadata)).toEqual(
195 Array(rowCount).fill({ source: `ordinary` }),
196 )
197 expect(
198 snapshot.collectionMetadata.map(({ key }) => key).sort(),
199 ).toEqual([...keys].sort())
200 expect(snapshot.collectionMetadata.map(({ value }) => value)).toEqual(
201 Array(rowCount).fill({ source: `ordinary` }),
202 )
203 expect(snapshot.keySet).toEqual({ status: `consistent` })
204 expect(maxBindings).toBe(MAX_BOUND_PARAMETERS)
205 // Includes the host's BEGIN and COMMIT around core query/run calls.
206 expect(writeCalls).toBeLessThanOrEqual(
207 14 + 6 * Math.ceil(rowCount / 25),
208 )
209 } finally {
210 close()
211 }
212 },
213 )
214})