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

neon-test-conformance.mjs

122 lines8.8 KB

1import { createHash, randomBytes } from 'node:crypto'
2import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'
3import { build } from 'esbuild'
4import { zipSync } from 'fflate'
5import { createNeonClient } from '@neon/sdk'
6import { DeleteObjectCommand, PutObjectCommand, S3Client } from '@aws-sdk/client-s3'
7import { buildConformanceArtifact } from './neon-conformance-artifact.mjs'
8​
9const env = process.env, profile = env.NEON_QUALIFICATION_PROFILE ?? 'conformance'
10if (!['conformance', 'neon', 'integration'].includes(profile)) throw new Error('Unknown colocated qualification profile')
11const slug = { conformance: 'dsconformance', neon: 'dsregression', integration: 'dstransactions' }[profile]
12const resultFile = profile === 'conformance' ? 'conformance-results.json' : `qualification-results/colocated-${profile}-results.json`
13const evidenceFile = profile === 'conformance' ? 'qualification-results/colocated-conformance.json' : `qualification-results/colocated-${profile}.json`
14const projectId = env.NEON_PROJECT_ID, branchId = env.NEON_TEST_BRANCH_ID
15if (!projectId || !branchId || !env.NEON_API_KEY) throw new Error('Recorded isolated Neon environment required')
16const state = JSON.parse(await readFile(env.NEON_TEST_STATE_FILE ?? '.neon-test-state.json', 'utf8'))
17if (state.projectId !== projectId || state.branchId !== branchId || !state.name.startsWith('ds-test-')) throw new Error('Unrecognized conformance branch')
18const neon = createNeonClient({ apiKey: env.NEON_API_KEY, throwOnError: true })
19const branch = await neon.branches.get({ projectId, branchId })
20if (branch.name !== state.name || branch.default || branch.protected) throw new Error('Conformance must run on the recorded disposable branch')
21const runtimeEnv = {}
22for (const name of ['TEST_DATABASE_URL', 'TEST_DATABASE_URL_UNPOOLED', 'NEON_REALTIME_URL', 'NEON_REALTIME_SECRET', 'AWS_ENDPOINT_URL_S3', 'AWS_REGION', 'AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'NEON_TEST_BUCKET', 'DURABLE_STREAMS_KEYRING']) {
23 if (!env[name]) throw new Error(`Missing conformance environment: ${name}`)
24 runtimeEnv[name] = env[name]
26// No management API key or caller-controlled script enters the Function.
27await rm(resultFile, { force: true })
28const key = randomBytes(32).toString('hex')
29if (env.GITHUB_ACTIONS === 'true') console.log(`::add-mask::${key}`)
30const { payload, nativeFiles, manifest } = await buildConformanceArtifact(profile)
31console.log(`Built unchanged suite artifact (${manifest.payloadBytes} compressed bytes).`)
32const bundle = await build({ entryPoints: ['test/fixtures/conformance-function.mjs'], bundle: true, platform: 'node', target: 'node24', format: 'esm', write: false,
33 banner: { js: 'import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);' } })
34const code = bundle.outputFiles[0].contents
35manifest.launcherSha256 = createHash('sha256').update(code).digest('hex')
36const deploymentZip = zipSync({ 'index.mjs': code, ...nativeFiles })
37if (deploymentZip.length > 32 * 1024 * 1024) throw new Error('Native conformance deployment exceeds the Neon upload limit')
38manifest.deploymentZipSha256 = createHash('sha256').update(deploymentZip).digest('hex')
39manifest.deploymentZipBytes = deploymentZip.length
40manifest.generatedAt = new Date().toISOString()
41await mkdir('qualification-results', { recursive: true })
42const evidence = { ...manifest, passed: false }
43const artifactKey = `qualification/conformance/${manifest.payloadSha256}.zip`
44const s3 = new S3Client({ endpoint: env.AWS_ENDPOINT_URL_S3, region: env.AWS_REGION, forcePathStyle: true,
45 requestChecksumCalculation: 'WHEN_REQUIRED', responseChecksumValidation: 'WHEN_REQUIRED' })
46let attempted = false
47try {
48 // Functions has a 32 MiB compressed deployment cap. Store the larger locked
49 // test graph privately on this disposable branch; the launcher pins its hash.
50 await s3.send(new PutObjectCommand({ Bucket: env.NEON_TEST_BUCKET, Key: artifactKey, Body: payload }), { abortSignal: AbortSignal.timeout(120_000) })
51 // The branch ledger predates deployment; whole-branch cleanup and the CI
52 // janitor cover runner loss, including an ambiguous deploy response.
53 attempted = true
54 const deployment = await neon.functions.deploy({ projectId, branchId, slug, runtime: 'nodejs24',
55 zip: new File([deploymentZip], 'conformance.zip', { type: 'application/zip' }),
56 environment: JSON.stringify({ ...runtimeEnv, DS_CONFORMANCE_KEY: key, DS_CONFORMANCE_PAYLOAD_SHA: manifest.payloadSha256,
57 DS_CONFORMANCE_PAYLOAD_KEY: artifactKey, DS_CONFORMANCE_PAYLOAD_BYTES: String(payload.length),
58 DS_QUALIFICATION_PROFILE: profile, DS_QUALIFICATION_FILES: JSON.stringify(manifest.expectedFiles) }),
59 })
60 const deadline = Date.now() + 180_000
61 let url, runtime
62 while (Date.now() < deadline) {
63 const fn = await neon.functions.get({ projectId, branchId, slug })
64 if (fn.current_deployment?.id === deployment.id && fn.current_deployment.status === 'failed') {
65 evidence.deploymentError = fn.current_deployment.error
66 throw new Error(`Conformance Function deployment failed: ${fn.current_deployment.error ?? 'unknown build failure'}`)
67 }
68 if (fn.active_deployment?.id === deployment.id && fn.invocation_url) {
69 try {
70 const response = await fetch(fn.invocation_url, { headers: { Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(10_000) })
71 if (response.ok) { const health = await response.json(); if (health.ready === true && health.payloadSha256 === manifest.payloadSha256 && health.profile === profile) { url = fn.invocation_url; runtime = health; break } }
72 else await response.arrayBuffer()
73 } catch { /* Deployment and cold start readiness are distinct. */ }
74 }
75 await new Promise((resolve) => setTimeout(resolve, 1000))
76 }
77 if (!url) throw new Error('Conformance Function did not become ready')
78 evidence.runtime = runtime
79 if (`${runtime.platform}/${runtime.arch}/${runtime.glibc ? 'glibc' : 'musl'}` !== manifest.target) throw new Error('Conformance artifact does not support this Function architecture')
80 console.log(`Running ${profile === 'conformance' ? 'all 338 upstream cases' : `all ${manifest.expectedFiles.length} ${profile} data fixtures`} on Neon ${runtime.platform}/${runtime.arch}, ${runtime.node}.`)
81 const response = await fetch(url, { method: 'POST', headers: { Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(25 * 60_000) })
82 if (!response.ok || !response.body) throw new Error(`Conformance coordinator returned HTTP ${response.status}`)
83 let pending = '', result
84 const decoder = new TextDecoder()
85 for await (const chunk of response.body) {
86 pending += decoder.decode(chunk, { stream: true })
87 if (pending.length > 12 * 1024 * 1024) throw new Error('Conformance event exceeds bound')
88 let newline
89 while ((newline = pending.indexOf('\n')) >= 0) {
90 const line = pending.slice(0, newline); pending = pending.slice(newline + 1)
91 if (!line) continue
92 if (!line.startsWith('data: ')) throw new Error('Malformed conformance event')
93 const event = JSON.parse(line.slice(6))
94 if (event.type === 'log') process.stdout.write(event.text)
95 else if (event.type === 'heartbeat') console.log('Neon conformance still running.')
96 else if (event.type === 'error') throw new Error(event.message)
97 else if (event.type === 'result') {
98 if (result) throw new Error('Duplicate conformance result')
99 result = event
100 // Retain all upstream results even if later stream/cleanup fails.
101 await writeFile(resultFile, JSON.stringify(result.report) + '\n')
102 }
103 }
104 }
105 if (pending.trim() || !result) throw new Error('Conformance stream ended without a complete result')
106 Object.assign(evidence, { passed: result.passed === true, exitCode: result.code, signal: result.signal, durationMs: result.durationMs,
107 total: result.report.numTotalTests, passedTests: result.report.numPassedTests, failedTests: result.report.numFailedTests, skippedTests: result.report.numPendingTests })
108 if (!evidence.passed) throw new Error(`Colocated ${profile} failed: ${evidence.passedTests}/${evidence.total}`)
109 console.log(`Colocated ${profile} passed: ${evidence.passedTests}/${evidence.total}, no failures or skips.`)
110} finally {
111 // Save a failed report on interrupted/ambiguous runs; successful cleanup is
112 // part of qualification, as with the multi-instance suite.
113 try {
114 if (attempted) {
115 try { await neon.functions.delete({ projectId, branchId, slug }) }
116 catch (error) { if (error.status !== 404) throw error }
117 }
118 await s3.send(new DeleteObjectCommand({ Bucket: env.NEON_TEST_BUCKET, Key: artifactKey }), { abortSignal: AbortSignal.timeout(30_000) })
119 evidence.cleanupComplete = true
120 } catch (error) { evidence.passed = false; throw error }
121 finally { s3.destroy(); await writeFile(evidenceFile, JSON.stringify(evidence, null, 2) + '\n') }