Open History to see the last commit
1import { spawn, execFile } from "node:child_process"
2import { promisify } from "node:util"
3import type { ChildProcess } from "node:child_process"
4import { mkdtemp, rm } from "node:fs/promises"
5import { join, resolve } from "node:path"
6import { randomBytes } from "node:crypto"
7import { connect } from "node:net"
8
9const root = resolve(import.meta.dirname, "..")
10
11export async function eventually(
12 check: () => boolean | Promise<boolean>,
13 label: string,
14 timeout = 30000,
15) {
16 const deadline = Date.now() + timeout
17 while (Date.now() < deadline) {
18 if (await check()) return
19 await new Promise((resolve) => setTimeout(resolve, 100))
20 }
21 throw new Error(`Timed out: ${label}`)
22}
23
24/** All test writes target an owned disposable cluster, never the development game. */
25export async function startTestStack(withUi = false) {
26 const backend = process.env.NEON_REALTIME_BACKEND_DIR
27 if (!backend)
28 throw new Error("Set NEON_REALTIME_BACKEND_DIR to your matching Realtime backend checkout.")
29 const pgBin = process.env.PG_BIN ?? join(root, ".local/realtime/pg_install/v18/bin")
30 const proxyBin =
31 process.env.REALTIME_PROXY_BIN ??
32 join(backend, "pgxn/neon_realtime/target/debug/realtime-proxy")
33 // macOS's default temp path is too long for Postgres's 103-byte Unix socket limit.
34 const dir = await mkdtemp("/tmp/boxes-test-")
35 const apiUrl = "http://127.0.0.1:3002",
36 realtimeUrl = "ws://127.0.0.1:8081"
37 const env = {
38 ...process.env,
39 PG_CONFIG: join(pgBin, "pg_config"),
40 NEON_REALTIME_DEV_ROOT: dir,
41 NEON_REALTIME_DEV_POSTGRES_PORT: "55441",
42 NEON_REALTIME_DEV_LISTENER_PORT: "55442",
43 API_PORT: "3002",
44 REALTIME_PUBLIC_URL: realtimeUrl,
45 REALTIME_SECRET: `nrt_live_1${randomBytes(32).toString("base64url")}`,
46 TEAM_COOKIE_SECRET: randomBytes(32).toString("hex"),
47 REALTIME_LISTEN_ADDR: "127.0.0.1:8081",
48 REALTIME_BRANCH_ID: "test-branch",
49 REALTIME_DATABASES: "postgres=test-database",
50 REALTIME_ALLOWED_ORIGINS: "http://127.0.0.1:5174",
51 OTEL_SDK_DISABLED: "true",
52 }
53 const children: ChildProcess[] = []
54 let stopping = false
55 const launch = (bin: string, args: string[]) => {
56 const child = spawn(bin, args, { cwd: root, env, stdio: ["ignore", "pipe", "pipe"] })
57 let output = ""
58 child.stdout?.on("data", (chunk) => {
59 output = (output + chunk).slice(-16000)
60 })
61 child.stderr?.on("data", (chunk) => {
62 output = (output + chunk).slice(-16000)
63 })
64 let error: Error | undefined
65 child.on("error", (value) => {
66 error = value
67 })
68 children.push(child)
69 return {
70 child,
71 output: () => {
72 if (error) throw error
73 if (!stopping && (child.exitCode !== null || child.signalCode !== null))
74 throw new Error(`${bin} exited:\n${output}`)
75 return output
76 },
77 }
78 }
79 const stopChild = async (child: ChildProcess) => {
80 if (child.exitCode !== null || child.signalCode !== null || !child.pid) return
81 const exited = new Promise<void>((resolve) => child.once("exit", () => resolve()))
82 child.kill("SIGTERM")
83 const timer = setTimeout(() => child.kill("SIGKILL"), 10000)
84 await exited
85 clearTimeout(timer)
86 }
87 const stop = async () => {
88 if (stopping) return
89 stopping = true
90 for (const child of [...children].reverse()) await stopChild(child)
91 await rm(dir, { recursive: true, force: true })
92 }
93 try {
94 const database = launch("bash", [join(backend, "pgxn/neon_realtime/scripts/dev-server.sh")])
95 await eventually(
96 () => database.output().includes("Disposable Neon Realtime instance is ready."),
97 "test Postgres startup",
98 )
99 const output = database.output()
100 const databaseUrl = output.match(/NEON_REALTIME_DATABASE_URL='([^']+)'/)?.[1]
101 const socket = output.match(/unix:\/\/([^']+)'/)?.[1]
102 if (!databaseUrl || !socket) throw new Error("Missing test database connection details")
103 Object.assign(env, {
104 DATABASE_URL: databaseUrl,
105 DATABASE_URL_UNPOOLED: databaseUrl,
106 NEON_REALTIME_URL: realtimeUrl,
107 NEON_REALTIME_SECRET: env.REALTIME_SECRET,
108 REALTIME_NEON_REALTIME_SOCKET: socket,
109 })
110 // Install only into the owned disposable database, before starting the API.
111 await promisify(execFile)(
112 process.execPath,
113 ["node_modules/tsx/dist/cli.mjs", "scripts/init-db.ts"],
114 {
115 cwd: root,
116 env,
117 timeout: 30000,
118 },
119 )
120 let proxy = launch(proxyBin, [])
121 const waitProxy = async () =>
122 eventually(async () => {
123 proxy.output()
124 return new Promise<boolean>((resolve) => {
125 const socket = connect(8081, "127.0.0.1")
126 socket.on("connect", () => {
127 socket.destroy()
128 resolve(true)
129 })
130 socket.on("error", () => resolve(false))
131 })
132 }, "test proxy startup")
133 await waitProxy()
134 const api = launch(process.execPath, ["node_modules/tsx/dist/cli.mjs", "server/index.ts"])
135 await eventually(async () => {
136 api.output()
137 return fetch(`${apiUrl}/api/health`)
138 .then((response) => response.ok)
139 .catch(() => false)
140 }, "test API startup")
141 if (withUi) {
142 const ui = launch(process.execPath, ["node_modules/vite/bin/vite.js", "--port", "5174"])
143 await eventually(async () => {
144 ui.output()
145 return fetch("http://127.0.0.1:5174")
146 .then((response) => response.ok)
147 .catch(() => false)
148 }, "test UI startup")
149 }
150 return {
151 databaseUrl,
152 apiUrl,
153 realtimeUrl,
154 identitySecret: env.TEAM_COOKIE_SECRET,
155 stop,
156 restartProxy: async () => {
157 await stopChild(proxy.child)
158 proxy = launch(proxyBin, [])
159 await waitProxy()
160 },
161 }
162 } catch (error) {
163 await stop()
164 throw error
165 }
166}