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 target = { kind: `eager`, collectionId } as const
60 const keys = Array.from(
61 { length: rowCount },
62 (_, index) => `row-${index}`,
63 )
64
65 try {
66 await adapter.applyCommittedTx(target, {
67 txId: `replacement`,
68 term: 1,
69 seq: 1,
70 rowVersion: 1,
71 truncate: true,
72 mutations: keys.map((key) => ({
73 type: `insert` as const,
74 key,
75 value: { id: key },
76 })),
77 })
78
79 const snapshot = await adapter.loadResumeSnapshot(target)
80 expect(snapshot.rows.map(({ key }) => key).sort()).toEqual(
81 [...keys].sort(),
82 )
83 expect(snapshot.keySet).toEqual({ status: `consistent` })
84 expect(Math.max(...boundParameterCounts)).toBe(MAX_BOUND_PARAMETERS)
85 } finally {
86 close()
87 }
88 },
89 )
90
91 /**
92 * A root DO driver declares the host's 100-binding limit. loadSubset uses
93 * the transaction driver, so that nested driver must carry the same limit.
94 * The independent row model is the set of IDs named by the chosen clauses;
95 * the 100/101 pair distinguishes the host cap from a legacy 999 fallback.
96 * The controlled storage throws before executing any over-limit statement.
97 * This is a Node receiving seam, not a native Cloudflare runtime receipt.
98 */
99 it.each([
100 [`savepoint`, `eq`],
101 [`savepoint`, `in`],
102 [`native`, `eq`],
103 [`native`, `in`],
104 ] as const)(
105 `keeps %s transaction %s predicates within the host limit`,
106 async (mode, kind) => {
107 const { adapter, boundParameterCounts, close } = createLimitedHost(
108 mode === `native`,
109 )
110 const collectionId = `cloudflare-predicate-${kind}`
111 const target = { kind: `eager`, collectionId } as const
112 try {
113 await adapter.applyCommittedTx(target, {
114 txId: `seed`,
115 term: 1,
116 seq: 1,
117 rowVersion: 1,
118 mutations: [
119 { type: `insert`, key: `target`, value: { id: `target` } },
120 { type: `insert`, key: `miss`, value: { id: `miss` } },
121 ],
122 })
123
124 for (const clauseCount of [100, 101]) {
125 const requestedIds = [
126 `target`,
127 ...Array.from(
128 { length: clauseCount - 1 },
129 (_, index) => `absent-${index}`,
130 ),
131 ]
132 const where = new IR.Func(
133 `or`,
134 requestedIds.map(
135 (id) =>
136 new IR.Func(kind, [
137 new IR.PropRef([`id`]),
138 new IR.Value(kind === `in` ? [id] : id),
139 ]),
140 ),
141 )
142 const attemptStart = boundParameterCounts.length
143 const rows = await adapter.loadSubset(target, { where })
144 expect(rows.map((row) => row.key)).toEqual([`target`])
145 expect(
146 Math.max(...boundParameterCounts.slice(attemptStart)),
147 ).toBeLessThanOrEqual(MAX_BOUND_PARAMETERS)
148 }
149 } finally {
150 close()
151 }
152 },
153 )
154
155 it.each([25, 26, 205])(
156 `persists %i ordinary rows with metadata in bounded host calls`,
157 async (rowCount) => {
158 const { adapter, boundParameterCounts, close } = createLimitedHost()
159 const collectionId = `cloudflare-ordinary-${rowCount}`
160 const target = { kind: `eager`, collectionId } as const
161 const keys = Array.from(
162 { length: rowCount },
163 (_, index) => `row-${index}`,
164 )
165
166 try {
167 await adapter.loadResumeSnapshot(target)
168 boundParameterCounts.length = 0
169 await adapter.applyCommittedTx(target, {
170 txId: `ordinary`,
171 term: 1,
172 seq: 1,
173 rowVersion: 1,
174 mutations: keys.map((key) => ({
175 type: `insert` as const,
176 key,
177 value: { id: key },
178 })),
179 rowMetadataMutations: keys.map((key) => ({
180 type: `set` as const,
181 key,
182 value: { source: `ordinary` },
183 })),
184 collectionMetadataMutations: keys.map((key) => ({
185 type: `set` as const,
186 key,
187 value: { source: `ordinary` },
188 })),
189 })
190 const writeCalls = boundParameterCounts.length
191 const maxBindings = Math.max(...boundParameterCounts)
192 const snapshot = await adapter.loadResumeSnapshot(target)
193
194 expect(snapshot.rows.map(({ key }) => key).sort()).toEqual(
195 [...keys].sort(),
196 )
197 expect(snapshot.rows.map(({ metadata }) => metadata)).toEqual(
198 Array(rowCount).fill({ source: `ordinary` }),
199 )
200 expect(
201 snapshot.collectionMetadata.map(({ key }) => key).sort(),
202 ).toEqual([...keys].sort())
203 expect(snapshot.collectionMetadata.map(({ value }) => value)).toEqual(
204 Array(rowCount).fill({ source: `ordinary` }),
205 )
206 expect(snapshot.keySet).toEqual({ status: `consistent` })
207 expect(maxBindings).toBe(MAX_BOUND_PARAMETERS)
208 // Includes the host's BEGIN and COMMIT around core query/run calls.
209 expect(writeCalls).toBeLessThanOrEqual(
210 14 + 6 * Math.ceil(rowCount / 25),
211 )
212 } finally {
213 close()
214 }
215 },
216 )
217})