Open History to see the last commit
1import { mkdtempSync, rmSync } from 'node:fs'
2import { createRequire } from 'node:module'
3import { tmpdir } from 'node:os'
4import { dirname, join } from 'node:path'
5import { setTimeout as delay } from 'node:timers/promises'
6import { fileURLToPath } from 'node:url'
7import { spawn } from 'node:child_process'
8import { describe, expect, it } from 'vitest'
9import { runRuntimeBridgeE2EContractSuite } from '../../db-sqlite-persistence-core/tests/contracts/runtime-bridge-e2e-contract'
10import type {
11 RuntimeBridgeE2EContractError,
12 RuntimeBridgeE2EContractHarness,
13 RuntimeBridgeE2EContractHarnessFactory,
14 RuntimeBridgeE2EContractTodo,
15} from '../../db-sqlite-persistence-core/tests/contracts/runtime-bridge-e2e-contract'
16
17type RuntimeProcessHarness = {
18 baseUrl: string
19 restart: () => Promise<void>
20 stop: () => Promise<void>
21 getOutput: () => {
22 stderr: string
23 stdout: string
24 }
25}
26
27type WranglerRuntimeResponse<TPayload> =
28 | {
29 ok: true
30 rows?: TPayload
31 }
32 | {
33 ok: false
34 error: RuntimeBridgeE2EContractError
35 }
36
37const packageDirectory = dirname(fileURLToPath(import.meta.url))
38const wranglerConfigPath = join(packageDirectory, `fixtures`, `wrangler.toml`)
39const require = createRequire(import.meta.url)
40const wranglerBinPath = require.resolve(`wrangler/bin/wrangler.js`)
41
42async function getAvailablePort(): Promise<number> {
43 const netModule = await import('node:net')
44 return new Promise<number>((resolve, reject) => {
45 const server = netModule.createServer()
46 server.listen(0, `127.0.0.1`, () => {
47 const address = server.address()
48 if (!address || typeof address === `string`) {
49 server.close()
50 reject(new Error(`Unable to allocate an available local port`))
51 return
52 }
53 const selectedPort = address.port
54 server.close((error) => {
55 if (error) {
56 reject(error)
57 return
58 }
59 resolve(selectedPort)
60 })
61 })
62 server.on(`error`, reject)
63 })
64}
65
66function createRuntimeError(
67 message: string,
68 stderr: string,
69 stdout: string,
70): Error {
71 return new Error([message, `stderr=${stderr}`, `stdout=${stdout}`].join(`\n`))
72}
73
74async function stopWranglerProcess(
75 child: ReturnType<typeof spawn> | undefined,
76): Promise<void> {
77 if (!child || child.exitCode !== null) {
78 return
79 }
80
81 child.kill(`SIGTERM`)
82 const closed = await Promise.race([
83 new Promise<boolean>((resolve) => {
84 child.once(`close`, () => resolve(true))
85 }),
86 delay(5_000).then(() => false),
87 ])
88
89 if (closed) {
90 return
91 }
92
93 child.kill(`SIGKILL`)
94 await new Promise<void>((resolve) => {
95 child.once(`close`, () => resolve())
96 })
97}
98
99async function startWranglerRuntime(options: {
100 persistPath: string
101 syncEnabled?: boolean
102 schemaVersion?: number
103 collectionId?: string
104}): Promise<RuntimeProcessHarness> {
105 let child: ReturnType<typeof spawn> | undefined
106 let stdoutBuffer = ``
107 let stderrBuffer = ``
108 const port = await getAvailablePort()
109
110 const spawnProcess = async (): Promise<void> => {
111 const runtimeVarEntries = [
112 [
113 `PERSISTENCE_WITH_SYNC`,
114 options.syncEnabled !== undefined
115 ? String(options.syncEnabled)
116 : undefined,
117 ],
118 [
119 `PERSISTENCE_SCHEMA_VERSION`,
120 options.schemaVersion !== undefined
121 ? String(options.schemaVersion)
122 : undefined,
123 ],
124 [`PERSISTENCE_COLLECTION_ID`, options.collectionId],
125 ].filter((entry): entry is [string, string] => entry[1] !== undefined)
126
127 const wranglerArgs = [
128 `dev`,
129 `--local`,
130 `--ip`,
131 `127.0.0.1`,
132 `--port`,
133 String(port),
134 `--persist-to`,
135 options.persistPath,
136 `--config`,
137 wranglerConfigPath,
138 ...runtimeVarEntries.flatMap(([key, value]) => [
139 `--var`,
140 `${key}:${value}`,
141 ]),
142 ]
143
144 child = spawn(process.execPath, [wranglerBinPath, ...wranglerArgs], {
145 cwd: packageDirectory,
146 env: {
147 ...process.env,
148 CI: `1`,
149 WRANGLER_SEND_METRICS: `false`,
150 },
151 stdio: [`ignore`, `pipe`, `pipe`],
152 })
153
154 if (!child.stdout || !child.stderr) {
155 throw new Error(`Unable to capture wrangler dev process output streams`)
156 }
157
158 child.stdout.on(`data`, (chunk: Buffer) => {
159 stdoutBuffer += chunk.toString()
160 })
161 child.stderr.on(`data`, (chunk: Buffer) => {
162 stderrBuffer += chunk.toString()
163 })
164
165 const baseUrl = `http://127.0.0.1:${String(port)}`
166 const startAt = Date.now()
167 while (Date.now() - startAt < 45_000) {
168 if (child.exitCode !== null) {
169 throw createRuntimeError(
170 `Wrangler dev exited before becoming healthy`,
171 stderrBuffer,
172 stdoutBuffer,
173 )
174 }
175
176 try {
177 const healthResponse = await fetch(`${baseUrl}/health`)
178 if (healthResponse.ok) {
179 return
180 }
181 } catch {
182 // Runtime may still be starting.
183 }
184
185 await delay(250)
186 }
187
188 throw createRuntimeError(
189 `Timed out waiting for wrangler dev runtime`,
190 stderrBuffer,
191 stdoutBuffer,
192 )
193 }
194
195 await spawnProcess()
196
197 return {
198 baseUrl: `http://127.0.0.1:${String(port)}`,
199 restart: async () => {
200 await stopWranglerProcess(child)
201 stdoutBuffer = ``
202 stderrBuffer = ``
203 await spawnProcess()
204 },
205 stop: async () => {
206 await stopWranglerProcess(child)
207 },
208 getOutput: () => ({
209 stderr: stderrBuffer,
210 stdout: stdoutBuffer,
211 }),
212 }
213}
214
215async function postJson<TPayload>(
216 runtime: RuntimeProcessHarness,
217 path: string,
218 body: unknown,
219): Promise<WranglerRuntimeResponse<TPayload>> {
220 let response: Response
221 try {
222 response = await fetch(`${runtime.baseUrl}${path}`, {
223 method: `POST`,
224 headers: {
225 'content-type': `application/json`,
226 },
227 body: JSON.stringify(body),
228 signal: AbortSignal.timeout(30_000),
229 })
230 } catch (error) {
231 const output = runtime.getOutput()
232 throw createRuntimeError(
233 `Timed out waiting for wrangler dev runtime response: ${String(error)}`,
234 output.stderr,
235 output.stdout,
236 )
237 }
238
239 const parsed = (await response.json()) as WranglerRuntimeResponse<TPayload>
240 return parsed
241}
242
243function assertRuntimeError(
244 response: WranglerRuntimeResponse<unknown>,
245): RuntimeBridgeE2EContractError {
246 if (!response.ok) {
247 return response.error
248 }
249
250 throw new Error(`Expected runtime call to fail, but it succeeded`)
251}
252
253function assertRuntimeSuccess<TPayload>(
254 response: WranglerRuntimeResponse<TPayload>,
255): TPayload | undefined {
256 if (response.ok) {
257 return response.rows
258 }
259
260 throw new Error(`${response.error.name}: ${response.error.message}`)
261}
262
263const createHarness: RuntimeBridgeE2EContractHarnessFactory = () => {
264 const tempDirectory = mkdtempSync(join(tmpdir(), `db-cloudflare-do-e2e-`))
265 const persistPath = join(tempDirectory, `wrangler-state`)
266 const collectionId = `todos`
267 let nextSequence = 1
268 const runtimePromise = startWranglerRuntime({
269 persistPath,
270 })
271
272 const harness: RuntimeBridgeE2EContractHarness = {
273 writeTodoFromClient: async (todo: RuntimeBridgeE2EContractTodo) => {
274 const runtime = await runtimePromise
275 const result = await postJson<void>(runtime, `/write-todo`, {
276 collectionId,
277 todo,
278 txId: `tx-${nextSequence}`,
279 seq: nextSequence,
280 rowVersion: nextSequence,
281 })
282 nextSequence++
283
284 if (!result.ok) {
285 throw new Error(`${result.error.name}: ${result.error.message}`)
286 }
287 },
288 loadTodosFromClient: async (targetCollectionId?: string) => {
289 const runtime = await runtimePromise
290 const result = await postJson<
291 Array<{ key: string; value: RuntimeBridgeE2EContractTodo }>
292 >(runtime, `/load-todos`, {
293 collectionId: targetCollectionId ?? collectionId,
294 })
295 if (!result.ok) {
296 throw new Error(`${result.error.name}: ${result.error.message}`)
297 }
298 return result.rows ?? []
299 },
300 loadUnknownCollectionErrorFromClient:
301 async (): Promise<RuntimeBridgeE2EContractError> => {
302 const runtime = await runtimePromise
303 const result = await postJson<never>(
304 runtime,
305 `/load-unknown-collection-error`,
306 {
307 collectionId: `missing`,
308 },
309 )
310 if (result.ok) {
311 throw new Error(
312 `Expected unknown collection request to fail, but it succeeded`,
313 )
314 }
315 return result.error
316 },
317 restartHost: async () => {
318 const runtime = await runtimePromise
319 await runtime.restart()
320 },
321 cleanup: async () => {
322 try {
323 const runtime = await runtimePromise
324 await runtime.stop()
325 } finally {
326 rmSync(tempDirectory, { recursive: true, force: true })
327 }
328 },
329 }
330
331 return harness
332}
333
334runRuntimeBridgeE2EContractSuite(
335 `cloudflare durable object runtime bridge e2e (wrangler local)`,
336 createHarness,
337 {
338 testTimeoutMs: 90_000,
339 },
340)
341
342describe(`cloudflare durable object schema mismatch behavior (wrangler local)`, () => {
343 it(`throws on schema mismatch in sync-absent mode`, async () => {
344 const tempDirectory = mkdtempSync(
345 join(tmpdir(), `db-cloudflare-do-local-mismatch-e2e-`),
346 )
347 const persistPath = join(tempDirectory, `wrangler-state`)
348 const collectionId = `todos`
349 let runtime = await startWranglerRuntime({
350 persistPath,
351 syncEnabled: false,
352 schemaVersion: 1,
353 collectionId,
354 })
355
356 try {
357 const writeResult = await postJson<void>(runtime, `/write-todo`, {
358 collectionId,
359 txId: `tx-1`,
360 seq: 1,
361 rowVersion: 1,
362 todo: {
363 id: `local-1`,
364 title: `Local mode row`,
365 score: 10,
366 },
367 })
368 assertRuntimeSuccess(writeResult)
369 } finally {
370 await runtime.stop()
371 }
372
373 runtime = await startWranglerRuntime({
374 persistPath,
375 syncEnabled: false,
376 schemaVersion: 2,
377 collectionId,
378 })
379 try {
380 const loadResult = await postJson<
381 Array<{ key: string; value: RuntimeBridgeE2EContractTodo }>
382 >(runtime, `/load-todos`, {
383 collectionId,
384 })
385 const runtimeError = assertRuntimeError(loadResult)
386 expect(runtimeError.message).toContain(`Schema version mismatch`)
387 } finally {
388 await runtime.stop()
389 rmSync(tempDirectory, { recursive: true, force: true })
390 }
391 }, 90_000)
392
393 it(`resets collection on schema mismatch in sync-present mode`, async () => {
394 const tempDirectory = mkdtempSync(
395 join(tmpdir(), `db-cloudflare-do-sync-mismatch-e2e-`),
396 )
397 const persistPath = join(tempDirectory, `wrangler-state`)
398 const collectionId = `todos`
399 let runtime = await startWranglerRuntime({
400 persistPath,
401 syncEnabled: true,
402 schemaVersion: 1,
403 collectionId,
404 })
405
406 try {
407 const writeResult = await postJson<void>(runtime, `/write-todo`, {
408 collectionId,
409 txId: `tx-1`,
410 seq: 1,
411 rowVersion: 1,
412 todo: {
413 id: `sync-1`,
414 title: `Sync mode row`,
415 score: 20,
416 },
417 })
418 assertRuntimeSuccess(writeResult)
419 } finally {
420 await runtime.stop()
421 }
422
423 runtime = await startWranglerRuntime({
424 persistPath,
425 syncEnabled: true,
426 schemaVersion: 2,
427 collectionId,
428 })
429 try {
430 const loadResult = await postJson<
431 Array<{ key: string; value: RuntimeBridgeE2EContractTodo }>
432 >(runtime, `/load-todos`, {
433 collectionId,
434 })
435 const rows = assertRuntimeSuccess(loadResult) ?? []
436 expect(rows).toEqual([])
437 } finally {
438 await runtime.stop()
439 rmSync(tempDirectory, { recursive: true, force: true })
440 }
441 }, 90_000)
442})