const assert = require('node:assert/strict'); const { execFileSync, spawnSync } = require('node:child_process'); const { randomUUID } = require('node:crypto'); const { mkdtempSync, mkdirSync, chmodSync, readFileSync, readdirSync, rmSync } = require('node:fs'); const { tmpdir } = require('node:os'); const path = require('node:path'); const { createRequire } = require('node:module'); const { setTimeout: delay } = require('node:timers/promises'); const root = path.resolve(__dirname, '../..'); const serverRequire = createRequire(path.join(root, 'server/package.json')); const { Pool } = serverRequire('pg'); async function main() { assert.equal(process.env.RUN_ISOLATED_BUDGET_DB_TEST, '1'); const scratch = mkdtempSync(path.join(tmpdir(), 'hyb-budget-synthetic-')); const socket = path.join(scratch, 'socket'); const dockerConfig = path.join(scratch, 'docker'); mkdirSync(socket); chmodSync(scratch, 0o755); chmodSync(socket, 0o777); mkdirSync(dockerConfig); const owner = randomUUID(); const docker = (args, input) => execFileSync('docker', ['--config', dockerConfig, ...args], { input, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], timeout: 60000, env: { PATH: process.env.PATH, LANG: 'C.UTF-8' }, }).trim(); let container; let pool; let failure; const passed = []; try { container = docker(['run', '-d', '--pull=never', '--network', 'none', '--read-only', '--label', `hyb.qa.owner=${owner}`, '--tmpfs', '/var/lib/postgresql/data', '--tmpfs', '/var/run/postgresql', '--tmpfs', '/tmp', '--mount', `type=bind,src=${socket},dst=/qa-socket`, '-e', 'POSTGRES_HOST_AUTH_METHOD=trust', '-e', 'POSTGRES_USER=synthetic', '-e', 'POSTGRES_DB=budget_synthetic', 'postgres:16-alpine', '-c', 'listen_addresses=', '-c', 'unix_socket_directories=/qa-socket,/var/run/postgresql']); assert.equal(docker(['inspect', '--format', '{{.HostConfig.NetworkMode}}', container]), 'none'); pool = new Pool({ host: socket, user: 'synthetic', database: 'budget_synthetic', password: '', max: 8, connectionTimeoutMillis: 1500, statement_timeout: 10000 }); let ready = false; for (let i = 0; i < 40; i++) { try { await pool.query('SELECT 1'); ready = true; break; } catch { await delay(250); } } if (!ready) { const logs = spawnSync('docker', ['--config', dockerConfig, 'logs', container], { encoding: 'utf8', env: { PATH: process.env.PATH }, timeout: 10000, }); console.error(logs.stdout, logs.stderr); throw new Error('isolated database did not become ready'); } const migrations = path.join(root, 'server/prisma/migrations'); let count = 0; for (const name of readdirSync(migrations).sort()) { if (name === 'migration_lock.toml') continue; // psql autocommit preserves PostgreSQL's new-enum-value transaction boundary. docker(['exec', '-i', container, 'psql', '-X', '-q', '-v', 'ON_ERROR_STOP=1', '-h', '/qa-socket', '-U', 'synthetic', '-d', 'budget_synthetic'], readFileSync(path.join(migrations, name, 'migration.sql'))); count++; } console.log(JSON.stringify({ stage: 'migrations', count, network: 'none', persistentVolumes: false })); passed.push('clean_database_all_migrations'); await require('./budget-pool-db-fixture.cjs')(pool, scratch); console.log(JSON.stringify({status:'PASS',checks:passed,scope:'isolated real PostgreSQL budget concurrency'})); } catch (error) { failure = error; throw error; } finally { try { if(pool) await pool.end(); if(container){ assert.equal(docker(['inspect','--format','{{ index .Config.Labels "hyb.qa.owner" }}',container]),owner); docker(['rm','-f',container]); } rmSync(scratch,{recursive:true,force:true}); console.log(JSON.stringify({cleanup:'PASS',onlyRunOwnedResources:true})); } catch (cleanupError) { console.error(JSON.stringify({cleanup:'FAIL',code:cleanupError.code??null})); if (!failure) throw cleanupError; } } } main().catch(error=>{console.error(JSON.stringify({status:'FAIL',name:error.name,code:error.code??null,actual:typeof error.actual==='string'&&/^[A-Z0-9-]{1,60}$/.test(error.actual)?error.actual:undefined,expected:typeof error.expected==='string'&&/^[A-Z0-9-]{1,60}$/.test(error.expected)?error.expected:undefined,fixtureLine:/budget-pool-db-fixture.cjs:(\d+)/.exec(error.stack??'')?.[1]??null,reason:error.name==='AssertionError'?String(error.message).split('\n')[0]:'budget_fixture_failed'}));process.exitCode=1;});