Open History to see the last commit
1import { readFile, realpath, rm, unlink } from 'node:fs/promises'
2import { basename, dirname } from 'node:path'
3import { tmpdir } from 'node:os'
4import { createNeonClient } from '@neon/sdk'
5import pg from 'pg'
6
7const stateFile = '.neon-test-state-rolling.json', artifactsFile = '.neon-test-state-rolling-artifacts.json'
8let state
9try { state = JSON.parse(await readFile(stateFile, 'utf8')) } catch (error) { if (error.code !== 'ENOENT') throw error }
10if (state) {
11 const { NEON_API_KEY: apiKey, NEON_PROJECT_ID: projectId, NEON_TEST_BRANCH_ID: branchId, TEST_DATABASE_URL_UNPOOLED: uri } = process.env
12 const parsed = uri && new URL(uri)
13 if (!apiKey || state.projectId !== projectId || state.branchId !== branchId || !/^ds_test_[a-f0-9]{32}$/.test(state.schema)
14 || !parsed || parsed.hostname !== state.databaseHost || parsed.pathname !== state.databaseName
15 || !Array.isArray(state.slugs) || state.slugs.length !== 4 || state.slugs.some((slug) => !/^dsmix[a-d][a-f0-9]{12}$/.test(slug))) throw new Error('Unrecognized rolling fixture cleanup')
16 const neon = createNeonClient({ apiKey, throwOnError: true, waitForReadiness: true })
17 const branch = await neon.branches.get({ projectId, branchId })
18 if (branch.default || branch.protected || branch.name !== state.branchName || !branch.name.startsWith('ds-test-')) throw new Error('Rolling fixture branch identity changed')
19 const functions = await neon.functions.list({ projectId, branchId }).all()
20 for (const fn of functions) if (state.slugs.includes(fn.slug)) await neon.functions.delete({ projectId, branchId, slug: fn.slug })
21 await new Promise((resolve) => setTimeout(resolve, 6000))
22 const pool = new pg.Pool({ connectionString: uri, max: 1, connectionTimeoutMillis: 20_000, query_timeout: 60_000 })
23 try { await pool.query(`DROP SCHEMA IF EXISTS "${state.schema}" CASCADE`) } finally { await pool.end() }
24 await unlink(stateFile)
25}
26let artifacts
27try { artifacts = JSON.parse(await readFile(artifactsFile, 'utf8')) } catch (error) { if (error.code !== 'ENOENT') throw error }
28if (artifacts) {
29 if (!basename(artifacts.directory).startsWith('durable-streams-rolling-')
30 || await realpath(dirname(artifacts.directory)) !== await realpath(tmpdir())) throw new Error('Unrecognized rolling artifact directory')
31 await rm(artifacts.directory, { recursive: true, force: true })
32 await unlink(artifactsFile)
33}
34console.log('Cleaned up the recorded rolling Functions, isolated schema, and packed consumers.')