fix: address review of the Postgres move

- close the pool on SIGTERM before exiting; query_timeout on the pool
- SIGTERM test fails instead of hanging; test cleanup in finally
- preStop sleep so rollouts don't drop form posts; Postgres startupProbe
- CI step timeout, clear error if test Postgres never starts, remove test image
- export stops on SQL errors; README note on changing the DB password

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfmHGGiYUjNcvJoyzdf
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-12-01 11:59:55 +08:00
1 parent 20e07e9d80
commit ad5996283e
7 files changed
+42 -14

No files matched your search

+3 -1
View File
@@ -52,6 +52,7 @@ jobs:
"$GITHUB_WORKSPACE/scripts/waitForOlderRuns.sh" "$RUN_NUMBER"
- name: Docker build & push
timeout-minutes: 20
env:
REGISTRY_USER: ${{ secrets.PACKAGE_USER }}
REGISTRY_PASSWORD: ${{ secrets.PACKAGE_RW_KEY }}
@@ -66,12 +67,13 @@ jobs:
printf '%s' "$REGISTRY_PASSWORD" | docker login "$_REGISTRY" -u "$REGISTRY_USER" --password-stdin
# Tests need Postgres: run them in the test stage against a throwaway one on its own network.
T="ins-ci-$GITHUB_RUN_ID"
trap 'docker rm -f "$T-pg" >/dev/null 2>&1; docker network rm "$T" >/dev/null 2>&1' EXIT
trap 'docker rm -f "$T-pg" >/dev/null 2>&1; docker network rm "$T" >/dev/null 2>&1; docker rmi -f "$T-test" >/dev/null 2>&1' EXIT
docker build --pull -f Dockerfile --target test -t "$T-test" .
docker network create "$T"
docker run -d --name "$T-pg" --network "$T" -e POSTGRES_USER=ci -e POSTGRES_DB=ci -e POSTGRES_PASSWORD=ci postgres:18
# -h 127.0.0.1: the image first starts a socket-only init server; TCP answers only once it is really up
for i in $(seq 1 30); do docker exec "$T-pg" pg_isready -h 127.0.0.1 -U ci -d ci && break; sleep 2; done
docker exec "$T-pg" pg_isready -h 127.0.0.1 -U ci -d ci || { echo "Postgres for tests did not start"; docker logs "$T-pg"; exit 1; }
docker run --rm --network "$T" -e TEST_DATABASE_URL="postgres://ci:ci@$T-pg:5432/ci" "$T-test"
docker build -f Dockerfile -t "$IMAGE_REF" .
docker push "$IMAGE_REF"
+3 -1
View File
@@ -46,6 +46,8 @@ First install, on the microk8s host (`k` = `microk8s kubectl`):
k -n ins-landing-page rollout status statefulset/postgres
k -n ins-landing-page rollout status deployment/ins-landing-page
The password is read only when the database is first created. To change it later, run `ALTER USER ins PASSWORD '...'` in Postgres first, then update the secret and restart the app; changing only the secret locks the app out.
`k apply -f k8s/` does not recurse, so `k8s/examples/secret.yaml` (an example, never the real value) is not applied.
Updates: every push to `main` runs the tests against a throwaway Postgres, then builds `gitea.containerverse.dev/solvway/ins-landing-page:ins-landing-page-prd-latest`. CI then runs `./krrd.sh ins-landing-page ins-landing-page` on the deploy host. Manifest changes are applied by hand (`k apply -f k8s/`).
@@ -73,7 +75,7 @@ Close the port-forward when you're done.
To CSV, with times in Malaysia time:
```bash
microk8s kubectl -n ins-landing-page exec -i postgres-0 -- psql -q -U ins -d ins -f - < docs/export-leads.sql > leads.csv
microk8s kubectl -n ins-landing-page exec -i postgres-0 -- psql -q -v ON_ERROR_STOP=1 -U ins -d ins -f - < docs/export-leads.sql > leads.csv
```
Read-only. Text cells starting with `= + - @` get a leading `'` so Excel can't run form input as a formula; phone numbers starting with `+` show it too.
@@ -62,4 +62,4 @@ Decision (user, 2026-12-01): move lead storage to Postgres so the team can open
- New dependency: `pg` (node-postgres), pinned exactly. Node has no built-in Postgres client. This ends "zero npm dependencies".
- The app reads `DATABASE_URL`, creates the `leads` table on start if missing, and closes the pool on SIGTERM.
- Tests run against a real Postgres, each run in its own throwaway schema, so they never touch existing tables. CI starts a Postgres container on the DinD daemon and runs the test image against it.
- DBeaver: `kubectl port-forward` to the Postgres service. CSV export via `psql \copy`.
- DBeaver: `kubectl port-forward` to the Postgres service. CSV export via `psql` running `COPY ... TO STDOUT` (docs/export-leads.sql).
+6
View File
@@ -59,6 +59,12 @@ spec:
ports:
- name: postgres
containerPort: 5432
# Allow up to 5 minutes for crash recovery before liveness can restart the pod.
startupProbe:
exec:
command: ["pg_isready", "-U", "ins", "-d", "ins"]
periodSeconds: 10
failureThreshold: 30
readinessProbe:
exec:
command: ["pg_isready", "-U", "ins", "-d", "ins"]
+6
View File
@@ -67,6 +67,12 @@ spec:
ports:
- name: http
containerPort: 3000
# Keep serving for a moment after SIGTERM while Traefik drops this pod from its endpoints,
# so a rollout doesn't turn a form submission into a 502.
lifecycle:
preStop:
exec:
command: ["sleep", "3"]
readinessProbe:
httpGet:
path: /
+5 -3
View File
@@ -70,7 +70,8 @@ async function createServer(databaseUrl) {
for (const [url, [file, type]] of Object.entries(PAGES)) {
files[url] = { body: fs.readFileSync(path.join(__dirname, 'public', file)), type };
}
const pool = new Pool({ connectionString: databaseUrl, max: 5, connectionTimeoutMillis: 5000 });
// query_timeout: a Postgres that accepts connections but never answers must not hang requests
const pool = new Pool({ connectionString: databaseUrl, max: 5, connectionTimeoutMillis: 5000, query_timeout: 10000 });
// an idle connection dropped by Postgres (restart, failover) must not crash the process
pool.on('error', (e) => console.error('postgres pool error:', e.message));
try {
@@ -113,7 +114,7 @@ async function createServer(databaseUrl) {
}
send(res, 404, { error: 'Not found' });
});
server.on('close', () => pool.end());
server.pool = pool; // callers end it after server.close (see SIGTERM below)
return server;
}
@@ -128,7 +129,8 @@ if (require.main === module) {
createServer(process.env.DATABASE_URL).then((server) => {
server.listen(port, () => console.log(`listening on :${port}`));
// node as PID 1 ignores SIGTERM by default; exit cleanly so k8s rollouts don't wait 30s
process.on('SIGTERM', () => server.close(() => process.exit(0)));
// finish in-flight requests, then close the database connections, then exit
process.on('SIGTERM', () => server.close(() => server.pool.end().finally(() => process.exit(0))));
}, (e) => {
// message only: the error never contains the password, but the URL would
console.error('startup failed:', e.message);
+18 -8
View File
@@ -29,7 +29,10 @@ before(async () => {
base = `http://127.0.0.1:${server.address().port}`;
});
after(async () => {
await new Promise((r) => server.close(r));
if (server) {
await new Promise((r) => server.close(r));
await server.pool.end();
}
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
await admin.end();
});
@@ -119,22 +122,29 @@ test('honeypot submission is accepted but not stored', async () => {
test('missing page file fails at startup, not on a request', async () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ins-nopage-'));
fs.copyFileSync(path.join(__dirname, 'server.js'), path.join(tmp, 'server.js'));
fs.symlinkSync(path.join(__dirname, 'node_modules'), path.join(tmp, 'node_modules'));
const { createServer: create } = require(path.join(tmp, 'server.js'));
await assert.rejects(() => create(dbUrl), /ENOENT/);
fs.rmSync(tmp, { recursive: true, force: true });
try {
fs.copyFileSync(path.join(__dirname, 'server.js'), path.join(tmp, 'server.js'));
fs.symlinkSync(path.join(__dirname, 'node_modules'), path.join(tmp, 'node_modules'));
const { createServer: create } = require(path.join(tmp, 'server.js'));
await assert.rejects(() => create(dbUrl), /ENOENT/);
} finally {
fs.rmSync(tmp, { recursive: true, force: true });
}
});
test('unreachable database fails at startup', async () => {
await assert.rejects(() => createServer('postgres://nobody:nothing@127.0.0.1:1/none'));
});
test('exits promptly on SIGTERM', async () => {
test('exits promptly on SIGTERM', { timeout: 15000 }, async () => {
const child = spawn(process.execPath, [path.join(__dirname, 'server.js')], {
env: { ...process.env, PORT: '0', DATABASE_URL: dbUrl },
});
await new Promise((r) => child.stdout.once('data', r));
// fail instead of hanging if the server dies before it starts listening
await new Promise((resolve, reject) => {
child.stdout.once('data', resolve);
child.once('exit', (c) => reject(new Error(`server exited early with code ${c}`)));
});
const start = Date.now();
child.kill('SIGTERM');
const code = await new Promise((r) => child.on('exit', (c) => r(c)));