Skip to content
Source
Sign inSign up
samwillis/neon-realtime-electric
Open History to see the last commit

local-function.ts

109 lines3.3 KB

1import { spawn } from 'node:child_process'
2import { createWriteStream } from 'node:fs'
3import { mkdir } from 'node:fs/promises'
4import { createServer } from 'node:net'
5import { once } from 'node:events'
6import type { ConfiguredTable } from '../../../packages/server/src/definition.js'
7​
8/** Credentialed integration harness; never provisions or deploys a Function. */
9export async function startLocalFunction(options: {
10 tables: ConfiguredTable[]
11 realtimeUrl: string
12 artifact: string
13}) {
14 for (const name of ['DATABASE_URL', 'NEON_REALTIME_SECRET'])
15 if (!process.env[name])
16 throw new Error(
17 `Local Function integration requires ${name}; load the ignored environment file`
18 )
19 await mkdir('.artifacts/staging', { recursive: true })
20 const output = createWriteStream(
21 `.artifacts/staging/${options.artifact}-function.log`
22 )
23 const socket = createServer()
24 socket.listen(0, '127.0.0.1')
25 await once(socket, 'listening')
26 const port = (socket.address() as { port: number }).port
27 await new Promise<void>((resolve) => socket.close(() => resolve()))
28 const origin = `http://127.0.0.1:${port}`
29 const child = spawn(
30 'neon',
31 [
32 ...(process.env.NEON_CLI_PROFILE
33 ? ['--profile', process.env.NEON_CLI_PROFILE]
34 : []),
35 'dev',
36 '--source',
37 'tests/integration/support/configured-function.ts',
38 '--port',
39 String(port),
40 ],
41 {
42 env: {
43 ...process.env,
44 NEON_REALTIME_URL: options.realtimeUrl,
45 NEON_TEST_SHAPE_CONFIG: JSON.stringify(options.tables),
46 },
47 stdio: ['ignore', 'pipe', 'pipe'],
48 }
49 )
50 child.stdout!.pipe(output, { end: false })
51 child.stderr!.pipe(output, { end: false })
52 let startupError: Error | undefined
53 child.once('error', (error) => {
54 startupError = error
55 })
56 let stopped = false
57 const stop = async () => {
58 if (stopped) return
59 stopped = true
60 if (child.pid && child.exitCode === null && child.signalCode === null) {
61 const exited = once(child, 'exit')
62 child.kill('SIGTERM')
63 let timer: ReturnType<typeof setTimeout> | undefined
64 try {
65 await Promise.race([
66 exited,
67 new Promise<void>((resolve) => {
68 timer = setTimeout(() => {
69 child.kill('SIGKILL')
70 resolve()
71 }, 5000)
72 }),
73 ])
74 } finally {
75 clearTimeout(timer)
76 }
77 }
78 output.end()
79 }
80 try {
81 const deadline = Date.now() + 25_000
82 const ready = new URL('/proxy/shapes', origin)
83 ready.searchParams.set('table', options.tables[0].table)
84 while (Date.now() < deadline) {
85 if (startupError) throw startupError
86 if (child.exitCode !== null || child.signalCode !== null)
87 throw new Error('neon dev exited before readiness')
88 try {
89 // HEAD validates the allowlist without creating a Realtime subscription.
90 if (
91 (
92 await fetch(ready, {
93 method: 'HEAD',
94 signal: AbortSignal.timeout(1000),
95 })
96 ).status === 404
97 )
98 return { origin, stop }
99 } catch {
100 /* Server is still starting. */
101 }
102 await new Promise((resolve) => setTimeout(resolve, 100))
103 }
104 throw new Error('neon dev did not become ready')
105 } catch (error) {
106 await stop()
107 throw error
108 }