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

neon-conformance-artifact.mjs

93 lines7.4 KB

1import { createHash } from 'node:crypto'
2import { execFile } from 'node:child_process'
3import { cp, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rm, writeFile } from 'node:fs/promises'
4import { tmpdir } from 'node:os'
5import { dirname, join, relative, resolve, sep } from 'node:path'
6import { promisify } from 'node:util'
7import { zipSync } from 'fflate'
8​
9// Build without management or data credentials. Ship the actual unchanged
10// Vitest fixture, upstream package, and frozen dependency graph to Node 24.
11export async function buildConformanceArtifact(profile = 'conformance') {
12 if (!['conformance', 'neon', 'integration'].includes(profile)) throw new Error('Unknown colocated qualification profile')
13 const root = resolve(import.meta.dirname, '..')
14 const directory = await realpath(await mkdtemp(join(tmpdir(), 'ds-conformance-build-')))
15 const run = promisify(execFile)
16 const buildEnv = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/SECRET|TOKEN|PASSWORD|KEY|DATABASE|^NEON_|^AWS_|^TEST_|^DURABLE_|^NODE_OPTIONS$/.test(key)))
17 const sourcePaths = ['src', 'migrations', 'test/fixtures/postgres-limits.ts', 'vitest.config.ts', 'package.json', 'pnpm-lock.yaml', 'tsconfig.json', 'LICENSE', 'NOTICE',
18 ...(profile === 'conformance' ? ['test/conformance'] : [`test/${profile}`, 'test/fixtures', 'dist'])]
19 if (profile !== 'conformance') await run('pnpm', ['build'], { cwd: root, env: buildEnv, timeout: 120_000, maxBuffer: 8 * 1024 * 1024 })
20 try {
21 for (const path of sourcePaths) { await mkdir(dirname(join(directory, path)), { recursive: true }); await cp(join(root, path), join(directory, path), { recursive: true }) }
22 // Reject a different runtime rather than use the build host's native code.
23 await writeFile(join(directory, 'pnpm-workspace.yaml'), 'supportedArchitectures:\n os: [linux]\n cpu: [arm64, wasm32]\n libc: [glibc]\n')
24 await run('pnpm', ['install', '--frozen-lockfile', '--ignore-scripts', '--prefer-offline'], {
25 cwd: directory, env: buildEnv, timeout: 240_000, maxBuffer: 8 * 1024 * 1024,
26 })
27 const files = {}, links = {}, executable = [], included = new Set()
28 async function include(path) {
29 const absolute = join(directory, path), stat = await lstat(absolute)
30 if (stat.isSymbolicLink()) {
31 const target = relative(directory, await realpath(absolute))
32 if (target.startsWith(`..${sep}`) || target === '..') throw new Error('Dependency symlink escaped artifact')
33 links[path] = relative(dirname(path), target)
34 await include(target)
35 } else if (stat.isDirectory()) {
36 for (const entry of (await readdir(absolute)).sort()) if (entry !== 'node_modules') await include(join(path, entry))
37 } else if (stat.isFile()) { files[path] = new Uint8Array(await readFile(absolute)); if (stat.mode & 0o111) executable.push(path) }
38 }
39 async function dependency(name, from, optional = false) {
40 // The native Rolldown addon exceeds the executable source-size budget.
41 // Its locked WASI variant changes only the compiler, never test clocks.
42 if (name.startsWith('@rolldown/binding-') && name !== '@rolldown/binding-wasm32-wasi') return
43 if (name.endsWith('-musl')) return
44 let parent = from
45 for (;;) {
46 const candidate = join(parent, 'node_modules', name)
47 let actual
48 try { actual = await realpath(candidate) } catch (error) { if (error.code !== 'ENOENT') throw error }
49 if (actual) {
50 if (candidate !== actual) links[relative(directory, candidate)] = relative(dirname(candidate), actual)
51 if (included.has(actual)) return
52 included.add(actual)
53 await include(relative(directory, actual))
54 const pkg = JSON.parse(await readFile(join(actual, 'package.json'), 'utf8'))
55 for (const child of Object.keys(pkg.dependencies ?? {})) await dependency(child, actual)
56 for (const child of new Set([...Object.keys(pkg.optionalDependencies ?? {}), ...Object.keys(pkg.peerDependencies ?? {})])) await dependency(child, actual, true)
57 return
58 }
59 const next = dirname(parent)
60 if (parent === directory || next === parent || !parent.startsWith(directory)) break
61 parent = next
62 }
63 if (!optional) throw new Error(`Missing frozen dependency ${name}`)
64 }
65 for (const path of sourcePaths) await include(path)
66 for (const name of ['vitest', 'pg', '@durable-streams/server-conformance-tests', '@aws-sdk/client-s3', '@neon/realtime', 'ws', 'ipaddr.js', ...(profile !== 'conformance' ? ['fast-check'] : [])]) await dependency(name, directory)
67 if (![...included].some((path) => path.endsWith('/@rolldown/binding-wasm32-wasi'))) throw new Error('Frozen WASI test compiler missing')
68 const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex')
69 const native = {}, nativeFiles = {}
70 // /tmp is writable but noexec on Functions. ELF executables and native
71 // addons must be deployed on the executable code mount, not unpacked there.
72 for (const [path, bytes] of Object.entries(files)) if (bytes[0] === 0x7f && bytes[1] === 0x45 && bytes[2] === 0x4c && bytes[3] === 0x46) {
73 const name = `native/${sha256(bytes)}.${path.endsWith('.node') ? 'node' : 'bin'}`
74 native[path] = name; nativeFiles[name] = [bytes, { os: 3, attrs: 0o100755 << 16 }]; delete files[path]
75 }
76 files['.artifact-links.json'] = new TextEncoder().encode(JSON.stringify(links))
77 files['.artifact-executable.json'] = new TextEncoder().encode(JSON.stringify(executable.filter((path) => !native[path])))
78 files['.artifact-native.json'] = new TextEncoder().encode(JSON.stringify(native))
79 const payload = zipSync(files, { level: 6 })
80 const sourceHash = createHash('sha256')
81 for (const path of Object.keys(files).filter((path) => !path.startsWith('node_modules/')).sort()) sourceHash.update(path).update('\0').update(files[path]).update('\0')
82 const { stdout: commit } = await run('git', ['rev-parse', 'HEAD'], { cwd: root, env: buildEnv })
83 const { stdout: dirty } = await run('git', ['status', '--porcelain', '--untracked-files=all', '--', ...sourcePaths, 'scripts/neon-conformance-artifact.mjs', 'scripts/neon-test-conformance.mjs', 'test/fixtures/conformance-function.mjs'], { cwd: root, env: buildEnv })
84 const upstream = await readFile(join(directory, 'node_modules/@durable-streams/server-conformance-tests/dist/index.js'))
85 return { payload, nativeFiles, manifest: { target: 'linux/arm64/glibc', testCompiler: 'rolldown-wasi', nativeFiles: Object.keys(nativeFiles), sourceCommit: commit.trim(), sourceDirty: Boolean(dirty.trim()), sourceSnapshotSha256: sourceHash.digest('hex'),
86 payloadSha256: sha256(payload), payloadBytes: payload.length, expandedBytes: Object.values(files).reduce((sum, bytes) => sum + bytes.length, 0),
87 lockSha256: sha256(files['pnpm-lock.yaml']), fixtureSha256: profile === 'conformance' ? sha256(files['test/conformance/server.test.ts']) : undefined,
88 upstreamVersion: '0.3.7', upstreamSha256: sha256(upstream), subscriptions: true,
89 reclamation: { enabled: true, recovery: 'provider-owned' }, profile, expectedTests: profile === 'conformance' ? 338 : undefined,
90 expectedFiles: Object.keys(files).filter((path) => path.startsWith(`test/${profile}/`) && path.endsWith('.test.ts') && (profile !== 'neon' || path !== 'test/neon/rolling.test.ts')).sort(),
91 separatelyQualified: profile === 'neon' ? ['test/neon/rolling.test.ts'] : [] } }
92 } finally { await rm(directory, { recursive: true, force: true }) }