Open History to see the last commit
1import { createHash, randomBytes, randomUUID } from 'node:crypto'
2import { execFileSync } from 'node:child_process'
3import { readFile, writeFile } from 'node:fs/promises'
4import { build } from 'esbuild'
5import { zipSync } from 'fflate'
6import { createNeonClient } from '@neon/sdk'
7import pg from 'pg'
8import { migrate } from '../dist/migrations.js'
9import { createS3ChunkStorage } from '../dist/s3.js'
10import { initializeSubscriptions, parseSubscriptionKeyring } from '../dist/subscriptions.js'
11
12const env = process.env
13const stateFile = env.NEON_TEST_STATE_FILE ?? '.neon-test-state-replay.json'
14const outputFile = env.NEON_TEST_FUNCTION_ENV_FILE ?? '.env.neon.replay.function'
15const state = JSON.parse(await readFile(stateFile, 'utf8'))
16if (!env.NEON_API_KEY || !env.NEON_PROJECT_ID || !env.NEON_TEST_BRANCH_ID || !env.TEST_DATABASE_URL_UNPOOLED
17 || state.projectId !== env.NEON_PROJECT_ID || state.branchId !== env.NEON_TEST_BRANCH_ID || !state.name.startsWith('ds-test-')) throw new Error('Recorded isolated replay branch required')
18const neon = createNeonClient({ apiKey: env.NEON_API_KEY, throwOnError: true })
19if ((await neon.branches.get({ projectId: state.projectId, branchId: state.branchId })).name !== state.name) throw new Error('Replay branch identity changed')
20const sourcePaths = ['src', 'migrations', 'package.json', 'pnpm-lock.yaml', 'test/fixtures/replay-function.mjs', 'test/fixtures/replay-data.mjs', 'scripts/neon-test-replay.mjs', 'scripts/qualify-replay.mjs']
21const git = (...args) => execFileSync('git', args, { encoding: 'utf8' }).trim()
22if (git('status', '--porcelain', '--untracked-files=all', '--', ...sourcePaths)) throw new Error('Commit replay source before deployment')
23const sourceCommit = git('rev-parse', 'HEAD')
24const integer = (name, fallback, min, max) => {
25 const value = Number(env[name] ?? fallback)
26 if (!Number.isSafeInteger(value) || value < min || value > max) throw new RangeError(`Invalid ${name}`)
27 return value
28}
29const settings = { targetChunkBytes: integer('REPLAY_CHUNK_BYTES', 4 * 1024 * 1024, 1, 16 * 1024 * 1024),
30 maxChunkFrames: integer('REPLAY_CHUNK_FRAMES', 8192, 1, 131072), blockBytes: integer('REPLAY_BLOCK_BYTES', 65536, 4096, 16 * 1024 * 1024),
31 cacheBytes: integer('REPLAY_CACHE_BYTES', 32 * 1024 * 1024, 0, 256 * 1024 * 1024), readAhead: integer('REPLAY_READ_AHEAD', 0, 0, 1), firstBlockProbe: true }
32let previous
33try { previous = Object.fromEntries((await readFile(outputFile, 'utf8')).trim().split('\n').map((line) => { const index = line.indexOf('='); return [line.slice(0, index), line.slice(index + 1)] })) }
34catch (error) { if (error.code !== 'ENOENT') throw error }
35if (previous && previous.TEST_FUNCTION_BRANCH_ID !== state.branchId) throw new Error('Replay environment belongs to another branch')
36const schema = previous?.TEST_FUNCTION_SCHEMA ?? `ds_test_${randomUUID().replaceAll('-', '')}`
37const token = previous?.TEST_FUNCTION_API_KEY ?? randomBytes(32).toString('hex')
38const objects = createS3ChunkStorage({ endpoint: env.AWS_ENDPOINT_URL_S3, region: env.AWS_REGION, bucket: env.NEON_TEST_BUCKET })
39const direct = new pg.Pool({ connectionString: env.TEST_DATABASE_URL_UNPOOLED, max: 1 })
40try {
41 await migrate(direct, { schema, storageIdentity: objects.identity, environmentId: state.branchId })
42 await initializeSubscriptions(direct, { schema, keyring: parseSubscriptionKeyring(env.DURABLE_STREAMS_KEYRING) })
43} finally { await direct.end(); objects.close() }
44const bundled = await build({ entryPoints: ['test/fixtures/replay-function.mjs'], bundle: true, platform: 'node', target: 'node24', format: 'esm', write: false,
45 external: ['pg-native', 'bufferutil', 'utf-8-validate'],
46 banner: { js: 'import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);' } })
47if (bundled.outputFiles.length !== 1) throw new Error('Expected one replay bundle')
48const code = bundled.outputFiles[0].contents
49const bundleSha256 = createHash('sha256').update(code).digest('hex')
50const slug = env.REPLAY_FUNCTION_SLUG ?? 'replaybench'
51if (!/^replay[a-z0-9-]{1,24}$/.test(slug)) throw new Error('Invalid replay Function slug')
52const deployed = await neon.functions.deploy({ projectId: state.projectId, branchId: state.branchId, slug, runtime: 'nodejs24',
53 zip: new File([zipSync({ 'index.mjs': code })], 'replay.zip', { type: 'application/zip' }),
54 environment: JSON.stringify({ DS_SCHEMA: schema, DS_ENVIRONMENT_ID: state.branchId, DS_BUCKET: env.NEON_TEST_BUCKET,
55 DS_REALTIME_URL: env.NEON_REALTIME_URL, DS_REALTIME_SECRET: env.NEON_REALTIME_SECRET, DS_KEYRING_JSON: env.DURABLE_STREAMS_KEYRING,
56 DS_BENCHMARK_KEY: `Bearer ${token}`, DS_BUILD_HASH: bundleSha256, DS_SOURCE_COMMIT: sourceCommit, DS_BENCHMARK_SETTINGS: JSON.stringify(settings) }) })
57const deadline = Date.now() + 180000
58let url, ready = false
59while (Date.now() < deadline) {
60 const fn = await neon.functions.get({ projectId: state.projectId, branchId: state.branchId, slug })
61 if (fn.current_deployment?.id === deployed.id && fn.current_deployment.status === 'failed') throw new Error('Replay Function deployment failed')
62 if (fn.active_deployment?.id === deployed.id && fn.invocation_url) {
63 url = fn.invocation_url
64 try {
65 const response = await fetch(new URL('_benchmark/health', url), { headers: { Authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(10000) })
66 const health = await response.json()
67 if (health.ready && health.build === bundleSha256 && health.sourceCommit === sourceCommit) { ready = true; break }
68 } catch { /* The deployment may precede runtime readiness. */ }
69 }
70 await new Promise((resolve) => setTimeout(resolve, 1000))
71}
72if (!ready) throw new Error('Replay Function readiness deadline exceeded')
73await writeFile(outputFile, Object.entries({ TEST_FUNCTION_URL: url, TEST_FUNCTION_API_KEY: token, TEST_FUNCTION_BRANCH_ID: state.branchId,
74 TEST_FUNCTION_SCHEMA: schema, TEST_FUNCTION_BUNDLE_SHA: bundleSha256, TEST_FUNCTION_SOURCE_COMMIT: sourceCommit,
75 TEST_FUNCTION_DEPLOYMENT_ID: deployed.id, REPLAY_SETTINGS: JSON.stringify(settings) }).map(([name, value]) => `${name}=${value}`).join('\n') + '\n', { mode: 0o600 })
76console.log(JSON.stringify({ ready, branchId: state.branchId, schema, sourceCommit, bundleSha256, settings }))