Open History to see the last commit
1import { spawn } from 'node:child_process'
2import { createRequire } from 'node:module'
3import { dirname, join } from 'node:path'
4import { setTimeout as delay } from 'node:timers/promises'
5import { fileURLToPath } from 'node:url'
6import type { RuntimeBridgeE2EContractError } from '../../../db-sqlite-persistence-core/tests/contracts/runtime-bridge-e2e-contract'
7
8/**
9 * Wrangler dev process helpers shared by the Cloudflare Durable Object e2e
10 * witnesses. `startWranglerRuntime` runs the fixture worker in local workerd
11 * with `--persist-to`, so a runtime that is stopped and started again over
12 * the same directory reads the same Durable Object storage.
13 */
14export type RuntimeProcessHarness = {
15 baseUrl: string
16 restart: () => Promise<void>
17 stop: () => Promise<void>
18 getOutput: () => {
19 stderr: string
20 stdout: string
21 }
22}
23
24export type WranglerRuntimeResponse<TPayload> =
25 | {
26 ok: true
27 rows?: TPayload
28 }
29 | {
30 ok: false
31 error: RuntimeBridgeE2EContractError
32 }
33
34const packageDirectory = dirname(fileURLToPath(import.meta.url))
35const wranglerConfigPath = join(packageDirectory, `wrangler.toml`)
36const require = createRequire(import.meta.url)
37const wranglerBinPath = require.resolve(`wrangler/bin/wrangler.js`)
38
39async function getAvailablePort(): Promise<number> {
40 const netModule = await import('node:net')
41 return new Promise<number>((resolve, reject) => {
42 const server = netModule.createServer()
43 server.listen(0, `127.0.0.1`, () => {
44 const address = server.address()
45 if (!address || typeof address === `string`) {
46 server.close()
47 reject(new Error(`Unable to allocate an available local port`))
48 return
49 }
50 const selectedPort = address.port
51 server.close((error) => {
52 if (error) {
53 reject(error)
54 return
55 }
56 resolve(selectedPort)
57 })
58 })
59 server.on(`error`, reject)
60 })
61}
62
63function createRuntimeError(
64 message: string,
65 stderr: string,
66 stdout: string,
67): Error {
68 return new Error([message, `stderr=${stderr}`, `stdout=${stdout}`].join(`\n`))
69}
70
71async function stopWranglerProcess(
72 child: ReturnType<typeof spawn> | undefined,
73): Promise<void> {
74 if (!child || child.exitCode !== null) {
75 return
76 }
77
78 child.kill(`SIGTERM`)
79 const closed = await Promise.race([
80 new Promise<boolean>((resolve) => {
81 child.once(`close`, () => resolve(true))
82 }),
83 delay(5_000).then(() => false),
84 ])
85
86 if (closed) {
87 return
88 }
89
90 child.kill(`SIGKILL`)
91 await new Promise<void>((resolve) => {
92 child.once(`close`, () => resolve())
93 })
94}
95
96export async function startWranglerRuntime(options: {
97 persistPath: string
98 syncEnabled?: boolean
99 schemaVersion?: number
100 collectionId?: string
101}): Promise<RuntimeProcessHarness> {
102 let child: ReturnType<typeof spawn> | undefined
103 let stdoutBuffer = ``
104 let stderrBuffer = ``
105 const port = await getAvailablePort()
106
107 const spawnProcess = async (): Promise<void> => {
108 const runtimeVarEntries = [
109 [
110 `PERSISTENCE_WITH_SYNC`,
111 options.syncEnabled !== undefined
112 ? String(options.syncEnabled)
113 : undefined,
114 ],
115 [
116 `PERSISTENCE_SCHEMA_VERSION`,
117 options.schemaVersion !== undefined
118 ? String(options.schemaVersion)
119 : undefined,
120 ],
121 [`PERSISTENCE_COLLECTION_ID`, options.collectionId],
122 ].filter((entry): entry is [string, string] => entry[1] !== undefined)
123
124 const wranglerArgs = [
125 `dev`,
126 `--local`,
127 `--ip`,
128 `127.0.0.1`,
129 `--port`,
130 String(port),
131 `--persist-to`,
132 options.persistPath,
133 `--config`,
134 wranglerConfigPath,
135 ...runtimeVarEntries.flatMap(([key, value]) => [
136 `--var`,
137 `${key}:${value}`,
138 ]),
139 ]
140
141 child = spawn(process.execPath, [wranglerBinPath, ...wranglerArgs], {
142 cwd: packageDirectory,
143 env: {
144 ...process.env,
145 CI: `1`,
146 WRANGLER_SEND_METRICS: `false`,
147 },
148 stdio: [`ignore`, `pipe`, `pipe`],
149 })
150
151 if (!child.stdout || !child.stderr) {
152 throw new Error(`Unable to capture wrangler dev process output streams`)
153 }
154
155 child.stdout.on(`data`, (chunk: Buffer) => {
156 stdoutBuffer += chunk.toString()
157 })
158 child.stderr.on(`data`, (chunk: Buffer) => {
159 stderrBuffer += chunk.toString()
160 })
161
162 const baseUrl = `http://127.0.0.1:${String(port)}`
163 const startAt = Date.now()
164 while (Date.now() - startAt < 45_000) {
165 if (child.exitCode !== null) {
166 throw createRuntimeError(
167 `Wrangler dev exited before becoming healthy`,
168 stderrBuffer,
169 stdoutBuffer,
170 )
171 }
172
173 try {
174 const healthResponse = await fetch(`${baseUrl}/health`)
175 if (healthResponse.ok) {
176 return
177 }
178 } catch {
179 // Runtime may still be starting.
180 }
181
182 await delay(250)
183 }
184
185 throw createRuntimeError(
186 `Timed out waiting for wrangler dev runtime`,
187 stderrBuffer,
188 stdoutBuffer,
189 )
190 }
191
192 await spawnProcess()
193
194 return {
195 baseUrl: `http://127.0.0.1:${String(port)}`,
196 restart: async () => {
197 await stopWranglerProcess(child)
198 stdoutBuffer = ``
199 stderrBuffer = ``
200 await spawnProcess()
201 },
202 stop: async () => {
203 await stopWranglerProcess(child)
204 },
205 getOutput: () => ({
206 stderr: stderrBuffer,
207 stdout: stdoutBuffer,
208 }),
209 }
210}
211
212export async function postJson<TPayload>(
213 runtime: RuntimeProcessHarness,
214 path: string,
215 body: unknown,
216): Promise<WranglerRuntimeResponse<TPayload>> {
217 let response: Response
218 try {
219 response = await fetch(`${runtime.baseUrl}${path}`, {
220 method: `POST`,
221 headers: {
222 'content-type': `application/json`,
223 },
224 body: JSON.stringify(body),
225 signal: AbortSignal.timeout(30_000),
226 })
227 } catch (error) {
228 const output = runtime.getOutput()
229 throw createRuntimeError(
230 `Timed out waiting for wrangler dev runtime response: ${String(error)}`,
231 output.stderr,
232 output.stdout,
233 )
234 }
235
236 const parsed = (await response.json()) as WranglerRuntimeResponse<TPayload>
237 return parsed
238}