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

conformance-function.mjs

144 lines9.6 KB

1// Test-only coordinator. Never included in the package or consumer example.
2import { spawn } from 'node:child_process'
3import { createHash, timingSafeEqual } from 'node:crypto'
4import { chmod, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises'
5import { tmpdir } from 'node:os'
6import { dirname, join, resolve } from 'node:path'
7import { fileURLToPath } from 'node:url'
8import { unzipSync } from 'fflate'
9import { GetObjectCommand, S3Client } from '@aws-sdk/client-s3'
10​
11const key = process.env.DS_CONFORMANCE_KEY
12const digest = process.env.DS_CONFORMANCE_PAYLOAD_SHA
13const profile = process.env.DS_QUALIFICATION_PROFILE ?? 'conformance'
14if (!['conformance', 'neon', 'integration'].includes(profile)) throw new Error('Unknown qualification profile')
15const expectedFiles = JSON.parse(process.env.DS_QUALIFICATION_FILES ?? '["test/conformance/server.test.ts"]')
16if (!key || !digest) throw new Error('Isolated conformance credentials required')
17const sensitive = Object.entries(process.env).filter(([name, value]) => /SECRET|TOKEN|KEY|PASSWORD|DATABASE_URL/.test(name) && value?.length >= 8).map(([, value]) => value)
18if (process.env.DURABLE_STREAMS_KEYRING) sensitive.push(...Object.values(JSON.parse(process.env.DURABLE_STREAMS_KEYRING).keys))
19function redact(value) {
20 let text = String(value)
21 for (const secret of sensitive) text = text.replaceAll(secret, '[redacted]')
22 return text.replace(/postgres(?:ql)?:\/\/[^\s'"<>]+/g, '[database URL]').replace(/dsw\.2\.[A-Za-z0-9_-]{1,128}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{43}|dsw\.[0-9a-f-]{36}\.[A-Za-z0-9_-]{43}/gi, '[wake token]')
24function authorized(request) {
25 const supplied = Buffer.from(request.headers.get('authorization') ?? '')
26 const expected = Buffer.from(`Bearer ${key}`)
27 return supplied.length === expected.length && timingSafeEqual(supplied, expected)
29let busy = false
30let active
31let forceStop
32function stop() {
33 if (!active?.pid) return
34 const pid = active.pid
35 const kill = (signal) => { try { process.kill(-pid, signal) } catch (error) { if (error.code !== 'ESRCH') throw error } }
36 kill('SIGTERM')
37 forceStop ??= setTimeout(() => kill('SIGKILL'), 5000).unref()
39process.once('SIGINT', stop)
40export default {
41 async fetch(request) {
42 if (!authorized(request)) return new Response(null, { status: 401 })
43 if (request.method === 'GET') return Response.json({ ready: true, payloadSha256: digest, profile, node: process.version, arch: process.arch, platform: process.platform,
44 glibc: process.report.getReport().header.glibcVersionRuntime ?? null })
45 if (request.method !== 'POST') return new Response(null, { status: 405 })
46 if (busy) return new Response(null, { status: 409 })
47 busy = true
48 let cancel
49 const body = new ReadableStream({
50 start(controller) {
51 let disconnected = false, logBytes = 0
52 const encoder = new TextEncoder()
53 const emit = (event) => { if (!disconnected) controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`)) }
54 const abort = () => { disconnected = true; stop() }
55 cancel = abort
56 request.signal.addEventListener('abort', abort, { once: true })
57 const heartbeat = setInterval(() => emit({ type: 'heartbeat' }), 10_000)
58 const deadline = setTimeout(stop, 20 * 60_000)
59 const task = async () => {
60 let directory
61 try {
62 emit({ type: 'started', node: process.version, arch: process.arch, platform: process.platform })
63 const s3 = new S3Client({ endpoint: process.env.AWS_ENDPOINT_URL_S3, region: process.env.AWS_REGION, forcePathStyle: true,
64 requestChecksumCalculation: 'WHEN_REQUIRED', responseChecksumValidation: 'WHEN_REQUIRED' })
65 let payload
66 try {
67 const object = await s3.send(new GetObjectCommand({ Bucket: process.env.NEON_TEST_BUCKET, Key: process.env.DS_CONFORMANCE_PAYLOAD_KEY }), { abortSignal: AbortSignal.timeout(120_000) })
68 if (!object.Body || object.ContentLength !== Number(process.env.DS_CONFORMANCE_PAYLOAD_BYTES)) throw new Error('Invalid conformance artifact size')
69 payload = await object.Body.transformToByteArray()
70 } finally { s3.destroy() }
71 if (createHash('sha256').update(payload).digest('hex') !== digest) throw new Error('Conformance artifact hash mismatch')
72 directory = await mkdtemp(join(tmpdir(), 'ds-conformance-'))
73 const entries = unzipSync(payload)
74 const safe = (path) => { const result = resolve(directory, path); if (!result.startsWith(`${directory}/`)) throw new Error('Invalid artifact path'); return result }
75 for (const [path, bytes] of Object.entries(entries)) {
76 const target = safe(path); await mkdir(dirname(target), { recursive: true }); await writeFile(target, bytes)
77 }
78 for (const path of JSON.parse(new TextDecoder().decode(entries['.artifact-executable.json']))) await chmod(safe(path), 0o755)
79 for (const [path, target] of Object.entries(JSON.parse(new TextDecoder().decode(entries['.artifact-links.json'])))) {
80 const link = safe(path); safe(join(dirname(path), target)); await mkdir(dirname(link), { recursive: true }); await symlink(target, link)
81 }
82 const nativeFiles = JSON.parse(new TextDecoder().decode(entries['.artifact-native.json']))
83 for (const [path, target] of Object.entries(nativeFiles)) {
84 if (!/^native\/[a-f0-9]{64}\.(node|bin)$/.test(target)) throw new Error('Invalid native artifact path')
85 const deployed = fileURLToPath(new URL(`./${target}`, import.meta.url))
86 if (createHash('sha256').update(await readFile(deployed)).digest('hex') !== target.split('/')[1].split('.')[0]) throw new Error('Native artifact hash mismatch')
87 const link = safe(path); await mkdir(dirname(link), { recursive: true }); await symlink(deployed, link)
88 }
89 if (disconnected) return
90 const started = performance.now()
91 // Conformance remains the full unfiltered pinned suite. The Neon
92 // data profile runs every real-service fixture except the control-
93 // plane packed consumer fixture, which is qualified separately.
94 // No management credentials enter this deployed coordinator.
95 const args = ['node_modules/vitest/vitest.mjs', 'run', '--project', profile, '--reporter=default', '--reporter=json', '--outputFile=conformance-results.json']
96 if (profile === 'neon') args.push('--exclude=test/neon/rolling.test.ts')
97 const child = spawn(process.execPath, args, {
98 cwd: directory, env: { ...process.env, NODE_OPTIONS: '', CI: 'true', NO_COLOR: '1', NAPI_RS_FORCE_WASI: 'error' }, stdio: ['ignore', 'pipe', 'pipe'], detached: true,
99 })
100 active = child
101 // Redact complete lines, so a credential split between transport
102 // chunks cannot bypass redaction. Oversized logs are dropped.
103 for (const stream of [child.stdout, child.stderr]) {
104 let pending = ''
105 stream.setEncoding('utf8')
106 stream.on('data', (text) => {
107 logBytes += Buffer.byteLength(text)
108 if (logBytes > 1024 * 1024) { pending = ''; return }
109 pending += text
110 const newline = pending.lastIndexOf('\n')
111 if (newline >= 0) { emit({ type: 'log', text: redact(pending.slice(0, newline + 1)) }); pending = pending.slice(newline + 1) }
112 })
113 stream.on('end', () => { if (pending) emit({ type: 'log', text: redact(pending) }) })
114 }
115 const result = await new Promise((resolve, reject) => { child.once('error', reject); child.once('close', (code, signal) => resolve({ code, signal })) })
116 active = undefined
117 const raw = await readFile(join(directory, 'conformance-results.json'), 'utf8')
118 if (raw.length > 8 * 1024 * 1024) throw new Error('Conformance report exceeds bound')
119 const sanitize = (value) => typeof value === 'string' ? redact(value) : Array.isArray(value) ? value.map(sanitize)
120 : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).map(([name, field]) => [name, sanitize(field)])) : value
121 const report = sanitize(JSON.parse(raw))
122 const actualFiles = report.testResults.map((item) => item.name.slice(directory.length + 1)).sort()
123 const passed = result.code === 0 && report.success === true && report.numTotalTests > 0
124 && report.numPassedTests === report.numTotalTests && report.numFailedTests === 0 && report.numPendingTests === 0 && report.numTodoTests === 0
125 && JSON.stringify(actualFiles) === JSON.stringify(expectedFiles)
126 && (profile !== 'conformance' || report.numTotalTests === 338)
127 emit({ type: 'result', passed, ...result, durationMs: Math.round(performance.now() - started), report })
128 } catch (error) { emit({ type: 'error', message: redact(error?.stack ?? error) }) }
129 finally {
130 try { if (directory) await rm(directory, { recursive: true, force: true }) }
131 catch (error) { emit({ type: 'error', message: `Coordinator cleanup failed: ${redact(error.message)}` }) }
132 clearInterval(heartbeat); clearTimeout(deadline); request.signal.removeEventListener('abort', abort)
133 clearTimeout(forceStop); forceStop = undefined
134 busy = false
135 if (!disconnected) controller.close()
136 }
137 }
138 void task()
139 },
140 cancel() { cancel?.() },
141 })
142 return new Response(body, { headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store' } })
143 },