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

+45 -29
View File
@@ -1,7 +1,7 @@
const http = require('node:http');
const fs = require('node:fs');
const path = require('node:path');
const { DatabaseSync } = require('node:sqlite');
const { Pool } = require('pg');
const MAX_BODY = 10 * 1024;
const REQUIRED = ['name', 'email', 'phone', 'company'];
@@ -14,21 +14,20 @@ const SERVICES = ['WiFi Managed Services', 'Cloud IP PABX', 'GRE IPTV', 'Digital
const FREE_EMAIL = /@(gmail|googlemail|yahoo|ymail|rocketmail|hotmail|outlook|live|msn|icloud|me|mac|aol|protonmail|proton|gmx|yandex|zoho)\.[a-z.]+$/i;
const PAGES = { '/': ['index.html', 'text/html; charset=utf-8'], '/logo.png': ['logo.png', 'image/png'] };
function openDb(dbPath) {
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
const db = new DatabaseSync(dbPath);
// WAL: an export (reader) never blocks inserts. busy_timeout blocks the event loop while waiting,
// ponytail: fine for one low-traffic pod; move to Postgres if this ever needs concurrency.
db.exec('PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;');
db.exec(`CREATE TABLE IF NOT EXISTS leads (
id INTEGER PRIMARY KEY,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
name TEXT NOT NULL, email TEXT NOT NULL, phone TEXT NOT NULL, company TEXT NOT NULL,
service TEXT, referrer TEXT,
utm_source TEXT, utm_medium TEXT, utm_campaign TEXT
)`);
return db;
}
// Kept identical to docs/schema.sql (a test compares the two).
const SCHEMA = `CREATE TABLE IF NOT EXISTS leads (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
name TEXT NOT NULL,
email TEXT NOT NULL,
phone TEXT NOT NULL,
company TEXT NOT NULL,
service TEXT,
referrer TEXT,
utm_source TEXT,
utm_medium TEXT,
utm_campaign TEXT
)`;
function validate(lead) {
for (const f of REQUIRED) {
@@ -56,7 +55,7 @@ function readBody(req) {
const chunks = [];
req.on('data', (c) => {
size += c.length;
// keep draining (not destroy) so the 413 reaches the client; the ingress body limit (nginx default 1m) caps abuse
// keep draining (not destroy) so the 413 reaches the client; Cloudflare's body limit caps abuse
if (size > MAX_BODY) reject(Object.assign(new Error('too large'), { status: 413 }));
else chunks.push(c);
});
@@ -65,16 +64,21 @@ function readBody(req) {
});
}
function createServer(dbPath) {
async function createServer(databaseUrl) {
// load static files up front: a missing file fails at startup instead of crashing on a request
const files = {};
for (const [url, [file, type]] of Object.entries(PAGES)) {
files[url] = { body: fs.readFileSync(path.join(__dirname, 'public', file)), type };
}
const db = openDb(dbPath);
const insert = db.prepare(`INSERT INTO leads
(name, email, phone, company, service, referrer, utm_source, utm_medium, utm_campaign)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`);
const pool = new Pool({ connectionString: databaseUrl, max: 5, connectionTimeoutMillis: 5000 });
// 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 {
await pool.query(SCHEMA);
} catch (e) {
await pool.end();
throw e;
}
const server = http.createServer(async (req, res) => {
const url = req.url.split('?')[0];
@@ -96,8 +100,11 @@ function createServer(dbPath) {
if (error) return send(res, 400, { error });
try {
const t = (f) => (lead[f] ? lead[f].trim() : null);
insert.run(t('name'), t('email'), t('phone'), t('company'), t('service'),
t('referrer'), t('utm_source'), t('utm_medium'), t('utm_campaign'));
await pool.query(`INSERT INTO leads
(name, email, phone, company, service, referrer, utm_source, utm_medium, utm_campaign)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
[t('name'), t('email'), t('phone'), t('company'), t('service'),
t('referrer'), t('utm_source'), t('utm_medium'), t('utm_campaign')]);
} catch (e) {
console.error('lead insert failed:', e.message);
return send(res, 500, { error: 'Could not save, please try again' });
@@ -106,7 +113,7 @@ function createServer(dbPath) {
}
send(res, 404, { error: 'Not found' });
});
server.on('close', () => db.close());
server.on('close', () => pool.end());
return server;
}
@@ -114,8 +121,17 @@ module.exports = { createServer };
if (require.main === module) {
const port = Number(process.env.PORT ?? 3000);
const server = createServer(process.env.DB_PATH || path.join(__dirname, 'data', 'leads.db'));
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)));
if (!process.env.DATABASE_URL) {
console.error('DATABASE_URL is not set');
process.exit(1);
}
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)));
}, (e) => {
// message only: the error never contains the password, but the URL would
console.error('startup failed:', e.message);
process.exit(1);
});
}