Open History to see the last commit
1import { randomBytes, createHash } from 'node:crypto'
2import { build } from 'esbuild'
3import { zipSync } from 'fflate'
4import pg from 'pg'
5
6export async function deployTestWebhook({ neon, projectId, branchId, schema, sourceUrl, previous }) {
7 const admin = previous?.TEST_WEBHOOK_RECEIVER_KEY ?? randomBytes(32).toString('hex')
8 if (process.env.GITHUB_ACTIONS === 'true') console.log(`::add-mask::${admin}`)
9 const pool = new pg.Pool({ connectionString: process.env.TEST_DATABASE_URL_UNPOOLED, max: 1 })
10 let jwks
11 try {
12 await pool.query(`CREATE TABLE IF NOT EXISTS "${schema}".webhook_test_deliveries (
13 wake_id text PRIMARY KEY, subscription_id text NOT NULL, payload jsonb NOT NULL, raw_body bytea NOT NULL,
14 signature text NOT NULL, attempts integer NOT NULL DEFAULT 1)`)
15 jwks = { keys: (await pool.query(`SELECT public_jwk FROM "${schema}".webhook_signing_keys`)).rows.map((row) => row.public_jwk) }
16 } finally { await pool.end() }
17 const bundle = await build({ entryPoints: ['test/fixtures/webhook-function.ts'], bundle: true, platform: 'node', target: 'node24', format: 'esm', write: false,
18 external: ['pg-native'], banner: { js: 'import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);' } })
19 const code = bundle.outputFiles[0].contents
20 const hash = createHash('sha256').update(code).digest('hex')
21 const slug = 'dswebhookreceiver'
22 const deployed = await neon.functions.deploy({ projectId, branchId, slug, runtime: 'nodejs24',
23 zip: new File([zipSync({ 'index.mjs': code })], 'webhook-receiver.zip', { type: 'application/zip' }),
24 environment: JSON.stringify({ DS_SCHEMA: schema, DS_RECEIVER_KEY: admin, DS_RECEIVER_JWKS: JSON.stringify(jwks),
25 DS_EXPECTED_SERVER: new URL('v1/stream', sourceUrl).href, DS_BUILD_HASH: hash }) })
26 const deadline = Date.now() + 180_000
27 let url
28 while (Date.now() < deadline) {
29 const fn = await neon.functions.get({ projectId, branchId, slug })
30 if (fn.current_deployment?.id === deployed.id && fn.current_deployment.status === 'failed') throw new Error('HTTPS receiver Function build failed')
31 if (fn.active_deployment?.id === deployed.id && fn.invocation_url) { url = fn.invocation_url; break }
32 await new Promise((resolve) => setTimeout(resolve, 1000))
33 }
34 if (!url) throw new Error('HTTPS receiver Function did not become active')
35 while (Date.now() < deadline) {
36 try {
37 const response = await fetch(new URL('health', url), { headers: { Authorization: admin }, signal: AbortSignal.timeout(10_000) })
38 if (response.ok && (await response.json()).build === hash) return { TEST_WEBHOOK_RECEIVER_URL: url, TEST_WEBHOOK_RECEIVER_KEY: admin }
39 } catch { /* Cold starts are bounded by the outer deployment deadline. */ }
40 await new Promise((resolve) => setTimeout(resolve, 1000))
41 }
42 throw new Error('HTTPS receiver Function failed its runtime readiness check')
43}