feat: store leads in PostgreSQL instead of SQLite

- server.js uses pg (pinned 8.23.1), reads DATABASE_URL, creates the
  leads table on start, fails fast if Postgres is unreachable
- tests run against a real Postgres in a throwaway schema
- CI runs the test image against a throwaway Postgres on DinD
- k8s: Postgres 18 StatefulSet (Longhorn, 2Gi), init container wait,
  password secret, network policy app-to-postgres; app no longer needs
  a volume or Recreate
- README: DBeaver via port-forward, CSV export via docs/export-leads.sql

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:55:14 +08:00
1 parent 5bb2a7343d
commit f78bd635a2
15 files changed
+508 -166

No files matched your search

+50 -47
View File
@@ -1,23 +1,37 @@
// Needs a Postgres to test against: TEST_DATABASE_URL=postgres://user:pass@host:port/db npm test
// Each run creates its own schema and drops it afterwards, so existing tables are never touched.
const { test, before, after } = require('node:test');
const assert = require('node:assert');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { DatabaseSync } = require('node:sqlite');
const { spawn } = require('node:child_process');
const { Pool } = require('pg');
const { createServer } = require('./server');
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ins-leads-'));
const dbPath = path.join(dir, 'leads.db');
const adminUrl = process.env.TEST_DATABASE_URL;
if (!adminUrl) throw new Error('Set TEST_DATABASE_URL to a Postgres the tests may create a schema in');
const schema = `test_${process.pid}_${Date.now()}`;
const withSchema = (s) => {
const u = new URL(adminUrl);
u.searchParams.set('options', `-c search_path=${s}`);
return u.toString();
};
const dbUrl = withSchema(schema);
const admin = new Pool({ connectionString: adminUrl });
let server, base;
before(async () => {
server = createServer(dbPath);
await admin.query(`CREATE SCHEMA ${schema}`);
server = await createServer(dbUrl);
await new Promise((r) => server.listen(0, r));
base = `http://127.0.0.1:${server.address().port}`;
});
after(() => {
server.close();
fs.rmSync(dir, { recursive: true, force: true });
after(async () => {
await new Promise((r) => server.close(r));
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
await admin.end();
});
const valid = {
@@ -33,16 +47,11 @@ const valid = {
const post = (body) =>
fetch(`${base}/api/leads`, {
method: 'POST',
headers: { 'content-type': 'application/json', referer: 'https://ads.example.com/' },
headers: { 'content-type': 'application/json' },
body: typeof body === 'string' ? body : JSON.stringify(body),
});
const rows = () => {
const db = new DatabaseSync(dbPath);
const r = db.prepare('SELECT * FROM leads').all();
db.close();
return r;
};
const rows = async () => (await admin.query(`SELECT * FROM ${schema}.leads ORDER BY id`)).rows;
test('serves the landing page', async () => {
const res = await fetch(`${base}/`);
@@ -53,22 +62,22 @@ test('serves the landing page', async () => {
test('valid lead is stored', async () => {
const res = await post(valid);
assert.strictEqual(res.status, 201);
const r = rows();
const r = await rows();
assert.strictEqual(r.length, 1);
assert.strictEqual(r[0].name, valid.name);
assert.strictEqual(r[0].company, valid.company);
assert.strictEqual(r[0].service, 'Cloud IP PABX');
assert.strictEqual(r[0].utm_source, 'google');
assert.strictEqual(r[0].referrer, 'https://www.google.com/');
assert.ok(r[0].created_at);
assert.ok(r[0].created_at instanceof Date);
});
test('missing required field is rejected', async () => {
const before = rows().length;
const before = (await rows()).length;
const res = await post({ ...valid, phone: '' });
assert.strictEqual(res.status, 400);
assert.ok((await res.json()).error);
assert.strictEqual(rows().length, before);
assert.strictEqual((await rows()).length, before);
});
test('invalid email is rejected', async () => {
@@ -102,39 +111,28 @@ test('oversized body is rejected', async () => {
});
test('honeypot submission is accepted but not stored', async () => {
const before = rows().length;
const before = (await rows()).length;
const res = await post({ ...valid, website: 'http://spam.example' });
assert.strictEqual(res.status, 200);
assert.strictEqual(rows().length, before);
assert.strictEqual((await rows()).length, before);
});
const { spawn } = require('node:child_process');
test('missing page file fails at startup, not on a request', () => {
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'));
assert.throws(() => create(path.join(tmp, 'leads.db')), /ENOENT/);
await assert.rejects(() => create(dbUrl), /ENOENT/);
fs.rmSync(tmp, { recursive: true, force: true });
});
test('insert waits for a lock held by another process (e.g. an export)', async () => {
const lock = spawn(process.execPath, ['--disable-warning=ExperimentalWarning', '-e', `
const { DatabaseSync } = require('node:sqlite');
const db = new DatabaseSync(${JSON.stringify(dbPath)});
db.exec('BEGIN EXCLUSIVE');
console.log('locked');
setTimeout(() => { db.exec('COMMIT'); db.close(); }, 500);
`]);
await new Promise((r) => lock.stdout.once('data', r));
const res = await post(valid);
assert.strictEqual(res.status, 201);
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 () => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ins-term-'));
const child = spawn(process.execPath, ['--disable-warning=ExperimentalWarning', path.join(__dirname, 'server.js')], {
env: { ...process.env, PORT: '0', DB_PATH: path.join(tmp, 'leads.db') },
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));
const start = Date.now();
@@ -142,15 +140,20 @@ test('exits promptly on SIGTERM', async () => {
const code = await new Promise((r) => child.on('exit', (c) => r(c)));
assert.strictEqual(code, 0);
assert.ok(Date.now() - start < 2000);
fs.rmSync(tmp, { recursive: true, force: true });
});
test('docs/schema.sql matches the table the server creates', () => {
const cols = (db) => db.prepare('PRAGMA table_info(leads)').all().map((c) => [c.name, c.type, c.notnull, c.dflt_value, c.pk]);
const fromDoc = new DatabaseSync(':memory:');
fromDoc.exec(fs.readFileSync(path.join(__dirname, 'docs', 'schema.sql'), 'utf8'));
const fromServer = new DatabaseSync(dbPath, { readOnly: true });
assert.deepStrictEqual(cols(fromDoc), cols(fromServer));
fromDoc.close();
fromServer.close();
test('docs/schema.sql matches the table the server creates', async () => {
const docSchema = `${schema}_doc`;
const cols = async (s) => (await admin.query(
`SELECT column_name, data_type, is_nullable, column_default, is_identity
FROM information_schema.columns WHERE table_schema = $1 AND table_name = 'leads' ORDER BY ordinal_position`, [s])).rows;
const doc = new Pool({ connectionString: withSchema(docSchema) });
try {
await admin.query(`CREATE SCHEMA ${docSchema}`);
await doc.query(fs.readFileSync(path.join(__dirname, 'docs', 'schema.sql'), 'utf8'));
assert.deepStrictEqual(await cols(docSchema), await cols(schema));
} finally {
await doc.end();
await admin.query(`DROP SCHEMA IF EXISTS ${docSchema} CASCADE`);
}
});