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

neon-test-function.mjs

130 lines9.8 KB

1import { randomBytes, randomUUID, createHash } from 'node:crypto'
2import { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises'
3import { build } from 'esbuild'
4import { zipSync } from 'fflate'
5import { createNeonClient } from '@neon/sdk'
6import pg from 'pg'
7import { execFileSync } from 'node:child_process'
8import { deployTestWebhook } from './neon-test-webhook.mjs'
9import { migrate, MIGRATION_IDS } from '../dist/migrations.js'
10import { createS3ChunkStorage } from '../dist/s3.js'
11import { initializeSubscriptions, parseSubscriptionKeyring } from '../dist/subscriptions.js'
12​
13const projectId = process.env.NEON_PROJECT_ID
14const apiKey = process.env.NEON_API_KEY
15const branchId = process.env.NEON_TEST_BRANCH_ID
16const stateFile = process.env.NEON_TEST_STATE_FILE ?? '.neon-test-state.json'
17const outputFile = process.env.NEON_TEST_FUNCTION_ENV_FILE ?? '.env.neon.function'
18if (!projectId || !apiKey || !branchId || !process.env.TEST_DATABASE_URL_UNPOOLED || !process.env.NEON_REALTIME_URL || !process.env.NEON_REALTIME_SECRET || !process.env.NEON_TEST_BUCKET || !process.env.DURABLE_STREAMS_KEYRING) throw new Error('Complete isolated Neon test environment required before Function deployment')
19const state = JSON.parse(await readFile(stateFile, 'utf8'))
20if (state.projectId !== projectId || state.branchId !== branchId || !state.name.startsWith('ds-test-')) throw new Error('Function deployment requires the recorded isolated test branch')
21const neon = createNeonClient({ apiKey, throwOnError: true })
22const branch = await neon.branches.get({ projectId, branchId })
23if (branch.name !== state.name) throw new Error('Test branch identity changed')
24const secret = () => randomBytes(32).toString('hex')
25let previous
26try { previous = Object.fromEntries((await readFile(outputFile, 'utf8')).trim().split('\n').map((line) => { const n = line.indexOf('='); return [line.slice(0, n), line.slice(n + 1)] })) }
27catch (error) { if (error.code !== 'ENOENT') throw error }
28if (previous && previous.TEST_FUNCTION_BRANCH_ID !== branchId) throw new Error('Refusing to overwrite another test branch Function environment')
29const schema = previous?.TEST_FUNCTION_SCHEMA ?? `ds_test_${randomUUID().replaceAll('-', '')}`
30if (!/^ds_test_[a-f0-9]{32}$/.test(schema)) throw new Error('Invalid Function test schema')
31const userKey = previous?.TEST_FUNCTION_API_KEY ?? secret()
32const otherKey = previous?.TEST_FUNCTION_OTHER_KEY ?? secret()
33const maintenanceKey = previous?.TEST_FUNCTION_MAINTENANCE_KEY ?? secret()
34const hintMode = process.env.NEON_TEST_MAINTENANCE_HINTS ?? 'off'
35const liveInterval = (name) => {
36 const value = Number(process.env[name] ?? 60_000)
37 if (!Number.isSafeInteger(value) || value < 100 || value > 60_000) throw new Error(`Invalid ${name}`)
38 return String(value)
40const liveFallbackMs = liveInterval('NEON_TEST_LIVE_FALLBACK_MS')
41const liveValidationMs = liveInterval('NEON_TEST_LIVE_VALIDATION_MS')
42if (!['on', 'off'].includes(hintMode)) throw new Error('Invalid test maintenance hint mode')
43if (process.env.GITHUB_ACTIONS === 'true') for (const value of [userKey, otherKey, maintenanceKey]) console.log(`::add-mask::${value}`)
44const objects = createS3ChunkStorage({ endpoint: process.env.AWS_ENDPOINT_URL_S3, region: process.env.AWS_REGION, bucket: process.env.NEON_TEST_BUCKET })
45const direct = new pg.Pool({ connectionString: process.env.TEST_DATABASE_URL_UNPOOLED, max: 1 })
46try {
47 const installed = await direct.query('SELECT to_regclass($1) AS relation', [`${schema}.migrations`])
48 if (installed.rows[0].relation) {
49 const history = await direct.query(`SELECT id FROM "${schema}".migrations ORDER BY id`)
50 if (history.rows.length !== MIGRATION_IDS.length || history.rows.some((row, index) => row.id !== MIGRATION_IDS[index])) {
51 throw new Error('The recorded test schema predates the current baseline; provision a fresh test environment')
52 }
53 }
54 await migrate(direct, { schema, storageIdentity: objects.identity, environmentId: branchId })
55 await initializeSubscriptions(direct, { schema, keyring: parseSubscriptionKeyring(process.env.DURABLE_STREAMS_KEYRING) })
57finally { await direct.end(); objects.close() }
58const bundle = await build({ entryPoints: ['examples/neon-function/index.ts'], bundle: true, platform: 'node', target: 'node24', format: 'esm', write: false,
59 external: ['pg-native', 'bufferutil', 'utf-8-validate'],
60 banner: { js: 'import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);' },
61})
62if (bundle.outputFiles.length !== 1) throw new Error('Expected a single self-contained Function bundle')
63const code = bundle.outputFiles[0].contents
64const hash = createHash('sha256').update(code).digest('hex')
65const sourceCommit = execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim()
66const deploymentId = randomUUID()
67const sourceDirty = execFileSync('git', ['status', '--porcelain', '--untracked-files=all', '--', 'src', 'examples/neon-function', 'package.json', 'pnpm-lock.yaml'], { encoding: 'utf8' }).trim() ? 'yes' : 'no'
68const deployment = await neon.functions.deploy({ projectId, branchId, slug: 'durablestreams', runtime: 'nodejs24',
69 zip: new File([zipSync({ 'index.mjs': code })], 'durable-streams.zip', { type: 'application/zip' }),
70 environment: JSON.stringify({ DS_SCHEMA: schema, DS_ENVIRONMENT_ID: branchId, DS_BUCKET: process.env.NEON_TEST_BUCKET,
71 DS_REALTIME_URL: process.env.NEON_REALTIME_URL, DS_REALTIME_SECRET: process.env.NEON_REALTIME_SECRET,
72 DS_KEYRING_JSON: process.env.DURABLE_STREAMS_KEYRING,
73 DS_AUTH_JSON: JSON.stringify([{ key: userKey, tenantId: 'function-a', subject: 'qualification-a' }, { key: otherKey, tenantId: 'function-b', subject: 'qualification-b' }]),
74 DS_MAINTENANCE_KEY: maintenanceKey, DS_BUILD_HASH: hash, DS_DEPLOYMENT_ID: deploymentId,
75 DS_MAINTENANCE_TRIGGER_NAME: 'durable-streams-maintenance', DS_LIVE_FALLBACK_MS: liveFallbackMs, DS_LIVE_VALIDATION_MS: liveValidationMs,
76 DS_MAX_CHUNK_AGE_MS: process.env.NEON_TEST_NO_CRON === '1' ? '3600000' : '1000', DS_MAINTENANCE_HINTS: hintMode, DS_CRON_MAX_CHUNKS: '64', DS_CRON_SUBSCRIPTION_WORK: '64' }),
77})
78let url
79const deadline = Date.now() + 180_000
80while (Date.now() < deadline) {
81 const fn = await neon.functions.get({ projectId, branchId, slug: 'durablestreams' })
82 if (fn.current_deployment?.id === deployment.id && fn.current_deployment.status === 'failed') throw new Error(`Function build failed: ${fn.current_deployment.error ?? 'unknown build error'}`)
83 if (fn.active_deployment?.id === deployment.id && fn.invocation_url) { url = fn.invocation_url; break }
84 await new Promise((resolve) => setTimeout(resolve, 1000))
86if (!url) throw new Error('Neon Function deployment did not become active')
87const triggerName = 'durable-streams-maintenance'
88const existing = (await neon.triggers.list({ projectId, branchId })).find((item) => item.name === triggerName)
89const noCron = process.env.NEON_TEST_NO_CRON === '1'
90if (noCron && existing) throw new Error('Cron-free qualification requires a fresh isolated branch')
91if (!noCron && !existing) await neon.triggers.create({ projectId, branchId, type: 'schedule', name: triggerName,
92 function_slug: 'durablestreams', function_path: '/_trigger', schedule: { cron: '* * * * *' } })
93const receiver = await deployTestWebhook({ neon, projectId, branchId, schema, sourceUrl: url, previous })
94const values = { ...receiver, TEST_FUNCTION_URL: url, TEST_FUNCTION_API_KEY: userKey, TEST_FUNCTION_OTHER_KEY: otherKey,
95 TEST_FUNCTION_MAINTENANCE_KEY: maintenanceKey, TEST_FUNCTION_SCHEMA: schema, TEST_FUNCTION_BRANCH_ID: branchId, TEST_FUNCTION_BUNDLE_SHA: hash,
96 TEST_FUNCTION_SOURCE_COMMIT: sourceCommit, TEST_FUNCTION_SOURCE_DIRTY: sourceDirty, TEST_FUNCTION_DEPLOYMENT_ID: deploymentId,
97 TEST_FUNCTION_MAINTENANCE_HINTS: hintMode, TEST_FUNCTION_HAS_CRON: noCron ? 'no' : 'yes', TEST_FUNCTION_CRON_CHUNKS: '64', TEST_FUNCTION_CRON_SUBSCRIPTION_WORK: '64',
98 TEST_FUNCTION_LIVE_FALLBACK_MS: liveFallbackMs, TEST_FUNCTION_LIVE_VALIDATION_MS: liveValidationMs }
99if (process.env.GITHUB_ACTIONS === 'true') for (const [key, value] of Object.entries(values)) if (/_KEY$|_URL$/.test(key)) console.log(`::add-mask::${value}`)
100const environment = Object.entries(values).map(([k, v]) => `${k}=${v}`).join('\n') + '\n'
101if (process.env.GITHUB_ENV) await appendFile(process.env.GITHUB_ENV, environment)
102else await writeFile(outputFile, environment, { mode: 0o600 })
103// Deployment readiness is not runtime readiness. Verify the actual HTTP handler.
104let ready = false
105let consecutiveReady = 0
106const readinessProbes = []
107const readinessStarted = performance.now()
108while (Date.now() < deadline) {
109 try {
110 const response = await fetch(new URL('health', url), { headers: { Authorization: `Bearer ${userKey}` }, signal: AbortSignal.timeout(15_000) })
111 let matches = false
112 if (response.ok) {
113 const health = await response.json()
114 matches = health.ready === true && health.build === hash && health.deploymentId === deploymentId
115 } else await response.arrayBuffer()
116 readinessProbes.push({ status: response.status, matches, elapsedMs: Math.round(performance.now() - readinessStarted) })
117 consecutiveReady = matches ? consecutiveReady + 1 : 0
118 if (consecutiveReady >= 3) { ready = true; break }
119 } catch {
120 consecutiveReady = 0
121 readinessProbes.push({ status: 'network-error', matches: false, elapsedMs: Math.round(performance.now() - readinessStarted) })
122 }
123 await new Promise((resolve) => setTimeout(resolve, 1000))
125await mkdir('qualification-results', { recursive: true })
126await writeFile(`qualification-results/function-readiness-${branchId}-${deploymentId}.json`, JSON.stringify({
127 branchId, deploymentId, bundleSha256: hash, ready, consecutiveReady, durationMs: Math.round(performance.now() - readinessStarted), probes: readinessProbes,
128}, null, 2) + '\n')
129if (!ready) throw new Error('Deployed Function failed its authenticated runtime health check')
130console.log(`Deployed and verified the current bundle on test branch ${branchId}.`)