Open History to see the last commit
1import { spawn, spawnSync } from "node:child_process"
2import type { ChildProcess } from "node:child_process"
3import { existsSync } from "node:fs"
4import { mkdir, readFile, writeFile } from "node:fs/promises"
5import { randomBytes } from "node:crypto"
6import { resolve, join } from "node:path"
7import { userInfo } from "node:os"
8import pg from "pg"
9
10const root = resolve(import.meta.dirname, "..")
11const local = join(root, ".local/dev")
12const backend = process.env.NEON_REALTIME_BACKEND_DIR
13if (!backend)
14 throw new Error("Set NEON_REALTIME_BACKEND_DIR to your matching Realtime backend checkout.")
15const pgBin = process.env.PG_BIN ?? join(root, ".local/realtime/pg_install/v18/bin")
16const proxy =
17 process.env.REALTIME_PROXY_BIN ?? join(backend, "pgxn/neon_realtime/target/debug/realtime-proxy")
18const data = join(local, "pgdata"),
19 pgSocket = join(local, "postgres-socket"),
20 realtimeSocket = join(local, "realtime-socket")
21const children: ChildProcess[] = []
22let stopping = false,
23 ownsPostgres = false
24const env = { ...process.env }
25
26function command(bin: string, args: string[]) {
27 const result = spawnSync(bin, args, { cwd: root, env, stdio: "inherit" })
28 if (result.error) throw result.error
29 if (result.status !== 0) throw new Error(`${bin} failed (${result.status})`)
30}
31function launch(bin: string, args: string[]) {
32 const child = spawn(bin, args, { cwd: root, env, stdio: "inherit" })
33 children.push(child)
34 child.on("error", (error) => {
35 console.error(error)
36 void shutdown(1)
37 })
38 child.on("exit", (code) => {
39 if (!stopping) {
40 console.error(`${bin} exited (${code})`)
41 void shutdown(code || 1)
42 }
43 })
44 return child
45}
46async function shutdown(code: number) {
47 if (stopping) return
48 stopping = true
49 const exited = children.map(
50 (child) =>
51 new Promise<void>((resolve) => {
52 if (child.exitCode !== null || child.signalCode !== null) return resolve()
53 child.once("exit", () => resolve())
54 child.kill("SIGTERM")
55 }),
56 )
57 await Promise.race([Promise.all(exited), new Promise((resolve) => setTimeout(resolve, 5000))])
58 for (const child of children)
59 if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL")
60 if (ownsPostgres) command(join(pgBin, "pg_ctl"), ["-D", data, "-m", "fast", "-w", "stop"])
61 process.exit(code)
62}
63for (const signal of ["SIGINT", "SIGTERM"] as const)
64 process.on(signal, () => {
65 void shutdown(0)
66 })
67
68try {
69 await mkdir(local, { recursive: true })
70 let persisted: Record<string, string> = {}
71 try {
72 persisted = JSON.parse(await readFile(join(local, "runtime.json"), "utf8"))
73 } catch {
74 /* First run. */
75 }
76 env.REALTIME_SECRET ??=
77 persisted.REALTIME_SECRET ?? `nrt_live_1${randomBytes(32).toString("base64url")}`
78 env.TEAM_COOKIE_SECRET ??= persisted.TEAM_COOKIE_SECRET ?? randomBytes(32).toString("hex")
79 env.REALTIME_PUBLIC_URL ??= "ws://127.0.0.1:8080"
80 env.API_PORT ??= "3001"
81 env.OTEL_SDK_DISABLED ??= "true"
82 if (!existsSync(proxy))
83 throw new Error("Realtime proxy is missing. Run pnpm setup:local-realtime first.")
84 if (!env.DATABASE_URL) {
85 if (!existsSync(join(pgBin, "initdb")))
86 throw new Error("Postgres is missing. Run pnpm setup:local-realtime first.")
87 await mkdir(pgSocket, { recursive: true })
88 await mkdir(realtimeSocket, { recursive: true })
89 if (!existsSync(join(data, "PG_VERSION"))) {
90 command(join(pgBin, "initdb"), ["-D", data, "-A", "trust", "--no-locale", "--encoding=UTF8"])
91 await writeFile(
92 join(data, "postgresql.auto.conf"),
93 `listen_addresses = '127.0.0.1'
94port = 55431
95unix_socket_directories = '${pgSocket.replaceAll("'", "''")}'
96shared_preload_libraries = 'neon_rmgr,neon_realtime'
97wal_level = logical
98output_plugin_libraries = 'neon_realtime'
99max_replication_slots = 8
100max_wal_senders = 8
101max_worker_processes = 16
102max_prepared_transactions = 10
103neon_realtime.listen_address = '127.0.0.1'
104neon_realtime.port = 55432
105neon_realtime.unix_socket_directory = '${realtimeSocket.replaceAll("'", "''")}'
106`,
107 )
108 }
109 const status = spawnSync(join(pgBin, "pg_ctl"), ["-D", data, "status"], { stdio: "ignore" })
110 if (status.status === 0)
111 throw new Error("This app's Postgres is already running; stop the other dev session first.")
112 command(join(pgBin, "pg_ctl"), ["-D", data, "-l", join(local, "postgres.log"), "-w", "start"])
113 ownsPostgres = true
114 env.DATABASE_URL = `postgresql://${encodeURIComponent(userInfo().username)}@127.0.0.1:55431/postgres`
115 env.REALTIME_NEON_REALTIME_SOCKET = join(realtimeSocket, "neon_realtime.sock")
116 }
117 if (!env.REALTIME_NEON_REALTIME_SOCKET)
118 throw new Error("Set REALTIME_NEON_REALTIME_SOCKET when using an external DATABASE_URL")
119 await writeFile(
120 join(local, "runtime.json"),
121 JSON.stringify(
122 {
123 DATABASE_URL: env.DATABASE_URL,
124 REALTIME_SECRET: env.REALTIME_SECRET,
125 TEAM_COOKIE_SECRET: env.TEAM_COOKIE_SECRET,
126 REALTIME_PUBLIC_URL: env.REALTIME_PUBLIC_URL,
127 API_PORT: env.API_PORT,
128 },
129 null,
130 2,
131 ),
132 { mode: 0o600 },
133 )
134 const pool = new pg.Pool({ connectionString: env.DATABASE_URL })
135 try {
136 await pool.query("CREATE EXTENSION IF NOT EXISTS neon_realtime")
137 } finally {
138 await pool.end()
139 }
140 // Fixture setup is a one-off script, separate from the watched API process.
141 // Pin both URLs so .env.local can never direct this setup at a cloud database.
142 env.NEON_REALTIME_URL = env.REALTIME_PUBLIC_URL
143 env.NEON_REALTIME_SECRET = env.REALTIME_SECRET
144 env.DATABASE_URL_UNPOOLED = env.DATABASE_URL
145 command(process.execPath, [join(root, "node_modules/tsx/dist/cli.mjs"), "scripts/init-db.ts"])
146 env.REALTIME_LISTEN_ADDR ??= new URL(env.REALTIME_PUBLIC_URL).host
147 env.REALTIME_BRANCH_ID ??= "local-branch"
148 env.REALTIME_DATABASES ??= "postgres=local-database"
149 env.REALTIME_ALLOWED_ORIGINS ??= "http://127.0.0.1:5173,http://localhost:5173"
150 launch(proxy, [])
151 launch(process.execPath, [
152 join(root, "node_modules/tsx/dist/cli.mjs"),
153 "watch",
154 "server/index.ts",
155 ])
156 launch(process.execPath, [join(root, "node_modules/vite/bin/vite.js")])
157 console.log(
158 "\n1 Million Boxes: http://127.0.0.1:5173\nPostgres data persists in .local/dev/pgdata. Ctrl-C stops the stack.\n",
159 )
160} catch (error) {
161 console.error(error)
162 await shutdown(1)
163}