From ad5996283e1911190c94a2f5aad3b4184550c719 Mon Sep 17 00:00:00 2001 From: ngqile Date: Tue, 1 Dec 2026 11:59:55 +0800 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_01EFUzfmHGGiYUjNcvJoyzdf --- .gitea/workflows/ci.yml | 4 ++- README.md | 4 ++- .../2026-12-01-ins-landing-page-design.md | 2 +- k8s/20-postgres.yaml | 6 +++++ k8s/40-app.yaml | 6 +++++ server.js | 8 +++--- server.test.js | 26 +++++++++++++------ 7 files changed, 42 insertions(+), 14 deletions(-) diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index ccd353f..fe4e851 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -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" diff --git a/README.md b/README.md index 66aa063..2469119 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/docs/superpowers/specs/2026-12-01-ins-landing-page-design.md b/docs/superpowers/specs/2026-12-01-ins-landing-page-design.md index 9e13ecf..0cb8176 100644 --- a/docs/superpowers/specs/2026-12-01-ins-landing-page-design.md +++ b/docs/superpowers/specs/2026-12-01-ins-landing-page-design.md @@ -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). diff --git a/k8s/20-postgres.yaml b/k8s/20-postgres.yaml index a4d9f8e..fff0e88 100644 --- a/k8s/20-postgres.yaml +++ b/k8s/20-postgres.yaml @@ -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"] diff --git a/k8s/40-app.yaml b/k8s/40-app.yaml index 3283705..15f89ce 100644 --- a/k8s/40-app.yaml +++ b/k8s/40-app.yaml @@ -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: / diff --git a/server.js b/server.js index 566e014..2cf5555 100644 --- a/server.js +++ b/server.js @@ -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); diff --git a/server.test.js b/server.test.js index 6f631fb..f4a6dbd 100644 --- a/server.test.js +++ b/server.test.js @@ -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)));