Open History to see the last commit
1import { createNeonClient } from '@neon/sdk'
2import { randomBytes } from 'node:crypto'
3import { appendFile, open, readFile, unlink, writeFile } from 'node:fs/promises'
4
5// No application imports: this is a trusted CI/development control-plane tool.
6const apiKey = process.env.NEON_API_KEY
7const projectId = process.env.NEON_PROJECT_ID
8if (!apiKey || !projectId) throw new Error('NEON_API_KEY and NEON_PROJECT_ID are required; Neon qualification cannot be skipped')
9const neon = createNeonClient({ apiKey, throwOnError: true, waitForReadiness: true, wait: { timeoutMs: 180_000 } })
10const stateFile = process.env.NEON_TEST_STATE_FILE ?? '.neon-test-state.json'
11const outputFile = process.env.NEON_TEST_ENV_FILE ?? '.env.neon.test'
12const operation = process.argv[2] ?? 'create'
13const escape = (value) => value.replaceAll('%', '%25').replaceAll('\r', '%0D').replaceAll('\n', '%0A')
14const mask = (value) => { if (process.env.GITHUB_ACTIONS === 'true') console.log(`::add-mask::${escape(value)}`) }
15
16async function storageEnvironment(branchId) {
17 const bucket = 'durable-streams-test'
18 const existing = (await neon.storage.buckets.list({ projectId, branchId })).find((item) => item.name === bucket)
19 if (existing && existing.access_level !== 'private') throw new Error('Test chunk bucket must be private')
20 if (!existing) await neon.storage.buckets.create({ projectId, branchId, name: bucket, access_level: 'private' })
21 const storage = await neon.storage.get({ projectId, branchId })
22 if (!storage.enabled || !storage.force_path_style) throw new Error('Neon Object Storage is not ready')
23 const credential = await neon.credentials.create({ projectId, branchId, name: 'durable-streams-qualification', principal_type: 'user',
24 scopes: ['storage:read', 'storage:write'], expires_at: new Date(Date.now() + 24 * 3600_000).toISOString() })
25 return { AWS_ENDPOINT_URL_S3: storage.s3_endpoint, AWS_REGION: storage.region,
26 AWS_ACCESS_KEY_ID: credential.token_id, AWS_SECRET_ACCESS_KEY: credential.s3_secret_access_key, NEON_TEST_BUCKET: bucket }
27}
28async function output(values, append = false) {
29 for (const value of Object.values(values)) mask(value)
30 if (values.DURABLE_STREAMS_KEYRING) for (const value of Object.values(JSON.parse(values.DURABLE_STREAMS_KEYRING).keys)) mask(value)
31 const environment = Object.entries(values).map(([k, v]) => `${k}=${v}`).join('\n') + '\n'
32 if (process.env.GITHUB_ENV) await appendFile(process.env.GITHUB_ENV, environment)
33 else if (append) await appendFile(outputFile, environment, { mode: 0o600 })
34 else await writeFile(outputFile, environment, { mode: 0o600, flag: 'wx' })
35}
36
37if (operation === 'delete') {
38 let state
39 try { state = JSON.parse(await readFile(stateFile, 'utf8')) } catch (error) {
40 if (error.code === 'ENOENT') { console.log('No branch was provisioned.'); process.exit(0) }
41 throw error
42 }
43 if (state.projectId !== projectId || !state.name.startsWith('ds-test-')) throw new Error('Refusing cleanup outside the recorded test installation')
44 await neon.branches.delete({ projectId, branchId: state.branchId })
45 try {
46 const environment = await readFile(outputFile, 'utf8')
47 if (environment.split('\n').includes(`NEON_TEST_BRANCH_ID=${state.branchId}`)) await unlink(outputFile)
48 } catch (error) { if (error.code !== 'ENOENT') throw error }
49 const functionFile = process.env.NEON_TEST_FUNCTION_ENV_FILE ?? '.env.neon.function'
50 try {
51 const environment = await readFile(functionFile, 'utf8')
52 if (environment.split('\n').includes(`TEST_FUNCTION_BRANCH_ID=${state.branchId}`)) await unlink(functionFile)
53 } catch (error) { if (error.code !== 'ENOENT') throw error }
54 await unlink(stateFile)
55 console.log(`Deleted test branch ${state.branchId}.`)
56} else if (operation === 'storage') {
57 const state = JSON.parse(await readFile(stateFile, 'utf8'))
58 if (state.projectId !== projectId || !state.name.startsWith('ds-test-')) throw new Error('Storage provisioning requires this run\'s test branch')
59 const environment = await readFile(outputFile, 'utf8')
60 if (!environment.split('\n').includes(`NEON_TEST_BRANCH_ID=${state.branchId}`) || environment.includes('AWS_ACCESS_KEY_ID=')) throw new Error('Refusing to overwrite a storage environment')
61 await output(await storageEnvironment(state.branchId), true)
62 console.log('Private Neon Object Storage bucket ready; credentials saved without logging them.')
63} else if (operation === 'create') {
64 const suffix = process.env.GITHUB_RUN_ID ? `${process.env.GITHUB_RUN_ID}-${process.env.GITHUB_RUN_ATTEMPT}` : `${Date.now()}`
65 const label = process.env.NEON_TEST_BRANCH_LABEL
66 if (label !== undefined && !/^[a-z]{1,16}$/.test(label)) throw new Error('Invalid test branch label')
67 const name = `ds-test-${suffix}${label ? `-${label}` : ''}`
68 const parentId = process.env.NEON_PARENT_BRANCH_ID ?? (await neon.branches.getDefault({ projectId })).id
69 // Refuse stale state before allocating infrastructure. An exclusive handle
70 // also prevents two local runs from overwriting each other's cleanup identity.
71 const state = await open(stateFile, 'wx', 0o600)
72 let branch
73 try {
74 branch = await neon.branches.create({ projectId, name, parent_id: parentId,
75 expires_at: new Date(Date.now() + 24 * 3600_000).toISOString(),
76 compute: { minCu: 0.25, maxCu: 1, suspendTimeoutSeconds: 300 },
77 })
78 // Persist cleanup identity before fetching secrets or enabling services.
79 await state.writeFile(JSON.stringify({ projectId, branchId: branch.id, name }))
80 await state.sync()
81 } catch (error) {
82 if (!branch) await unlink(stateFile)
83 throw error
84 } finally { await state.close() }
85 await neon.realtime.enable({ projectId, branchId: branch.id })
86 const [pooled, direct, realtime, key] = await Promise.all([
87 neon.postgres.connectionString({ projectId, branchId: branch.id, pooled: true }),
88 neon.postgres.connectionString({ projectId, branchId: branch.id, pooled: false }),
89 neon.realtime.get({ projectId, branchId: branch.id }),
90 neon.realtime.secret({ projectId, branchId: branch.id }),
91 ])
92 if (!realtime.enabled || realtime.pending || !realtime.invocation_url || key.pending) throw new Error('Realtime did not reach ready state')
93 const verified = (uri) => { const url = new URL(uri); url.searchParams.set('sslmode', 'verify-full'); return url.href }
94 const values = { TEST_DATABASE_URL: verified(pooled), TEST_DATABASE_URL_UNPOOLED: verified(direct),
95 NEON_REALTIME_URL: realtime.invocation_url, NEON_REALTIME_SECRET: key.secret,
96 NEON_TEST_BRANCH_ID: branch.id, NEON_TEST_PROJECT_ID: projectId,
97 DURABLE_STREAMS_KEYRING: JSON.stringify({ currentKeyId: 'v1', keys: { v1: randomBytes(32).toString('base64') } }),
98 ...await storageEnvironment(branch.id),
99 }
100 await output(values)
101 console.log(`Ready: Postgres 18, Realtime, and Object Storage on isolated branch ${branch.id}; credentials saved without logging them.`)
102} else throw new Error('Expected create, storage, or delete')