Open History to see the last commit
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 } 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)
39}
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 { await migrate(direct, { schema, storageIdentity: objects.identity, environmentId: branchId }); await initializeSubscriptions(direct, { schema, keyring: parseSubscriptionKeyring(process.env.DURABLE_STREAMS_KEYRING) }) }
47finally { await direct.end(); objects.close() }
48const bundle = await build({ entryPoints: ['examples/neon-function/index.ts'], bundle: true, platform: 'node', target: 'node24', format: 'esm', write: false,
49 external: ['pg-native', 'bufferutil', 'utf-8-validate'],
50 banner: { js: 'import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);' },
51})
52if (bundle.outputFiles.length !== 1) throw new Error('Expected a single self-contained Function bundle')
53const code = bundle.outputFiles[0].contents
54const hash = createHash('sha256').update(code).digest('hex')
55const sourceCommit = execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim()
56const deploymentId = randomUUID()
57const sourceDirty = execFileSync('git', ['status', '--porcelain', '--untracked-files=all', '--', 'src', 'examples/neon-function', 'package.json', 'pnpm-lock.yaml'], { encoding: 'utf8' }).trim() ? 'yes' : 'no'
58const deployment = await neon.functions.deploy({ projectId, branchId, slug: 'durablestreams', runtime: 'nodejs24',
59 zip: new File([zipSync({ 'index.mjs': code })], 'durable-streams.zip', { type: 'application/zip' }),
60 environment: JSON.stringify({ DS_SCHEMA: schema, DS_ENVIRONMENT_ID: branchId, DS_BUCKET: process.env.NEON_TEST_BUCKET,
61 DS_REALTIME_URL: process.env.NEON_REALTIME_URL, DS_REALTIME_SECRET: process.env.NEON_REALTIME_SECRET,
62 DS_KEYRING_JSON: process.env.DURABLE_STREAMS_KEYRING,
63 DS_AUTH_JSON: JSON.stringify([{ key: userKey, tenantId: 'function-a', subject: 'qualification-a' }, { key: otherKey, tenantId: 'function-b', subject: 'qualification-b' }]),
64 DS_MAINTENANCE_KEY: maintenanceKey, DS_BUILD_HASH: hash, DS_DEPLOYMENT_ID: deploymentId,
65 DS_MAINTENANCE_TRIGGER_NAME: 'durable-streams-maintenance', DS_LIVE_FALLBACK_MS: liveFallbackMs, DS_LIVE_VALIDATION_MS: liveValidationMs,
66 DS_MAINTENANCE_HINTS: hintMode, DS_CRON_MAX_CHUNKS: '64', DS_CRON_SUBSCRIPTION_WORK: '64' }),
67})
68let url
69const deadline = Date.now() + 180_000
70while (Date.now() < deadline) {
71 const fn = await neon.functions.get({ projectId, branchId, slug: 'durablestreams' })
72 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'}`)
73 if (fn.active_deployment?.id === deployment.id && fn.invocation_url) { url = fn.invocation_url; break }
74 await new Promise((resolve) => setTimeout(resolve, 1000))
75}
76if (!url) throw new Error('Neon Function deployment did not become active')
77const triggerName = 'durable-streams-maintenance'
78const existing = (await neon.triggers.list({ projectId, branchId })).find((item) => item.name === triggerName)
79const noCron = process.env.NEON_TEST_NO_CRON === '1'
80if (noCron && existing) throw new Error('Cron-free qualification requires a fresh isolated branch')
81if (!noCron && !existing) await neon.triggers.create({ projectId, branchId, type: 'schedule', name: triggerName,
82 function_slug: 'durablestreams', function_path: '/_trigger', schedule: { cron: '* * * * *' } })
83const receiver = await deployTestWebhook({ neon, projectId, branchId, schema, sourceUrl: url, previous })
84const values = { ...receiver, TEST_FUNCTION_URL: url, TEST_FUNCTION_API_KEY: userKey, TEST_FUNCTION_OTHER_KEY: otherKey,
85 TEST_FUNCTION_MAINTENANCE_KEY: maintenanceKey, TEST_FUNCTION_SCHEMA: schema, TEST_FUNCTION_BRANCH_ID: branchId, TEST_FUNCTION_BUNDLE_SHA: hash,
86 TEST_FUNCTION_SOURCE_COMMIT: sourceCommit, TEST_FUNCTION_SOURCE_DIRTY: sourceDirty, TEST_FUNCTION_DEPLOYMENT_ID: deploymentId,
87 TEST_FUNCTION_MAINTENANCE_HINTS: hintMode, TEST_FUNCTION_HAS_CRON: noCron ? 'no' : 'yes', TEST_FUNCTION_CRON_CHUNKS: '64', TEST_FUNCTION_CRON_SUBSCRIPTION_WORK: '64',
88 TEST_FUNCTION_LIVE_FALLBACK_MS: liveFallbackMs, TEST_FUNCTION_LIVE_VALIDATION_MS: liveValidationMs }
89if (process.env.GITHUB_ACTIONS === 'true') for (const [key, value] of Object.entries(values)) if (/_KEY$|_URL$/.test(key)) console.log(`::add-mask::${value}`)
90const environment = Object.entries(values).map(([k, v]) => `${k}=${v}`).join('\n') + '\n'
91if (process.env.GITHUB_ENV) await appendFile(process.env.GITHUB_ENV, environment)
92else await writeFile(outputFile, environment, { mode: 0o600 })
93// Deployment readiness is not runtime readiness. Verify the actual HTTP handler.
94let ready = false
95let consecutiveReady = 0
96const readinessProbes = []
97const readinessStarted = performance.now()
98while (Date.now() < deadline) {
99 try {
100 const response = await fetch(new URL('health', url), { headers: { Authorization: `Bearer ${userKey}` }, signal: AbortSignal.timeout(15_000) })
101 let matches = false
102 if (response.ok) {
103 const health = await response.json()
104 matches = health.ready === true && health.build === hash && health.deploymentId === deploymentId
105 } else await response.arrayBuffer()
106 readinessProbes.push({ status: response.status, matches, elapsedMs: Math.round(performance.now() - readinessStarted) })
107 consecutiveReady = matches ? consecutiveReady + 1 : 0
108 if (consecutiveReady >= 3) { ready = true; break }
109 } catch {
110 consecutiveReady = 0
111 readinessProbes.push({ status: 'network-error', matches: false, elapsedMs: Math.round(performance.now() - readinessStarted) })
112 }
113 await new Promise((resolve) => setTimeout(resolve, 1000))
114}
115await mkdir('qualification-results', { recursive: true })
116await writeFile(`qualification-results/function-readiness-${branchId}-${deploymentId}.json`, JSON.stringify({
117 branchId, deploymentId, bundleSha256: hash, ready, consecutiveReady, durationMs: Math.round(performance.now() - readinessStarted), probes: readinessProbes,
118}, null, 2) + '\n')
119if (!ready) throw new Error('Deployed Function failed its authenticated runtime health check')
120console.log(`Deployed and verified the current bundle on test branch ${branchId}.`)