diff --git a/.changeset/test-postgres.md b/.changeset/test-postgres.md new file mode 100644 index 0000000..d208ace --- /dev/null +++ b/.changeset/test-postgres.md @@ -0,0 +1,9 @@ +--- +"@plexus-ms/test-postgres": minor +--- + +A new package: a throwaway PostgreSQL server for tests, started from the binary on the PATH and removed afterwards. +`startPostgres({ major })` initialises a cluster in a temporary directory and starts it on a free loopback port; `createDatabase()` gives each test file a database of its own, empty or copied from a template, and `dropDatabase()` drops one. +It fails with a message naming the mise pin to add when no server is on the PATH, and when the server is of another major than the one asked for; it needs PostgreSQL 17 or later. +As root it runs the server as `nobody`, and no server outlives the process that started it, even one killed with SIGKILL. +It must stay external to a bundle, and refuses to start when it is bundled into its caller's file. diff --git a/mise.toml b/mise.toml index 4d7b493..b9bc22e 100644 --- a/mise.toml +++ b/mise.toml @@ -9,6 +9,8 @@ hk = "latest" # The plx pins are written with each Plexus version, never by the update bot (§ 1 PLX-Updates); # allow_low_downloads only waives npm's young-package heuristics. "npm:@plexus-ms/cli" = { version = "0.133.0", allow_low_downloads = true } +# The server @plexus-ms/test-postgres starts in its own tests; PLX_POSTGRES_MAJOR below names its major. +"conda:postgresql" = "18.6" [settings] # Not a version source: it lets config_roots match a project without a mise config of its own, @@ -21,6 +23,9 @@ postinstall = "if command -v hk >/dev/null; then hk install --mise; fi && npx co [env] _.path = ["{{config_root}}/node_modules/.bin"] +# The major the tests ask the server for: that of the conda:postgresql pin, which a wrong one fails. +# Declared in turbo.json, so a new major runs the tests again. +PLX_POSTGRES_MAJOR = "18" [tasks.dev] description = "No-op: a package repo has no development environment to start; build builds its packages and test exercises them" diff --git a/packages/test-postgres/package.json b/packages/test-postgres/package.json new file mode 100644 index 0000000..f539605 --- /dev/null +++ b/packages/test-postgres/package.json @@ -0,0 +1,36 @@ +{ + "name": "@plexus-ms/test-postgres", + "version": "0.0.0", + "description": "A throwaway PostgreSQL server for tests, from the binary on the PATH", + "license": "GPL-3.0-or-later", + "type": "module", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + }, + "types": "./dist/index.d.ts", + "files": [ + "dist" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/plexus-ms/libraries.git", + "directory": "packages/test-postgres" + }, + "publishConfig": { + "registry": "https://registry.npmjs.org", + "access": "public" + }, + "scripts": { + "build": "tsc", + "check": "tsc --noEmit", + "test": "node --test", + "prepack": "tsc" + }, + "devDependencies": { + "@types/node": "^24.19.4", + "typescript": "catalog:" + } +} diff --git a/packages/test-postgres/src/binaries.test.ts b/packages/test-postgres/src/binaries.test.ts new file mode 100644 index 0000000..f1a608e --- /dev/null +++ b/packages/test-postgres/src/binaries.test.ts @@ -0,0 +1,112 @@ +import assert from 'node:assert/strict'; +import { existsSync } from 'node:fs'; +import { mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { afterEach, test } from 'node:test'; +import { askedMajor, startThatFails } from './fixtures/support.ts'; +import { startPostgres } from './index.ts'; + +const originalPath = process.env.PATH; +const made: string[] = []; +afterEach(async () => { + process.env.PATH = originalPath; + delete process.env.DATABASE_URL; + for (const dir of made.splice(0)) await rm(dir, { recursive: true, force: true }); +}); + +// A directory on its own as the PATH, holding stand-ins for the tools named: +// postgres answers --version with `version`, initdb leaves a file initdb-ran +// beside them, and the others do nothing. +async function pathWith(tools: string[], version = `${askedMajor()}.6`) { + const dir = await mkdtemp(path.join(tmpdir(), 'test-postgres-path-')); + made.push(dir); + const scripts: Record = { + postgres: `echo "postgres (PostgreSQL) ${version}"`, + initdb: `touch "${dir}/initdb-ran"`, + }; + for (const tool of tools) { + await writeFile(path.join(dir, tool), `#!/bin/sh\n${scripts[tool] ?? 'exit 0'}\n`, { mode: 0o755 }); + } + process.env.PATH = dir; + return dir; +} + +const SERVER = ['initdb', 'pg_ctl', 'postgres', 'psql']; + +const namesThePin = (major: number) => (error: Error) => { + assert.match(error.message, new RegExp(`"conda:postgresql" = "${major}\\.`)); + assert.match(error.message, /mise\.toml/); + return true; +}; + +test('without PostgreSQL on the PATH it fails naming the mise pin to add', async () => { + const major = askedMajor(); + await pathWith([]); + await assert.rejects(startPostgres({ major }), (error: Error) => { + assert.match(error.message, /initdb/); + return namesThePin(major)(error); + }); +}); + +test('with a client-only install on the PATH it says so and names the mise pin', async () => { + const major = askedMajor(); + const dir = await pathWith(['psql', 'pg_dump']); + await assert.rejects(startPostgres({ major }), (error: Error) => { + assert.match(error.message, /client/); + assert.ok(error.message.includes(dir), 'names where the client is'); + return namesThePin(major)(error); + }); +}); + +test('with initdb but no server beside it it names what is missing and the mise pin', async () => { + const major = askedMajor(); + await pathWith(['initdb', 'psql']); + await assert.rejects(startPostgres({ major }), (error: Error) => { + assert.match(error.message, /pg_ctl/); + assert.match(error.message, /\bpostgres\b/); + return namesThePin(major)(error); + }); +}); + +test('it never falls back to a database from the environment', async () => { + const major = askedMajor(); + const running = await startPostgres({ major }); + try { + process.env.DATABASE_URL = running.url; + await pathWith([]); + await assert.rejects(startPostgres({ major }), namesThePin(major)); + } finally { + process.env.PATH = originalPath; + await running.stop(); + } +}); + +test('a server older than 17 fails before initdb, naming the version found', async () => { + const dir = await pathWith(SERVER, '16.9'); + const { error } = await startThatFails(() => startPostgres({ major: 16 })); + assert.match(error?.message ?? 'it started', /PostgreSQL 17 or later/); + assert.match(error?.message ?? '', /16\.9/); + assert.equal(existsSync(path.join(dir, 'initdb-ran')), false, 'initdb did not run'); +}); + +test('an install without psql beside initdb fails naming psql and the mise pin', async () => { + const major = askedMajor(); + await pathWith(['initdb', 'pg_ctl', 'postgres']); + await assert.rejects(startPostgres({ major }), (error: Error) => { + assert.match(error.message, /psql/); + return namesThePin(major)(error); + }); +}); + +test('a server of a lower and one of a higher major than asked for both fail', async () => { + for (const version of ['17.4', '19.1']) { + await pathWith(SERVER, version); + const { error } = await startThatFails(() => startPostgres({ major: 18 })); + assert.match( + error?.message ?? `it started with ${version}`, + new RegExp(`PostgreSQL ${version.replace('.', '\\.')}`), + ); + assert.match(error?.message ?? '', /"conda:postgresql" = "18\./); + } +}); diff --git a/packages/test-postgres/src/bundled.test.ts b/packages/test-postgres/src/bundled.test.ts new file mode 100644 index 0000000..9c990a8 --- /dev/null +++ b/packages/test-postgres/src/bundled.test.ts @@ -0,0 +1,111 @@ +import assert from 'node:assert/strict'; +import { execFileSync, spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { test } from 'node:test'; +import { askedMajor, startThatFails } from './fixtures/support.ts'; +import { startPostgres } from './index.ts'; + +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); +const processesNaming = (text: string) => + execFileSync('ps', ['-A', '-o', 'pid=', '-o', 'command='], { encoding: 'utf8' }) + .split('\n') + .filter((line) => line.includes(text)) + .map((line) => Number.parseInt(line, 10)); + +// A bundler puts the package's code and the caller's into one file, as here +// by hand: the package's source with a caller after it, in a directory whose +// package.json names `owner`. Every process that runs the file logs itself, +// and a process three levels down exits at once, so that a regression stays +// small. With `caught`, the caller catches the refusal and lives on for two +// seconds, during which nothing may be created. +async function assertBundleRefused(owner: string, caught = false) { + const app = await mkdtemp(path.join(tmpdir(), 'test-postgres-bundle-')); + const clusters = path.join(app, 'tmp'); + const log = path.join(app, 'processes.log'); + const file = path.join(app, 'app.ts'); + try { + await mkdir(clusters); + await writeFile(path.join(app, 'package.json'), `{ "name": "${owner}", "type": "module" }\n`); + const caller = [ + "import { appendFileSync } from 'node:fs';", + 'const depth = Number(process.env.TEST_BUNDLE_DEPTH ?? 0);', + `appendFileSync(${JSON.stringify(log)}, \`\${depth}\\n\`);`, + 'process.env.TEST_BUNDLE_DEPTH = String(depth + 1);', + 'if (depth >= 2) process.exit(0);', + caught ? 'try {' : '', + `const server = await startPostgres({ major: ${askedMajor()} });`, + 'await server.stop();', + caught + ? '} catch (error) { console.error(String(error)); await new Promise((r) => setTimeout(r, 2_000)); process.exit(1); }' + : '', + ].join('\n'); + await writeFile(file, `${await readFile(new URL('./index.ts', import.meta.url), 'utf8')}\n${caller}\n`); + + const run = spawn(process.execPath, [file], { + env: { ...process.env, TMPDIR: clusters }, + stdio: ['ignore', 'ignore', 'pipe'], + }); + let stderr = ''; + run.stderr.on('data', (chunk) => { + stderr += chunk; + }); + let created = false; + let ended = false; + const exited = once(run, 'exit').finally(() => { + ended = true; + }); + const watched = (async () => { + while (!ended) { + created ||= (await readdir(clusters)).length > 0; + await sleep(50); + } + })(); + const [code] = (await Promise.race([exited, sleep(20_000).then(() => ['timeout'])])) as [number | string]; + ended = true; + await watched; + await sleep(1_000); + + const depths = (await readFile(log, 'utf8')).trim().split('\n').map(Number); + assert.ok(depths.filter((depth) => depth > 0).length <= 1, `at most one supervisor ever existed: ${depths}`); + assert.notEqual(code, 0); + assert.match(stderr, /bundled/); + assert.match(stderr, /external/); + assert.deepEqual(processesNaming(clusters), [], 'no server runs'); + assert.deepEqual(await readdir(clusters), [], 'no cluster directory is left'); + assert.equal(created, false, 'no cluster directory was ever made'); + } finally { + // What a regression left: its processes, then its servers, then the files. + for (const pid of processesNaming(file)) process.kill(pid, 'SIGKILL'); + for (const pid of processesNaming(clusters)) process.kill(pid, 'SIGQUIT'); + for (let i = 0; i < 50 && processesNaming(clusters).length > 0; i++) await sleep(100); + await rm(app, { recursive: true, force: true }); + } +} + +test('bundled into the file of its caller it refuses to start, and starts nothing', { timeout: 60_000 }, () => + assertBundleRefused('app'), +); + +// The own-file check passes there, so the supervisor starts and has to find +// out for itself. +test('bundled into a file inside the package directory it refuses too, and leaves nothing', { timeout: 60_000 }, () => + assertBundleRefused('@plexus-ms/test-postgres'), +); + +test('a caller in such a bundle that catches the refusal and lives on starts nothing either', { timeout: 60_000 }, () => + assertBundleRefused('@plexus-ms/test-postgres', true), +); + +test('a process the package marked as a supervisor refuses to start another server', async () => { + process.env.PLEXUS_TEST_POSTGRES_SUPERVISOR = '{}'; + try { + const { error, left } = await startThatFails(() => startPostgres({ major: askedMajor() })); + assert.match(error?.message ?? 'it started', /bundled/); + assert.deepEqual(left, [], 'nothing was started'); + } finally { + delete process.env.PLEXUS_TEST_POSTGRES_SUPERVISOR; + } +}); diff --git a/packages/test-postgres/src/databases.test.ts b/packages/test-postgres/src/databases.test.ts new file mode 100644 index 0000000..20c7d2a --- /dev/null +++ b/packages/test-postgres/src/databases.test.ts @@ -0,0 +1,90 @@ +import assert from 'node:assert/strict'; +import { execFile } from 'node:child_process'; +import { after, before, test } from 'node:test'; +import { promisify } from 'node:util'; +import { askedMajor, query } from './fixtures/support.ts'; +import { createDatabase, dropDatabase, type Postgres, startPostgres } from './index.ts'; + +let server: Postgres; +before(async () => { + server = await startPostgres({ major: askedMajor() }); +}); +after(() => server.stop()); + +const nameOf = (url: string) => new URL(url).pathname.slice(1); + +test('createDatabase() gives each caller an empty database of its own, in parallel', async () => { + const [a, b] = await Promise.all([createDatabase(server.url), createDatabase(server.url)]); + assert.notEqual(nameOf(a), nameOf(b)); + await Promise.all([ + query(a, "create table t (v text); insert into t values ('a')"), + query(b, "create table t (v text); insert into t values ('b')"), + ]); + assert.equal(await query(a, 'select v from t'), 'a'); + assert.equal(await query(b, 'select v from t'), 'b'); +}); + +test('a database made from a template starts with its contents, even while a session holds the template', async () => { + const template = await createDatabase(server.url); + await query(template, "create table t (v text); insert into t values ('seed')"); + // A session still connected to the template, as a migration's pool can be + // for a moment after it ends: PostgreSQL refuses to copy the template meanwhile. + const lingering = promisify(execFile)('psql', ['-X', '-d', template, '-c', 'select pg_sleep(1)']); + await new Promise((resolve) => setTimeout(resolve, 200)); + const copies = await Promise.all( + Array.from({ length: 4 }, () => createDatabase(server.url, { template: nameOf(template) })), + ); + await lingering; + for (const copy of copies) assert.equal(await query(copy, 'select v from t'), 'seed'); + await query(copies[0] ?? '', "insert into t values ('only here')"); + assert.equal(await query(copies[1] ?? '', 'select count(*) from t'), '1'); +}); + +test('dropDatabase() drops the database its URL names, even with a session connected', async () => { + const url = await createDatabase(server.url); + // Longer than the five seconds PostgreSQL waits for a session to leave. + const lingering = promisify(execFile)('psql', ['-X', '-d', url, '-c', 'select pg_sleep(30)']).catch(() => {}); + await new Promise((resolve) => setTimeout(resolve, 200)); + await dropDatabase(url); + await lingering; + assert.equal(await query(server.url, `select count(*) from pg_database where datname = '${nameOf(url)}'`), '0'); +}); + +test('a name with a space and a double quote works as a template, and its URL drops it', async () => { + const name = 'odd "name" here'; + await query(server.url, `create database "odd ""name"" here"`); + const url = new URL(server.url); + url.pathname = `/${encodeURIComponent(name)}`; + await query(url.toString(), "create table t (v text); insert into t values ('from the odd one')"); + const copy = await createDatabase(server.url, { template: name }); + assert.equal(await query(copy, 'select v from t'), 'from the odd one'); + await dropDatabase(url.toString()); + assert.equal(await query(server.url, `select count(*) from pg_database where datname = 'odd "name" here'`), '0'); +}); + +test('the PG variables of the environment do not change where the calls connect', async () => { + const variables = { + PGHOSTADDR: '127.0.0.2', + PGPORT: '1', + PGDATABASE: 'nowhere', + PGUSER: 'nobody_here', + PGSSLMODE: 'require', + PGCONNECT_TIMEOUT: '2', + }; + Object.assign(process.env, variables); + let made: string; + let other: Postgres; + try { + other = await startPostgres({ major: askedMajor() }); + made = await createDatabase(server.url); + await dropDatabase(made); + } finally { + for (const name of Object.keys(variables)) delete process.env[name]; + } + try { + assert.equal(await query(other.url, 'select 1'), '1'); + assert.equal(await query(server.url, `select count(*) from pg_database where datname = '${nameOf(made)}'`), '0'); + } finally { + await other.stop(); + } +}); diff --git a/packages/test-postgres/src/fixtures/as-root.ts b/packages/test-postgres/src/fixtures/as-root.ts new file mode 100644 index 0000000..21f3491 --- /dev/null +++ b/packages/test-postgres/src/fixtures/as-root.ts @@ -0,0 +1,49 @@ +// The root case, which no test covers: a script run by hand as root. It +// starts a server, uses it and stops it, then tries an install that the +// unprivileged user cannot reach, and prints what it saw as one JSON line: +// the server's user is nobody, the directory is removed, and the second start +// fails naming nobody. +// In a container, from this package's directory: docker run --rm --cpus 2 --memory 2g --pids-limit 300 -v "$PWD":/pkg:ro -e PLX_POSTGRES_MAJOR=18 --entrypoint node /pkg/src/fixtures/as-root.ts +import { execFileSync } from 'node:child_process'; +import { existsSync, readFileSync, statSync } from 'node:fs'; +import { mkdtemp, rm, symlink } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { createDatabase, startPostgres } from '../index.ts'; +import { askedMajor, query } from './support.ts'; + +const major = askedMajor(); +const seen: Record = { uid: process.getuid?.() }; + +const server = await startPostgres({ major }); +let dataDirectory = ''; +try { + dataDirectory = await query(server.url, 'show data_directory'); + const postmaster = readFileSync(path.join(dataDirectory, 'postmaster.pid'), 'utf8').split('\n')[0] ?? ''; + seen.serverUser = execFileSync('ps', ['-o', 'user=', '-p', postmaster], { encoding: 'utf8' }).trim(); + seen.directoryOwner = statSync(dataDirectory).uid; + seen.query = await query(await createDatabase(server.url), 'select 1'); +} finally { + await server.stop(); +} +seen.removed = !existsSync(path.dirname(dataDirectory)); + +// The same install behind a directory that only root may enter, as an +// install under /root is. +const hidden = await mkdtemp(path.join(tmpdir(), 'test-postgres-hidden-')); +for (const tool of ['initdb', 'pg_ctl', 'postgres', 'psql']) { + const target = execFileSync('sh', ['-c', `command -v ${tool}`], { encoding: 'utf8' }).trim(); + await symlink(target, path.join(hidden, tool)); +} +process.env.PATH = `${hidden}${path.delimiter}${process.env.PATH}`; +try { + const unexpected = await startPostgres({ major }); + await unexpected.stop(); + seen.unreachable = 'started'; +} catch (error) { + seen.unreachable = error instanceof Error ? error.message : String(error); +} finally { + await rm(hidden, { recursive: true, force: true }); +} + +console.log(JSON.stringify(seen)); diff --git a/packages/test-postgres/src/fixtures/support.ts b/packages/test-postgres/src/fixtures/support.ts new file mode 100644 index 0000000..e07e0d6 --- /dev/null +++ b/packages/test-postgres/src/fixtures/support.ts @@ -0,0 +1,61 @@ +// What the tests share: the major they ask for, a way to ask a server +// something with the psql on the PATH, so that the tests need no driver, a +// way to watch a start that must fail, and the process list. +import { execFile, execFileSync } from 'node:child_process'; +import { mkdtemp, readdir, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { promisify } from 'node:util'; + +/** The major of the repo's PostgreSQL pin, which mise puts in PLX_POSTGRES_MAJOR. */ +export function askedMajor(): number { + const major = Number(process.env.PLX_POSTGRES_MAJOR); + if (!Number.isInteger(major)) throw new Error('PLX_POSTGRES_MAJOR names no major: run the tests through mise'); + return major; +} + +/** Runs `sql` against the database `url` names and returns psql's unaligned, tuples-only output. */ +export async function query(url: string, sql: string): Promise { + const { stdout } = await promisify(execFile)('psql', ['-X', '-At', '-v', 'ON_ERROR_STOP=1', '-d', url, '-c', sql]); + return stdout.trim(); +} + +/** + * Runs a start that must fail, with TMPDIR set to a directory of its own, and + * returns its error and what it left in that directory. A server that starts + * anyway is stopped, and the error is then undefined. + */ +export async function startThatFails( + start: () => Promise<{ stop(): Promise }>, +): Promise<{ error: Error | undefined; left: string[] }> { + const scratch = await mkdtemp(path.join(tmpdir(), 'test-postgres-scratch-')); + const original = process.env.TMPDIR; + process.env.TMPDIR = scratch; + try { + let error: Error | undefined; + try { + await (await start()).stop(); + } catch (caught) { + error = caught as Error; + } + return { error, left: await readdir(scratch) }; + } finally { + if (original === undefined) delete process.env.TMPDIR; + else process.env.TMPDIR = original; + await rm(scratch, { recursive: true, force: true }); + } +} + +/** The machine's processes, from ps. */ +export function processes(): { pid: number; ppid: number; command: string }[] { + return execFileSync('ps', ['-A', '-o', 'pid=', '-o', 'ppid=', '-o', 'command='], { encoding: 'utf8' }) + .split('\n') + .map((line) => line.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/)) + .filter((match) => match !== null) + .map(([, pid, ppid, command]) => ({ pid: Number(pid), ppid: Number(ppid), command: command ?? '' })); +} + +/** The supervisors this process started, which --supervise names in the process list. */ +export function supervisors(): { pid: number; ppid: number; command: string }[] { + return processes().filter(({ ppid, command }) => ppid === process.pid && command.includes('--supervise')); +} diff --git a/packages/test-postgres/src/index.ts b/packages/test-postgres/src/index.ts new file mode 100644 index 0000000..09d1a35 --- /dev/null +++ b/packages/test-postgres/src/index.ts @@ -0,0 +1,473 @@ +// @plexus-ms/test-postgres: a throwaway PostgreSQL server for tests, started +// from the binary on the PATH and removed afterwards. +// +// startPostgres() initialises a cluster in a new temporary directory with +// initdb, owned by the postgres role with trust authentication, UTF-8 with +// the builtin C.UTF-8 locale so that text sorts and cases alike on every +// machine, and without fsync, since the data lives for one run. The caller's +// settings, such as max_connections for many test workers, go into its +// postgresql.conf; the port, the address and the socket directory are the +// package's, and a caller's setting of them is refused. It starts the server +// with pg_ctl on a free port on 127.0.0.1, its socket in that directory, and +// returns the URL of the `postgres` database. stop() shuts the server down at +// once and removes the directory. A start that fails removes the directory +// too, and its error carries the end of the server's log, where PostgreSQL +// says why. +// +// The cluster belongs to a supervisor, this file run as a detached Node +// process, and not to the caller: the supervisor starts the cluster, reports +// its URL on its stdout, and waits for the end of its stdin, whose other end +// the caller holds. stop() closes that end; so does the kernel when the +// caller exits or is killed, SIGKILL included, which no exit handler sees. +// Either way the supervisor shuts the server down and removes the directory, +// and so it does on a SIGTERM, SIGINT or SIGHUP of its own; one that comes +// during the start fails the start once the cluster is up and gone again. A +// SIGKILL of the supervisor itself cannot be handled and leaves the server +// running. It runs in a session of its own, so that a SIGKILL to the caller's +// process group, as a runner may send to end a job, does not reach it. The +// caller may exit without calling stop(): nothing of the server keeps its +// event loop alive. +// +// So the package must stay a file of its own, external to any bundle: a +// bundle that holds the caller's code too would run the caller again as the +// supervisor. It refuses to start when its file is not the package's own (the +// nearest package.json names another package). The supervisor is marked by +// the environment variable PLEXUS_TEST_POSTGRES_SUPERVISOR, which the package +// sets on it, and not by its command line, which a bundle may change; a +// process so marked refuses to start another server. A bundle placed inside +// the package's own directory gets past the own-file check; its supervisor +// lets the bundled caller run first, and when that caller is refused it +// reports the refusal and starts nothing. +// +// createDatabase() makes a database of its own for each caller, so that test +// files running in parallel share no state: an empty one, or a copy of a +// template, such as a database the run migrated once, which PostgreSQL makes +// in milliseconds. Copies made at once from one template do not wait +// on each other; a session connected to the template makes PostgreSQL wait +// for it to leave, about five seconds, and then refuse the copy with SQLSTATE +// 55006, which the call passes on. +// dropDatabase() drops one, closing the sessions still connected to it. Both +// speak to the server with the psql beside the first initdb on the PATH when +// they are called, without the environment's PG variables, and need no +// driver. +// +// The binaries are the first initdb on the PATH and the pg_ctl, postgres and +// psql beside it: in a Plexus repo, the conda:postgresql pin of its +// mise.toml. The package installs nothing. When the PATH holds no initdb, or +// only a client, or an initdb without the rest, it fails with a message that +// names the pin to add. It never falls back to a container, to a database +// named by the environment (DATABASE_URL, the PG variables), or to an +// emulation: a pass must be the same evidence on every machine. +// +// The caller names the major it expects, and a server of another major on +// the PATH fails the start before anything is initialised, so that a test +// never passes against a version nobody pinned. It needs PostgreSQL 17 or +// later, the first with the builtin locale, and refuses an older server +// before initdb runs. +// +// PostgreSQL refuses to run as root. Where this process is root, as in a +// container or a cloud session, the cluster's directory belongs to nobody and +// initdb, pg_ctl and the server run as nobody. That needs the install to be +// readable by nobody, which one under /root (mode 0700) is not; the start +// then fails with a message that says so, as it does when there is no user +// nobody. It never runs the server as root and never changes the +// permissions of the install. No test covers this path; it is tried by hand +// with src/fixtures/as-root.ts. + +import { type SpawnOptions, spawn } from 'node:child_process'; +import { randomBytes } from 'node:crypto'; +import { once } from 'node:events'; +import { accessSync, constants, readFileSync, writeSync } from 'node:fs'; +import { appendFile, chown, mkdtemp, readFile, rm } from 'node:fs/promises'; +import { createServer, type Socket } from 'node:net'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { createInterface } from 'node:readline'; +import { fileURLToPath } from 'node:url'; + +export interface StartOptions { + /** The major version the server must have, as in 18. */ + major: number; + /** Server parameters for postgresql.conf, as in `{ max_connections: 400 }`. */ + settings?: Record; +} + +export interface Postgres { + /** The URL of the server's `postgres` database, as the `postgres` role. */ + url: string; + /** Shuts the server down and removes its directory. */ + stop(): Promise; +} + +export async function startPostgres(options: StartOptions): Promise { + if (process.env[SUPERVISOR] !== undefined) { + // A supervisor whose file holds a caller too, a bundle the own-file check + // let through: its own caller hears why before this process dies of it. + if (supervising && !refused) writeSync(1, `${JSON.stringify({ error: BUNDLED })}\n`); + refused = true; + throw new Error(BUNDLED); + } + const file = ownFile(); + const settings = checkSettings(options.settings ?? {}); + const bin = findInstall(options.major); + const owner = process.getuid?.() === 0 ? await unprivilegedUser() : undefined; + const postgres = path.join(bin, 'postgres'); + const version = ( + await run(postgres, ['--version'], owner).catch((error: Error) => { + if (!owner) throw error; + throw new Error( + `The process runs as root, so the server runs as nobody (uid ${owner.uid}), and nobody cannot run ${postgres}: ${error.message}. Make the install and every directory above it readable and searchable by all users, or install it where they are, as with a MISE_DATA_DIR outside /root.`, + ); + }) + ).match(/\(PostgreSQL\) (\S+)/)?.[1]; + const found = Number.parseInt(version ?? '', 10); + if (found < 17 || options.major < 17) { + throw new Error( + `@plexus-ms/test-postgres needs PostgreSQL 17 or later, for the builtin locale; the server on the PATH is PostgreSQL ${version} (${bin}). ${pin(Math.max(options.major, 17))}`, + ); + } + if (found !== options.major) { + throw new Error( + `The server on the PATH is PostgreSQL ${version} (${bin}), but ${options.major} was asked for. ${pin(options.major)}`, + ); + } + const supervisor = spawn(process.execPath, [file, '--supervise'], { + env: { ...process.env, [SUPERVISOR]: JSON.stringify({ bin, owner, settings }) }, + detached: true, + stdio: ['pipe', 'pipe', 'ignore'], + }); + const reports = createInterface({ input: supervisor.stdout })[Symbol.asyncIterator](); + const exited = once(supervisor, 'exit'); + const next = async (): Promise => { + const line = await reports.next(); + if (line.done) { + const [code, signal] = await exited; + return { error: `The supervisor of the server exited with ${signal ?? code} before it reported` }; + } + return JSON.parse(line.value) as Report; + }; + const ready = await next(); + if (!('url' in ready)) throw new Error('error' in ready ? ready.error : 'The supervisor reported no URL'); + // The supervisor lives on its own now: this process may exit without + // waiting for it, and the end of its stdin, however it comes, stops it. + const pipes = [supervisor.stdin, supervisor.stdout] as Socket[]; + supervisor.unref(); + for (const pipe of pipes) pipe.unref(); + let stopped: Promise | undefined; + return { + url: ready.url, + stop() { + stopped ??= (async () => { + supervisor.ref(); + for (const pipe of pipes) pipe.ref(); + supervisor.stdin.end(); + const [report] = await Promise.all([next(), exited]); + if ('error' in report) throw new Error(report.error); + })(); + return stopped; + }, + }; +} + +// What the supervisor writes to its stdout, one JSON line each: the server's +// URL once it runs, and whether it stopped. +type Report = { url: string } | { stopped: true } | { error: string }; + +// The variable that marks the supervisor and carries what it needs: the +// install's directory, the owner and the settings. `--supervise` on its +// command line only names it in a process list. +const SUPERVISOR = 'PLEXUS_TEST_POSTGRES_SUPERVISOR'; + +const BUNDLED = + '@plexus-ms/test-postgres cannot run bundled into another file, since it runs its own file as the supervisor of the server: keep it external to the bundle (for esbuild, --external:@plexus-ms/test-postgres).'; + +// This file, when it is the package's own: the file whose nearest +// package.json is this package's. A bundle that holds the caller's code too +// would run the caller again as the supervisor, and each such supervisor +// would start the next. +function ownFile(): string { + const file = fileURLToPath(import.meta.url); + for (let dir = path.dirname(file); dir !== path.dirname(dir); dir = path.dirname(dir)) { + let manifest: string; + try { + manifest = readFileSync(path.join(dir, 'package.json'), 'utf8'); + } catch { + continue; + } + if (JSON.parse(manifest).name === '@plexus-ms/test-postgres') return file; + break; + } + throw new Error(BUNDLED); +} + +// The supervisor: this file run on its own, marked by SUPERVISOR. It starts the cluster and reports its URL, then waits +// for the end of its stdin, and stops the cluster and removes its directory. +// Whether this process is a supervisor, and whether a startPostgres() in it +// refused to start. +let supervising = false; +let refused = false; + +async function supervise({ bin, owner, settings }: { bin: string; owner?: Owner; settings: Settings }) { + supervising = true; + // A caller bundled into this file runs now, before anything is created. + await new Promise((resolve) => setImmediate(resolve)); + if (refused) { + process.exitCode = 1; + return; + } + process.stdout.on('error', () => {}); + const report = (line: Report) => process.stdout.write(`${JSON.stringify(line)}\n`); + // The end of stdin or one of these signals asks for the stop. One that + // comes during the start is answered once the start is over, and the start + // then fails rather than hand out the URL of a server that is going. + let asked: string | undefined; + const stopAsked = new Promise((resolve) => { + const ask = (reason: string) => { + asked ??= reason; + resolve(); + }; + process.stdin + .on('end', () => ask('the end of its stdin')) + .on('error', () => ask('an error on its stdin')) + .resume(); + for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP']) process.on(signal, () => ask(`signal ${signal}`)); + }); + let cluster: Cluster; + try { + cluster = await startCluster(bin, owner, settings); + } catch (error) { + report({ error: error instanceof Error ? error.message : String(error) }); + process.exitCode = 1; + process.stdin.destroy(); + return; + } + if (asked !== undefined) { + await cluster.stop().catch(() => {}); + report({ error: `The supervisor of the server was stopped by ${asked} during the start` }); + process.exitCode = 1; + process.stdin.destroy(); + return; + } + report({ url: cluster.url }); + await stopAsked; + try { + await cluster.stop(); + report({ stopped: true }); + } catch (error) { + report({ error: error instanceof Error ? error.message : String(error) }); + process.exitCode = 1; + } +} + +// The user the server runs as when this process is root. +interface Owner { + uid: number; + gid: number; +} + +// PostgreSQL refuses to run as root, so as root the server runs as nobody, +// the one unprivileged user that Linux and macOS systems have, containers +// with neither a postgres user nor sudo among them. +async function unprivilegedUser(): Promise { + try { + const [uid, gid] = await Promise.all([run('id', ['-u', 'nobody']), run('id', ['-g', 'nobody'])]); + return { uid: Number(uid), gid: Number(gid) }; + } catch (error) { + throw new Error( + `The process runs as root, where PostgreSQL refuses to run, and there is no user nobody to run the server as: ${error instanceof Error ? error.message : error}`, + ); + } +} + +interface Cluster { + url: string; + stop(): Promise; +} + +async function startCluster(bin: string, owner: Owner | undefined, settings: Settings): Promise { + const dir = await mkdtemp(path.join(tmpdir(), 'test-postgres-')); + if (owner) await chown(dir, owner.uid, owner.gid); + const data = path.join(dir, 'data'); + const pgCtl = path.join(bin, 'pg_ctl'); + try { + const port = await freePort(); + await run( + path.join(bin, 'initdb'), + [ + '-D', + data, + '-U', + 'postgres', + '-A', + 'trust', + '--no-sync', + '-E', + 'UTF8', + '--locale=C', + '--locale-provider=builtin', + '--builtin-locale=C.UTF-8', + ], + owner, + ); + await appendFile( + path.join(data, 'postgresql.conf'), + configuration({ fsync: 'off', ...settings, port, listen_addresses: '127.0.0.1', unix_socket_directories: dir }), + ); + const log = path.join(dir, 'server.log'); + await run(pgCtl, ['-D', data, '-l', log, '-w', 'start'], owner).catch(async (error: Error) => { + // pg_ctl says only that the server did not start; why is in the log, + // which goes with the directory. + const tail = (await readFile(log, 'utf8').catch(() => '')).trim().split('\n').slice(-20).join('\n'); + throw new Error(`${error.message}\nThe end of server.log:\n${tail}`); + }); + return { + url: `postgres://postgres@127.0.0.1:${port}/postgres`, + async stop() { + try { + await run(pgCtl, ['-D', data, '-m', 'immediate', '-w', 'stop'], owner); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }, + }; + } catch (error) { + await rm(dir, { recursive: true, force: true }); + throw error; + } +} + +/** + * Creates a database on the server of `url` and returns its URL: an empty one, + * or a copy of the database named `template` on that server. + */ +export async function createDatabase(url: string, options: { template?: string } = {}): Promise { + const name = `test_${randomBytes(4).toString('hex')}`; + const template = options.template === undefined ? '' : ` template ${identifier(options.template)}`; + await sql(withDatabase(url, 'postgres'), `create database ${name}${template}`); + return withDatabase(url, name); +} + +/** Drops the database `url` names, closing the sessions connected to it. */ +export async function dropDatabase(url: string): Promise { + const name = decodeURIComponent(new URL(url).pathname.slice(1)); + await sql(withDatabase(url, 'postgres'), `drop database if exists ${identifier(name)} with (force)`); +} + +function withDatabase(url: string, name: string): string { + const parsed = new URL(url); + parsed.pathname = `/${name}`; + return parsed.toString(); +} + +function identifier(name: string): string { + return `"${name.replaceAll('"', '""')}"`; +} + +// One statement through psql, which names the SQLSTATE of an error in its +// message. The environment's PG variables are left out, so that only the URL +// says where and how to connect. +function sql(url: string, statement: string): Promise { + const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith('PG'))); + return run( + path.join(findInstall(), 'psql'), + ['-X', '-q', '-v', 'ON_ERROR_STOP=1', '-v', 'VERBOSITY=verbose', '-d', url, '-c', statement], + { env }, + ); +} + +// The directory of the first initdb on the PATH, which must hold the rest of +// the install beside it, or an error that names the pin to add. +function findInstall(major?: number): string { + const dirs = (process.env.PATH ?? '').split(path.delimiter).filter(Boolean); + const dir = dirs.find((candidate) => isExecutable(path.join(candidate, 'initdb'))); + if (!dir) { + const client = dirs.find((candidate) => isExecutable(path.join(candidate, 'psql'))); + const found = client ? `, and the psql in ${client} is a client-only install` : ''; + throw new Error(`No PostgreSQL server on the PATH: no initdb${found}. ${pin(major)}`); + } + const missing = TOOLS.filter((tool) => !isExecutable(path.join(dir, tool))); + if (missing.length > 0) { + throw new Error(`The PostgreSQL install in ${dir} has no ${missing.join(', ')} beside initdb. ${pin(major)}`); + } + return dir; +} + +const TOOLS = ['initdb', 'pg_ctl', 'postgres', 'psql']; + +function pin(major: number | undefined): string { + const version = `${major ?? ''}.`; + return `Pin the server in the repo's mise.toml, as "conda:postgresql" = "${version}" under [tools], and run mise install.`; +} + +function isExecutable(file: string): boolean { + try { + accessSync(file, constants.X_OK); + return true; + } catch { + return false; + } +} + +type Settings = Record; + +// The settings the package writes itself, which a caller cannot change. +const OWN_SETTINGS = ['port', 'listen_addresses', 'unix_socket_directories']; + +// Refuses a caller's setting that the package sets itself, a name that is no +// parameter's, and a value that is not a string or a number on one line. +function checkSettings(settings: Record): Settings { + for (const [name, value] of Object.entries(settings)) { + if (OWN_SETTINGS.includes(name)) throw new Error(`The setting ${name} is the package's own`); + if (!/^[a-z_][a-z0-9_.]*$/i.test(name)) throw new Error(`Not a server setting: ${name}`); + if (!(typeof value === 'string' || typeof value === 'number') || /[\r\n]/.test(String(value))) { + throw new Error(`The setting ${name} needs a string or a number on one line, not ${JSON.stringify(value)}`); + } + } + return settings as Settings; +} + +// Lines for postgresql.conf, where a later line wins over the defaults above +// it: no shell and no command line sees a value. +function configuration(settings: Settings): string { + return Object.entries(settings) + .map(([name, value]) => `${name} = '${String(value).replaceAll("'", "''")}'\n`) + .join(''); +} + +// A loopback port nothing listens on right now. +function freePort(): Promise { + return new Promise((resolve, reject) => { + const probe = createServer(); + probe.once('error', reject); + probe.listen(0, '127.0.0.1', () => { + const address = probe.address(); + probe.close(() => + typeof address === 'object' && address ? resolve(address.port) : reject(new Error('No free port')), + ); + }); + }); +} + +// Runs a tool to its end and resolves with its stdout, or rejects with its +// stderr. pg_ctl sends the server's output to the log file, so the started +// server holds no pipe of ours. +function run(file: string, args: string[], options: SpawnOptions = {}): Promise { + return new Promise((resolve, reject) => { + const child = spawn(file, args, { ...options, stdio: ['ignore', 'pipe', 'pipe'] }); + let stdout = ''; + let stderr = ''; + child.stdout?.on('data', (chunk) => { + stdout += chunk; + }); + child.stderr?.on('data', (chunk) => { + stderr += chunk; + }); + child.once('error', reject); + child.once('close', (code) => + code === 0 ? resolve(stdout) : reject(new Error(`${path.basename(file)} exited with ${code}: ${stderr.trim()}`)), + ); + }); +} + +const supervisorConfiguration = process.env[SUPERVISOR]; +if (supervisorConfiguration !== undefined) void supervise(JSON.parse(supervisorConfiguration)); diff --git a/packages/test-postgres/src/killed.test.ts b/packages/test-postgres/src/killed.test.ts new file mode 100644 index 0000000..8650e76 --- /dev/null +++ b/packages/test-postgres/src/killed.test.ts @@ -0,0 +1,147 @@ +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { existsSync } from 'node:fs'; +import { mkdtemp, readdir, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { createInterface } from 'node:readline'; +import { test } from 'node:test'; +import { askedMajor, processes, query, supervisors } from './fixtures/support.ts'; +import { startPostgres } from './index.ts'; + +// The processes whose command line names the data directory: the server's +// postmaster, as pg_ctl starts it. +function serverProcesses(dataDirectory: string): number[] { + return processes() + .filter(({ command }) => command.includes(`-D ${dataDirectory}`)) + .map(({ pid }) => pid); +} + +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +// Waits for the server of `dataDirectory` and its directory to go, and +// asserts that they went. A failing run takes down what it found, so that it +// leaves nothing behind. +async function assertGone(dataDirectory: string) { + const deadline = Date.now() + 15_000; + while ((serverProcesses(dataDirectory).length > 0 || existsSync(dataDirectory)) && Date.now() < deadline) { + await sleep(100); + } + const left = serverProcesses(dataDirectory); + try { + assert.deepEqual(left, [], 'no server process is left'); + assert.equal(existsSync(path.dirname(dataDirectory)), false, 'its directory is removed'); + } finally { + for (const pid of left) process.kill(pid, 'SIGQUIT'); + while (serverProcesses(dataDirectory).length > 0 && Date.now() < deadline + 15_000) await sleep(100); + await rm(path.dirname(dataDirectory), { recursive: true, force: true }); + } +} + +// A caller in a process of its own: it starts a server, prints its data +// directory and then, unless told to end, waits. With `group` it leads a process group of +// its own, as a shell's foreground job does. +async function caller(options: { end?: boolean; group?: boolean } = {}) { + const entry = new URL('./index.ts', import.meta.url).href; + const script = [ + "import { execFileSync } from 'node:child_process';", + `import { startPostgres } from ${JSON.stringify(entry)};`, + `const server = await startPostgres({ major: ${askedMajor()} });`, + "const show = ['-X', '-At', '-d', server.url, '-c', 'show data_directory'];", + "console.log(execFileSync('psql', show, { encoding: 'utf8' }).trim());", + options.end ? '' : 'setInterval(() => {}, 60_000);', + ].join('\n'); + const parent = spawn(process.execPath, ['--input-type=module', '-e', script], { + stdio: ['ignore', 'pipe', 'inherit'], + detached: options.group ?? false, + }); + const exited = once(parent, 'exit'); + const [dataDirectory] = (await once(createInterface({ input: parent.stdout }), 'line')) as [string]; + return { parent, exited, dataDirectory }; +} + +test('it leaves no server running when the process that started it is killed with SIGKILL', async () => { + const { parent, exited, dataDirectory } = await caller(); + assert.notDeepEqual(serverProcesses(dataDirectory), [], 'the server runs'); + + parent.kill('SIGKILL'); + const [, signal] = await exited; + assert.equal(signal, 'SIGKILL'); + await assertGone(dataDirectory); +}); + +test('a caller that ends without stop() is not held up, and leaves nothing', async () => { + const started = Date.now(); + const { parent, exited, dataDirectory } = await caller({ end: true }); + const [code] = await Promise.race([exited, sleep(5_000).then(() => ['still running'])]); + // A caller held up is ended here, so that this process can end. + if (code === 'still running') parent.kill('SIGKILL'); + assert.equal(code, 0, 'the caller ended by itself'); + assert.ok(Date.now() - started < 5_000); + await assertGone(dataDirectory); +}); + +// SIGINT is what a Ctrl-C sends to the foreground group; SIGKILL to a group is +// how a runner may end a job. +for (const signal of ['SIGINT', 'SIGKILL'] as const) { + test(`a ${signal} to the caller's process group leaves nothing`, async () => { + const { parent, exited, dataDirectory } = await caller({ group: true }); + process.kill(-(parent.pid ?? 0), signal); + await exited; + await assertGone(dataDirectory); + }); +} + +for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP'] as const) { + test(`a ${signal} to the supervisor stops the server and removes its directory`, async () => { + const server = await startPostgres({ major: askedMajor() }); + const dataDirectory = await query(server.url, 'show data_directory'); + const [supervisor] = supervisors(); + assert.ok(supervisor, 'the supervisor is a child of this process, named by --supervise'); + process.kill(supervisor.pid, signal); + await assertGone(dataDirectory); + await server.stop().catch(() => {}); + }); +} + +test('a signal to the supervisor during the start fails the start and leaves nothing', async () => { + const scratch = await mkdtemp(path.join(tmpdir(), 'test-postgres-signal-')); + const original = process.env.TMPDIR; + process.env.TMPDIR = scratch; + const running = () => + processes() + .filter(({ command }) => command.includes(`-D ${scratch}`)) + .map(({ pid }) => pid); + try { + const started = startPostgres({ major: askedMajor() }).then(async (server) => { + await server.stop(); + return server.url; + }); + // The supervisor has begun the cluster: its directory exists, initdb runs. + const deadline = Date.now() + 15_000; + while ((await readdir(scratch)).length === 0 && Date.now() < deadline) await sleep(10); + const [supervisor] = supervisors(); + assert.ok(supervisor, 'the supervisor runs'); + process.kill(supervisor.pid, 'SIGTERM'); + await assert.rejects(started, /signal/); + while ( + (running().length > 0 || (await readdir(scratch)).length > 0 || supervisors().length > 0) && + Date.now() < deadline + ) { + await sleep(100); + } + // A supervisor that stays is ended here, so that this process can end. + const lingering = supervisors(); + for (const { pid } of lingering) process.kill(pid, 'SIGKILL'); + assert.deepEqual(running(), [], 'no server process is left'); + assert.deepEqual(await readdir(scratch), [], 'no directory is left'); + assert.deepEqual(lingering, [], 'the supervisor exited'); + } finally { + if (original === undefined) delete process.env.TMPDIR; + else process.env.TMPDIR = original; + for (const pid of running()) process.kill(pid, 'SIGQUIT'); + for (let i = 0; i < 100 && running().length > 0; i++) await sleep(100); + await rm(scratch, { recursive: true, force: true }); + } +}); diff --git a/packages/test-postgres/src/major.test.ts b/packages/test-postgres/src/major.test.ts new file mode 100644 index 0000000..9456bbf --- /dev/null +++ b/packages/test-postgres/src/major.test.ts @@ -0,0 +1,15 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { askedMajor, startThatFails } from './fixtures/support.ts'; +import { startPostgres } from './index.ts'; + +test('it fails when the server on the PATH is of another major than the one asked for', async () => { + const installed = askedMajor(); + const asked = installed + 1; + const { error, left } = await startThatFails(() => startPostgres({ major: asked })); + assert.ok(error, 'the start fails'); + assert.match(error.message, new RegExp(`PostgreSQL ${installed}\\.\\d+`), 'names the version found'); + assert.match(error.message, new RegExp(`\\b${asked}\\b`), 'names the major asked for'); + assert.match(error.message, /mise\.toml/); + assert.deepEqual(left, [], 'nothing was initialised'); +}); diff --git a/packages/test-postgres/src/start.test.ts b/packages/test-postgres/src/start.test.ts new file mode 100644 index 0000000..642701b --- /dev/null +++ b/packages/test-postgres/src/start.test.ts @@ -0,0 +1,93 @@ +import assert from 'node:assert/strict'; +import { existsSync } from 'node:fs'; +import path from 'node:path'; +import { test } from 'node:test'; +import { askedMajor, query, startThatFails, supervisors } from './fixtures/support.ts'; +import { startPostgres } from './index.ts'; + +test('starts a server on a loopback port that answers, and stop() takes it down with its directory', async () => { + const major = askedMajor(); + const server = await startPostgres({ major }); + let dataDirectory = ''; + try { + assert.equal(new URL(server.url).hostname, '127.0.0.1'); + assert.equal(await query(server.url, 'select 1 + 1'), '2'); + assert.equal(await query(server.url, "select current_setting('server_version_num')::int / 10000"), String(major)); + dataDirectory = await query(server.url, 'show data_directory'); + assert.ok(existsSync(dataDirectory)); + } finally { + await server.stop(); + } + assert.equal(existsSync(path.dirname(dataDirectory)), false, 'the temporary directory is removed'); + await assert.rejects(query(server.url, 'select 1'), 'the server is down'); +}); + +test('the cluster is UTF-8 with the builtin C.UTF-8 locale, the same on every machine', async () => { + const server = await startPostgres({ major: askedMajor() }); + try { + assert.equal(await query(server.url, 'show server_encoding'), 'UTF8'); + assert.equal( + await query(server.url, 'select datlocale from pg_database where datname = current_database()'), + 'C.UTF-8', + ); + assert.equal(await query(server.url, "select upper('äb')"), 'ÄB'); + } finally { + await server.stop(); + } +}); + +test('settings are passed to the server', async () => { + const server = await startPostgres({ major: askedMajor(), settings: { max_connections: 250, cluster_name: "it's" } }); + try { + assert.equal(await query(server.url, 'show max_connections'), '250'); + assert.equal(await query(server.url, 'show cluster_name'), "it's"); + } finally { + await server.stop(); + } +}); + +test('a start that fails says what PostgreSQL said, and leaves no directory', async () => { + const { error, left } = await startThatFails(() => + startPostgres({ major: askedMajor(), settings: { max_connections: 'many' } }), + ); + assert.match(error?.message ?? 'it started', /invalid value for parameter "max_connections"/); + assert.deepEqual(left, []); + // Its supervisor exits too, rather than wait for this process to end. One + // that stays is ended here, so that this process can end. + const deadline = Date.now() + 5_000; + while (supervisors().length > 0 && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 100)); + const lingering = supervisors(); + for (const { pid } of lingering) process.kill(pid, 'SIGKILL'); + assert.deepEqual(lingering, [], 'the supervisor exited'); +}); + +test('settings the package sets itself, odd names, and values that are not a string or a number are refused', async () => { + const refused: Record[] = [ + { port: 5432 }, + { listen_addresses: '*' }, + { unix_socket_directories: '/tmp' }, + { cluster_name: undefined }, + { cluster_name: true }, + { cluster_name: ['a'] }, + { 'cluster name': 'a' }, + { cluster_name: 'a\nport = 1' }, + ]; + for (const settings of refused) { + const { error, left } = await startThatFails(() => + startPostgres({ major: askedMajor(), settings: settings as Record }), + ); + assert.match(error?.message ?? `it started with ${JSON.stringify(settings)}`, /setting/); + assert.deepEqual(left, []); + } +}); + +test('the server listens on 127.0.0.1 only, its socket in its own directory', async () => { + const server = await startPostgres({ major: askedMajor() }); + try { + assert.equal(await query(server.url, 'show listen_addresses'), '127.0.0.1'); + const dataDirectory = await query(server.url, 'show data_directory'); + assert.equal(await query(server.url, 'show unix_socket_directories'), path.dirname(dataDirectory)); + } finally { + await server.stop(); + } +}); diff --git a/packages/test-postgres/tsconfig.json b/packages/test-postgres/tsconfig.json new file mode 100644 index 0000000..94828e9 --- /dev/null +++ b/packages/test-postgres/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2022"], + "types": ["node"], + "module": "NodeNext", + "moduleResolution": "NodeNext", + "outDir": "dist", + "rootDir": "src", + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "strict": true, + "verbatimModuleSyntax": true, + "skipLibCheck": true, + "noUncheckedIndexedAccess": true + }, + "include": ["src"], + "exclude": ["dist", "node_modules", "**/*.test.ts", "src/fixtures"] +} diff --git a/packages/test-postgres/turbo.json b/packages/test-postgres/turbo.json new file mode 100644 index 0000000..6c0e160 --- /dev/null +++ b/packages/test-postgres/turbo.json @@ -0,0 +1,9 @@ +{ + "$schema": "https://turborepo.com/schema.json", + "extends": ["//"], + "tasks": { + "test": { + "env": ["$TURBO_EXTENDS$", "PLX_POSTGRES_MAJOR"] + } + } +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d6bb691..b535c07 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -222,6 +222,15 @@ importers: specifier: 'catalog:' version: 6.0.3 + packages/test-postgres: + devDependencies: + '@types/node': + specifier: ^24.19.4 + version: 24.19.4 + typescript: + specifier: 'catalog:' + version: 6.0.3 + packages: '@biomejs/biome@2.6.9':