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:
1 parent
5bb2a7343d
commit
f78bd635a2
15 files changed
+508
-166
No files matched your search
@@ -1,7 +1,12 @@
|
|||||||
.git
|
.git
|
||||||
|
.gitea
|
||||||
.superpowers
|
.superpowers
|
||||||
.playwright-cli
|
.playwright-cli
|
||||||
|
.impeccable
|
||||||
data
|
data
|
||||||
docs
|
docs
|
||||||
|
!docs/schema.sql
|
||||||
|
k8s
|
||||||
|
scripts
|
||||||
node_modules
|
node_modules
|
||||||
*.db
|
*.db
|
||||||
+11
-3
@@ -3,8 +3,8 @@ name: CI
|
|||||||
# Image build for ins-landing-page, following dynamic-qr's pipeline (build container, DinD, one
|
# Image build for ins-landing-page, following dynamic-qr's pipeline (build container, DinD, one
|
||||||
# moving tag per profile, per-branch run queue, guarded microk8s rollout, notifications). The k8s
|
# moving tag per profile, per-branch run queue, guarded microk8s rollout, notifications). The k8s
|
||||||
# manifests live in k8s/ and are applied by hand (README "Kubernetes"); CI only rolls the
|
# manifests live in k8s/ and are applied by hand (README "Kubernetes"); CI only rolls the
|
||||||
# Deployment so it pulls the new image, and only from main. Tests run inside the Dockerfile's
|
# Deployment so it pulls the new image, and only from main. Tests run from the Dockerfile's
|
||||||
# `test` stage, so a failing test stops the image from being pushed.
|
# `test` stage against a throwaway Postgres container, so a failing test stops the push.
|
||||||
#
|
#
|
||||||
# Tags: main -> ins-landing-page-prd-latest; dev -> ins-landing-page-dev-latest.
|
# Tags: main -> ins-landing-page-prd-latest; dev -> ins-landing-page-dev-latest.
|
||||||
|
|
||||||
@@ -64,7 +64,15 @@ jobs:
|
|||||||
esac
|
esac
|
||||||
IMAGE_REF="$_REGISTRY/$_REGISTRY_PREFIX/$_IMAGE_NAME:$_REPO_NAME-$PROFILE-latest"
|
IMAGE_REF="$_REGISTRY/$_REGISTRY_PREFIX/$_IMAGE_NAME:$_REPO_NAME-$PROFILE-latest"
|
||||||
printf '%s' "$REGISTRY_PASSWORD" | docker login "$_REGISTRY" -u "$REGISTRY_USER" --password-stdin
|
printf '%s' "$REGISTRY_PASSWORD" | docker login "$_REGISTRY" -u "$REGISTRY_USER" --password-stdin
|
||||||
docker build --pull -f Dockerfile --target test .
|
# 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
|
||||||
|
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 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 build -f Dockerfile -t "$IMAGE_REF" .
|
||||||
docker push "$IMAGE_REF"
|
docker push "$IMAGE_REF"
|
||||||
echo "Pushed $IMAGE_REF"
|
echo "Pushed $IMAGE_REF"
|
||||||
|
|||||||
+8
-7
@@ -1,17 +1,18 @@
|
|||||||
FROM node:22-alpine AS base
|
FROM node:22-alpine AS base
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY package.json server.js ./
|
COPY package.json package-lock.json ./
|
||||||
|
RUN npm ci --omit=dev
|
||||||
|
COPY server.js ./
|
||||||
COPY public ./public
|
COPY public ./public
|
||||||
|
|
||||||
# CI builds this stage first (`--target test`); a failing test stops the image from being pushed.
|
# CI runs this stage against a throwaway Postgres (TEST_DATABASE_URL); a failing test stops the push.
|
||||||
FROM base AS test
|
FROM base AS test
|
||||||
COPY server.test.js ./
|
COPY server.test.js ./
|
||||||
RUN node --disable-warning=ExperimentalWarning --test
|
COPY docs/schema.sql ./docs/schema.sql
|
||||||
|
CMD ["node", "--test"]
|
||||||
|
|
||||||
FROM base
|
FROM base
|
||||||
ENV NODE_ENV=production PORT=3000 DB_PATH=/data/leads.db
|
ENV NODE_ENV=production PORT=3000
|
||||||
RUN mkdir -p /data && chown node:node /data
|
|
||||||
USER node
|
USER node
|
||||||
VOLUME /data
|
|
||||||
EXPOSE 3000
|
EXPOSE 3000
|
||||||
CMD ["node", "--disable-warning=ExperimentalWarning", "server.js"]
|
CMD ["node", "server.js"]
|
||||||
@@ -1,86 +1,85 @@
|
|||||||
# INS Landing Page
|
# INS Landing Page
|
||||||
|
|
||||||
Single landing page for Infinity Networks Security with a lead form. Leads are stored in a SQLite file; there is no admin UI, leads are exported manually.
|
Landing page for Infinity Networks Security's hotel technology services, with a lead form. Leads are stored in PostgreSQL; there is no admin UI, leads are read in DBeaver or exported as CSV.
|
||||||
|
|
||||||
- `public/index.html`: the page (content from infinitynetworks.com.my)
|
- `public/index.html`: the page
|
||||||
- `server.js`: serves the page and `POST /api/leads`, Node 22 built-ins only, no npm dependencies
|
- `server.js`: serves the page and `POST /api/leads`; creates the `leads` table on start if it is missing
|
||||||
|
- `docs/schema.sql`: the table, for reference (a test keeps it in sync with `server.js`)
|
||||||
|
- `docs/export-leads.sql`: CSV export query
|
||||||
|
|
||||||
|
Node 22, one dependency: [`pg`](https://www.npmjs.com/package/pg) (pinned in `package-lock.json`).
|
||||||
|
|
||||||
## Run locally
|
## Run locally
|
||||||
|
|
||||||
Requires Node 22.13 or newer.
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm start # http://localhost:3000, database at ./data/leads.db
|
docker run -d --name ins-pg -e POSTGRES_USER=ins -e POSTGRES_DB=ins -e POSTGRES_PASSWORD=devpass \
|
||||||
npm test
|
-p 127.0.0.1:5432:5432 postgres:18
|
||||||
|
npm ci
|
||||||
|
DATABASE_URL=postgres://ins:devpass@127.0.0.1:5432/ins npm start # http://localhost:3000
|
||||||
|
TEST_DATABASE_URL=postgres://ins:devpass@127.0.0.1:5432/ins npm test
|
||||||
```
|
```
|
||||||
|
|
||||||
Environment: `PORT` (default `3000`), `DB_PATH` (default `./data/leads.db`).
|
Environment: `DATABASE_URL` (required), `PORT` (default `3000`). Tests create their own schema in `TEST_DATABASE_URL` and drop it afterwards; they never touch an existing `leads` table.
|
||||||
|
|
||||||
## Docker
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker build -t ins-landing-page .
|
|
||||||
docker run -p 3000:3000 -v ins-leads:/data ins-landing-page
|
|
||||||
```
|
|
||||||
|
|
||||||
## Kubernetes (microk8s)
|
## Kubernetes (microk8s)
|
||||||
|
|
||||||
`k8s/` deploys everything into namespace `ins-landing-page`, the same way as dynamic-qr:
|
`k8s/` deploys everything into namespace `ins-landing-page`, the same way as dynamic-qr:
|
||||||
|
|
||||||
- `40-app.yaml`: Longhorn PVC (1 Gi, ReadWriteOnce) mounted at `/data`, Service, and Deployment. The Deployment runs **1 replica** with `strategy: Recreate`, because SQLite has a single writer. It runs as uid 1000 with a read-only root filesystem.
|
- `20-postgres.yaml`: Postgres 18 StatefulSet with a Longhorn PVC (2 Gi, ReadWriteOnce) and a headless Service `postgres`.
|
||||||
|
- `40-app.yaml`: Service and Deployment. The app waits in an init container until Postgres answers, then creates the `leads` table if it is missing. It runs as uid 1000 with a read-only root filesystem.
|
||||||
- `50-gateway.yaml`:
|
- `50-gateway.yaml`:
|
||||||
- A Let's Encrypt Certificate and a Traefik Gateway for `ins-landing.containerverse.dev`.
|
- A Let's Encrypt Certificate and a Traefik Gateway for `ins-landing.containerverse.dev`.
|
||||||
- HTTP redirects to HTTPS.
|
- HTTP redirects to HTTPS.
|
||||||
- `POST /api/leads` goes through the `lead-rate-limit` middleware: 5 per minute per visitor, burst 5, keyed on the Cloudflare visitor IP.
|
- `POST /api/leads` goes through the `lead-rate-limit` middleware: 5 per minute per visitor, burst 5, keyed on the Cloudflare visitor IP.
|
||||||
- `60-network-policy.yaml`: denies all ingress except Traefik to port 3000, and Traefik to cert-manager's HTTP-01 solver.
|
- `60-network-policy.yaml`: denies all ingress except Traefik to the app (port 3000), the app to Postgres (5432), and Traefik to cert-manager's HTTP-01 solver.
|
||||||
|
|
||||||
Prerequisite: DNS for `ins-landing.containerverse.dev` points at the cluster through Cloudflare, like the other `containerverse.dev` hosts.
|
Prerequisite: DNS for `ins-landing.containerverse.dev` points at the cluster through Cloudflare, like the other `containerverse.dev` hosts.
|
||||||
|
|
||||||
First install, on the microk8s host (`k` = `microk8s kubectl`):
|
First install, on the microk8s host (`k` = `microk8s kubectl`):
|
||||||
|
|
||||||
k apply -f k8s/00-namespace.yaml
|
k apply -f k8s/00-namespace.yaml
|
||||||
|
k -n ins-landing-page create secret generic ins-landing-page-db \
|
||||||
|
--from-literal=POSTGRES_PASSWORD="$(openssl rand -hex 24)"
|
||||||
k -n ins-landing-page create secret docker-registry regcred \
|
k -n ins-landing-page create secret docker-registry regcred \
|
||||||
--docker-server=gitea.containerverse.dev --docker-username=<user> --docker-password=<token>
|
--docker-server=gitea.containerverse.dev --docker-username=<user> --docker-password=<token>
|
||||||
k apply -f k8s/
|
k apply -f k8s/
|
||||||
|
k -n ins-landing-page rollout status statefulset/postgres
|
||||||
k -n ins-landing-page rollout status deployment/ins-landing-page
|
k -n ins-landing-page rollout status deployment/ins-landing-page
|
||||||
|
|
||||||
Updates: every push to `main` runs the tests and 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/`).
|
`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/`).
|
||||||
|
|
||||||
CI needs the same repository secrets as dynamic-qr: `PACKAGE_USER`, `PACKAGE_RW_KEY`, `DRONECICD_SSH_*`, `TELEGRAM_*` and, optionally, `MICROSOFT_TEAMS_WEBHOOK_URL`. They come from the `solvway` org once the repo is transferred there.
|
CI needs the same repository secrets as dynamic-qr: `PACKAGE_USER`, `PACKAGE_RW_KEY`, `DRONECICD_SSH_*`, `TELEGRAM_*` and, optionally, `MICROSOFT_TEAMS_WEBHOOK_URL`. They come from the `solvway` org once the repo is transferred there.
|
||||||
|
|
||||||
|
## Opening the database in DBeaver
|
||||||
|
|
||||||
|
Postgres is not exposed outside the cluster. Forward a local port to it, on the microk8s host:
|
||||||
|
|
||||||
|
microk8s kubectl -n ins-landing-page port-forward svc/postgres 15432:5432
|
||||||
|
|
||||||
|
If DBeaver runs on another machine, tunnel to that host first: `ssh -L 15432:127.0.0.1:15432 <user>@<microk8s-host>`.
|
||||||
|
|
||||||
|
In DBeaver: **New Database Connection → PostgreSQL**:
|
||||||
|
|
||||||
|
- Host `127.0.0.1`, port `15432`, database `ins`, user `ins`.
|
||||||
|
- Password: `microk8s kubectl -n ins-landing-page get secret ins-landing-page-db -o jsonpath='{.data.POSTGRES_PASSWORD}' | base64 -d`.
|
||||||
|
- Tick **Read-only connection** (connection settings → General) unless you mean to change data. This is the live database.
|
||||||
|
|
||||||
|
Close the port-forward when you're done.
|
||||||
|
|
||||||
## Exporting leads
|
## Exporting leads
|
||||||
|
|
||||||
To CSV, from the running pod:
|
To CSV, with times in Malaysia time:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
microk8s kubectl -n ins-landing-page exec deploy/ins-landing-page -- node --disable-warning=ExperimentalWarning -e "
|
microk8s kubectl -n ins-landing-page exec -i postgres-0 -- psql -q -U ins -d ins -f - < docs/export-leads.sql > leads.csv
|
||||||
const {DatabaseSync}=require('node:sqlite');
|
|
||||||
const rows=new DatabaseSync(process.env.DB_PATH,{readOnly:true}).prepare('SELECT * FROM leads ORDER BY id').all();
|
|
||||||
const q=v=>v==null?'':'\"'+String(v).replace(/^[=+\-@]/,\"'\$&\").replace(/\"/g,'\"\"')+'\"';
|
|
||||||
if(rows.length)console.log(Object.keys(rows[0]).join(','));
|
|
||||||
for(const r of rows)console.log(Object.values(r).map(q).join(','));
|
|
||||||
" > leads.csv
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Opening the database in DBeaver
|
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.
|
||||||
|
|
||||||
SQLite is a file, not a network server, so DBeaver cannot connect to the pod. Take a consistent snapshot and open that copy:
|
Leads are personal data (PDPA): keep exports out of shared drives and delete them when you're done.
|
||||||
|
|
||||||
```bash
|
## Backups
|
||||||
NS=ins-landing-page
|
|
||||||
POD=$(microk8s kubectl -n $NS get pod -l app=ins-landing-page -o name | head -1 | cut -d/ -f2)
|
|
||||||
# VACUUM INTO writes one complete file, including leads still in the WAL
|
|
||||||
microk8s kubectl -n $NS exec $POD -- node --disable-warning=ExperimentalWarning -e \
|
|
||||||
"new (require('node:sqlite').DatabaseSync)(process.env.DB_PATH).exec(\"VACUUM INTO '/data/snapshot.db'\")"
|
|
||||||
microk8s kubectl -n $NS cp $POD:/data/snapshot.db ./leads-snapshot.db
|
|
||||||
microk8s kubectl -n $NS exec $POD -- rm /data/snapshot.db
|
|
||||||
```
|
|
||||||
|
|
||||||
In DBeaver: **New Database Connection → SQLite →** point **Path** at `leads-snapshot.db`. Query and export freely; it's your own copy.
|
|
||||||
|
|
||||||
Edits made in DBeaver stay in the copy. **Never copy a file back into the pod while the app is running**: it would overwrite leads submitted in the meantime. To fix or delete live rows, run the SQL in the pod (`exec ... node -e "..."`) and keep a snapshot first.
|
|
||||||
|
|
||||||
Leads are personal data (PDPA): delete snapshots and CSVs when you're done.
|
|
||||||
|
|
||||||
Schema: `docs/schema.sql`. Columns: `id, created_at (UTC), name, email, phone, company, service, referrer, utm_source, utm_medium, utm_campaign`.
|
|
||||||
|
|
||||||
|
The leads live only on the Postgres volume, and these manifests set up no backup. Confirm with the cluster manager that Longhorn snapshots or backups cover the `ins-landing-page-postgres` volume, or schedule a `pg_dump`.
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
-- Export all leads as CSV on stdout. Read-only.
|
||||||
|
-- Usage: README "Exporting leads".
|
||||||
|
-- Text cells starting with = + - @ tab or CR get a leading apostrophe, so Excel cannot run
|
||||||
|
-- form input as a formula (CSV injection).
|
||||||
|
COPY (
|
||||||
|
SELECT id,
|
||||||
|
to_char(created_at AT TIME ZONE 'Asia/Kuala_Lumpur', 'YYYY-MM-DD HH24:MI:SS') AS created_at_myt,
|
||||||
|
regexp_replace(name, E'^([=+@\\t\\r-])', E'\'\\1') AS name,
|
||||||
|
regexp_replace(email, E'^([=+@\\t\\r-])', E'\'\\1') AS email,
|
||||||
|
regexp_replace(phone, E'^([=+@\\t\\r-])', E'\'\\1') AS phone,
|
||||||
|
regexp_replace(company, E'^([=+@\\t\\r-])', E'\'\\1') AS company,
|
||||||
|
service,
|
||||||
|
regexp_replace(referrer, E'^([=+@\\t\\r-])', E'\'\\1') AS referrer,
|
||||||
|
regexp_replace(utm_source, E'^([=+@\\t\\r-])', E'\'\\1') AS utm_source,
|
||||||
|
regexp_replace(utm_medium, E'^([=+@\\t\\r-])', E'\'\\1') AS utm_medium,
|
||||||
|
regexp_replace(utm_campaign, E'^([=+@\\t\\r-])', E'\'\\1') AS utm_campaign
|
||||||
|
FROM leads
|
||||||
|
ORDER BY id
|
||||||
|
) TO STDOUT WITH (FORMAT csv, HEADER);
|
||||||
+7
-7
@@ -1,4 +1,4 @@
|
|||||||
-- Lead storage for ins-landing-page (SQLite).
|
-- Lead storage for ins-landing-page (PostgreSQL).
|
||||||
--
|
--
|
||||||
-- Reference only: server.js creates this table itself on first start (CREATE TABLE IF NOT EXISTS),
|
-- Reference only: server.js creates this table itself on first start (CREATE TABLE IF NOT EXISTS),
|
||||||
-- so nobody needs to run this file on deploy. server.test.js fails if this file and server.js
|
-- so nobody needs to run this file on deploy. server.test.js fails if this file and server.js
|
||||||
@@ -8,14 +8,14 @@
|
|||||||
-- so a new column also needs an ALTER TABLE step against the live database.
|
-- so a new column also needs an ALTER TABLE step against the live database.
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS leads (
|
CREATE TABLE IF NOT EXISTS leads (
|
||||||
id INTEGER PRIMARY KEY,
|
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, -- UTC, 'YYYY-MM-DD HH:MM:SS'
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
name TEXT NOT NULL,
|
name TEXT NOT NULL,
|
||||||
email TEXT NOT NULL, -- work email; free providers rejected
|
email TEXT NOT NULL, -- work email; free providers rejected
|
||||||
phone TEXT NOT NULL, -- phone / WhatsApp, as typed
|
phone TEXT NOT NULL, -- phone / WhatsApp, as typed
|
||||||
company TEXT NOT NULL,
|
company TEXT NOT NULL,
|
||||||
service TEXT, -- one of the form's options, or NULL
|
service TEXT, -- one of the form's options, or NULL
|
||||||
referrer TEXT, -- site the visitor came from
|
referrer TEXT, -- site the visitor came from
|
||||||
utm_source TEXT,
|
utm_source TEXT,
|
||||||
utm_medium TEXT,
|
utm_medium TEXT,
|
||||||
utm_campaign TEXT
|
utm_campaign TEXT
|
||||||
|
|||||||
@@ -53,3 +53,13 @@ The page owner supplied a new brief. It replaces the page content and form; stor
|
|||||||
- Google Fonts allowed (owner request). Floating WhatsApp/call button on mobile.
|
- Google Fonts allowed (owner request). Floating WhatsApp/call button on mobile.
|
||||||
- Decision (user, 2026-12-01): keep the existing database endpoint instead of the brief's `action="#"` placeholder.
|
- Decision (user, 2026-12-01): keep the existing database endpoint instead of the brief's `action="#"` placeholder.
|
||||||
- Schema: `industry` and `message` columns replaced by `service`. The local database held only throwaway test data and is recreated.
|
- Schema: `industry` and `message` columns replaced by `service`. The local database held only throwaway test data and is recreated.
|
||||||
|
|
||||||
|
## Revision 2026-12-01: Postgres instead of SQLite
|
||||||
|
|
||||||
|
Decision (user, 2026-12-01): move lead storage to Postgres so the team can open the live data in DBeaver.
|
||||||
|
|
||||||
|
- Option chosen: a dedicated Postgres 18 StatefulSet in namespace `ins-landing-page`, copied from dynamic-qr (Longhorn PVC, password Secret, init container waiting for `pg_isready`, network policy allowing only the app). Rejected: a database on a shared Postgres (cross-namespace coupling, leads sharing a server with other apps).
|
||||||
|
- 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`.
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
apiVersion: v1
|
||||||
|
kind: PersistentVolumeClaim
|
||||||
|
metadata:
|
||||||
|
name: ins-landing-page-postgres
|
||||||
|
namespace: ins-landing-page
|
||||||
|
spec:
|
||||||
|
storageClassName: longhorn
|
||||||
|
# ReadWriteOnce, not ReadWriteMany: Longhorn serves RWX over NFS, which a database should not
|
||||||
|
# write through. One replica mounts it.
|
||||||
|
accessModes:
|
||||||
|
- ReadWriteOnce
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
storage: 2Gi
|
||||||
|
---
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Service
|
||||||
|
metadata:
|
||||||
|
name: postgres
|
||||||
|
namespace: ins-landing-page
|
||||||
|
spec:
|
||||||
|
clusterIP: None
|
||||||
|
selector:
|
||||||
|
app: postgres
|
||||||
|
ports:
|
||||||
|
- name: postgres
|
||||||
|
port: 5432
|
||||||
|
---
|
||||||
|
apiVersion: apps/v1
|
||||||
|
kind: StatefulSet
|
||||||
|
metadata:
|
||||||
|
name: postgres
|
||||||
|
namespace: ins-landing-page
|
||||||
|
spec:
|
||||||
|
serviceName: postgres
|
||||||
|
replicas: 1
|
||||||
|
selector:
|
||||||
|
matchLabels:
|
||||||
|
app: postgres
|
||||||
|
template:
|
||||||
|
metadata:
|
||||||
|
labels:
|
||||||
|
app: postgres
|
||||||
|
spec:
|
||||||
|
terminationGracePeriodSeconds: 60
|
||||||
|
containers:
|
||||||
|
- name: postgres
|
||||||
|
image: postgres:18
|
||||||
|
env:
|
||||||
|
- name: POSTGRES_USER
|
||||||
|
value: ins
|
||||||
|
- name: POSTGRES_DB
|
||||||
|
value: ins
|
||||||
|
- name: POSTGRES_PASSWORD
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: ins-landing-page-db
|
||||||
|
key: POSTGRES_PASSWORD
|
||||||
|
ports:
|
||||||
|
- name: postgres
|
||||||
|
containerPort: 5432
|
||||||
|
readinessProbe:
|
||||||
|
exec:
|
||||||
|
command: ["pg_isready", "-U", "ins", "-d", "ins"]
|
||||||
|
periodSeconds: 5
|
||||||
|
livenessProbe:
|
||||||
|
exec:
|
||||||
|
command: ["pg_isready", "-U", "ins", "-d", "ins"]
|
||||||
|
periodSeconds: 20
|
||||||
|
failureThreshold: 6
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
cpu: 100m
|
||||||
|
memory: 128Mi
|
||||||
|
limits:
|
||||||
|
memory: 1Gi
|
||||||
|
volumeMounts:
|
||||||
|
# postgres:18 keeps its data under /var/lib/postgresql/<major>/docker.
|
||||||
|
- name: data
|
||||||
|
mountPath: /var/lib/postgresql
|
||||||
|
volumes:
|
||||||
|
- name: data
|
||||||
|
persistentVolumeClaim:
|
||||||
|
claimName: ins-landing-page-postgres
|
||||||
+24
-27
@@ -1,18 +1,3 @@
|
|||||||
# Leads live in a SQLite file on this volume. ReadWriteOnce + 1 replica + Recreate: SQLite has a
|
|
||||||
# single writer, so two pods must never hold the file at once (not even during a rollout).
|
|
||||||
apiVersion: v1
|
|
||||||
kind: PersistentVolumeClaim
|
|
||||||
metadata:
|
|
||||||
name: ins-landing-page-data
|
|
||||||
namespace: ins-landing-page
|
|
||||||
spec:
|
|
||||||
storageClassName: longhorn
|
|
||||||
accessModes:
|
|
||||||
- ReadWriteOnce
|
|
||||||
resources:
|
|
||||||
requests:
|
|
||||||
storage: 1Gi
|
|
||||||
---
|
|
||||||
apiVersion: v1
|
apiVersion: v1
|
||||||
kind: Service
|
kind: Service
|
||||||
metadata:
|
metadata:
|
||||||
@@ -32,8 +17,6 @@ metadata:
|
|||||||
namespace: ins-landing-page
|
namespace: ins-landing-page
|
||||||
spec:
|
spec:
|
||||||
replicas: 1
|
replicas: 1
|
||||||
strategy:
|
|
||||||
type: Recreate
|
|
||||||
selector:
|
selector:
|
||||||
matchLabels:
|
matchLabels:
|
||||||
app: ins-landing-page
|
app: ins-landing-page
|
||||||
@@ -49,7 +32,23 @@ spec:
|
|||||||
runAsNonRoot: true
|
runAsNonRoot: true
|
||||||
runAsUser: 1000 # the image's `node` user
|
runAsUser: 1000 # the image's `node` user
|
||||||
runAsGroup: 1000
|
runAsGroup: 1000
|
||||||
fsGroup: 1000 # so the app can write to the Longhorn volume
|
# Start the app only once Postgres answers, instead of crash-looping into a growing back-off
|
||||||
|
# after a first install or a node restart. Same image as the StatefulSet, so nothing extra is pulled.
|
||||||
|
initContainers:
|
||||||
|
- name: wait-for-postgres
|
||||||
|
image: postgres:18
|
||||||
|
command: ["sh", "-c", "until pg_isready -h postgres -p 5432 -U ins -d ins; do sleep 2; done"]
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
cpu: 10m
|
||||||
|
memory: 16Mi
|
||||||
|
limits:
|
||||||
|
memory: 64Mi
|
||||||
|
securityContext:
|
||||||
|
allowPrivilegeEscalation: false
|
||||||
|
readOnlyRootFilesystem: true
|
||||||
|
capabilities:
|
||||||
|
drop: ["ALL"]
|
||||||
containers:
|
containers:
|
||||||
- name: ins-landing-page
|
- name: ins-landing-page
|
||||||
# One moving tag per profile (CI); the rollout restarts the pod to pull it.
|
# One moving tag per profile (CI); the rollout restarts the pod to pull it.
|
||||||
@@ -58,14 +57,16 @@ spec:
|
|||||||
env:
|
env:
|
||||||
- name: PORT
|
- name: PORT
|
||||||
value: "3000"
|
value: "3000"
|
||||||
- name: DB_PATH
|
- name: POSTGRES_PASSWORD
|
||||||
value: /data/leads.db
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: ins-landing-page-db
|
||||||
|
key: POSTGRES_PASSWORD
|
||||||
|
- name: DATABASE_URL
|
||||||
|
value: postgres://ins:$(POSTGRES_PASSWORD)@postgres:5432/ins
|
||||||
ports:
|
ports:
|
||||||
- name: http
|
- name: http
|
||||||
containerPort: 3000
|
containerPort: 3000
|
||||||
volumeMounts:
|
|
||||||
- name: data
|
|
||||||
mountPath: /data
|
|
||||||
readinessProbe:
|
readinessProbe:
|
||||||
httpGet:
|
httpGet:
|
||||||
path: /
|
path: /
|
||||||
@@ -89,7 +90,3 @@ spec:
|
|||||||
readOnlyRootFilesystem: true
|
readOnlyRootFilesystem: true
|
||||||
capabilities:
|
capabilities:
|
||||||
drop: ["ALL"]
|
drop: ["ALL"]
|
||||||
volumes:
|
|
||||||
- name: data
|
|
||||||
persistentVolumeClaim:
|
|
||||||
claimName: ins-landing-page-data
|
|
||||||
@@ -35,6 +35,27 @@ spec:
|
|||||||
- protocol: TCP
|
- protocol: TCP
|
||||||
port: 3000
|
port: 3000
|
||||||
---
|
---
|
||||||
|
# Postgres: app pods only (kubectl exec and port-forward are not pod network traffic and are unaffected).
|
||||||
|
apiVersion: networking.k8s.io/v1
|
||||||
|
kind: NetworkPolicy
|
||||||
|
metadata:
|
||||||
|
name: postgres-from-app
|
||||||
|
namespace: ins-landing-page
|
||||||
|
spec:
|
||||||
|
podSelector:
|
||||||
|
matchLabels:
|
||||||
|
app: postgres
|
||||||
|
policyTypes:
|
||||||
|
- Ingress
|
||||||
|
ingress:
|
||||||
|
- from:
|
||||||
|
- podSelector:
|
||||||
|
matchLabels:
|
||||||
|
app: ins-landing-page
|
||||||
|
ports:
|
||||||
|
- protocol: TCP
|
||||||
|
port: 5432
|
||||||
|
---
|
||||||
# cert-manager's HTTP-01 solver pod: Traefik must reach it, or the certificate cannot be issued
|
# cert-manager's HTTP-01 solver pod: Traefik must reach it, or the certificate cannot be issued
|
||||||
# or renewed.
|
# or renewed.
|
||||||
apiVersion: networking.k8s.io/v1
|
apiVersion: networking.k8s.io/v1
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
# EXAMPLE ONLY - never commit real values. Create the real Secret on the cluster:
|
||||||
|
# microk8s kubectl -n ins-landing-page create secret generic ins-landing-page-db \
|
||||||
|
# --from-literal=POSTGRES_PASSWORD="$(openssl rand -hex 24)"
|
||||||
|
# The password is embedded in a postgres:// URL, so use URL-safe characters (hex is).
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Secret
|
||||||
|
metadata:
|
||||||
|
name: ins-landing-page-db
|
||||||
|
namespace: ins-landing-page
|
||||||
|
type: Opaque
|
||||||
|
stringData:
|
||||||
|
POSTGRES_PASSWORD: change-me
|
||||||
Generated
+162
@@ -0,0 +1,162 @@
|
|||||||
|
{
|
||||||
|
"name": "ins-landing-page",
|
||||||
|
"lockfileVersion": 3,
|
||||||
|
"requires": true,
|
||||||
|
"packages": {
|
||||||
|
"": {
|
||||||
|
"name": "ins-landing-page",
|
||||||
|
"dependencies": {
|
||||||
|
"pg": "8.23.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=22.13"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/pg": {
|
||||||
|
"version": "8.23.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/pg/-/pg-8.23.1.tgz",
|
||||||
|
"integrity": "sha512-aL96AHANtWjPLDOLqnhx+ngp9+UK7ETEU8VJrDCGvsSSi/mGLcWYsS6Herg7lmaBJe4uwrfqsa7gTEFaSizDoQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"pg-connection-string": "^2.14.1",
|
||||||
|
"pg-pool": "^3.14.0",
|
||||||
|
"pg-protocol": "^1.16.1",
|
||||||
|
"pg-types": "2.2.0",
|
||||||
|
"pgpass": "1.0.5"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 16.0.0"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"pg-cloudflare": "^1.4.1"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"pg-native": ">=3.0.1"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"pg-native": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/pg-cloudflare": {
|
||||||
|
"version": "1.4.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.4.1.tgz",
|
||||||
|
"integrity": "sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"node_modules/pg-connection-string": {
|
||||||
|
"version": "2.14.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.14.1.tgz",
|
||||||
|
"integrity": "sha512-qR3kGNPBLpCNtz0evbKA0Y/MRFXwSSdT+pTJvYp/bXTcReZbvX1kzF0IyTc1QnxqF7AZbOeBhNL8R5mYQZV/MA==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/pg-int8": {
|
||||||
|
"version": "1.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz",
|
||||||
|
"integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==",
|
||||||
|
"license": "ISC",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=4.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/pg-pool": {
|
||||||
|
"version": "3.14.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.14.0.tgz",
|
||||||
|
"integrity": "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"peerDependencies": {
|
||||||
|
"pg": ">=8.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/pg-protocol": {
|
||||||
|
"version": "1.16.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.16.1.tgz",
|
||||||
|
"integrity": "sha512-p9VOFMiHB/ZbJATetbg+99PxssTVSQRnyuPSQ67mN1+1KBOjZaZ83ZQzltnxPhJwSsC3nwVjJ10DVJlerbFzLg==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/pg-types": {
|
||||||
|
"version": "2.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz",
|
||||||
|
"integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"pg-int8": "1.0.1",
|
||||||
|
"postgres-array": "~2.0.0",
|
||||||
|
"postgres-bytea": "~1.0.0",
|
||||||
|
"postgres-date": "~1.0.4",
|
||||||
|
"postgres-interval": "^1.1.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/pgpass": {
|
||||||
|
"version": "1.0.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz",
|
||||||
|
"integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"split2": "^4.1.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/postgres-array": {
|
||||||
|
"version": "2.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
|
||||||
|
"integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/postgres-bytea": {
|
||||||
|
"version": "1.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz",
|
||||||
|
"integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.10.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/postgres-date": {
|
||||||
|
"version": "1.0.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz",
|
||||||
|
"integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.10.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/postgres-interval": {
|
||||||
|
"version": "1.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz",
|
||||||
|
"integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"xtend": "^4.0.0"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.10.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/split2": {
|
||||||
|
"version": "4.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
|
||||||
|
"integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",
|
||||||
|
"license": "ISC",
|
||||||
|
"engines": {
|
||||||
|
"node": ">= 10.x"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/xtend": {
|
||||||
|
"version": "4.0.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
|
||||||
|
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.4"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+6
-1
@@ -1,9 +1,14 @@
|
|||||||
{
|
{
|
||||||
"name": "ins-landing-page",
|
"name": "ins-landing-page",
|
||||||
"private": true,
|
"private": true,
|
||||||
"engines": { "node": ">=22.13" },
|
"engines": {
|
||||||
|
"node": ">=22.13"
|
||||||
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "node server.js",
|
"start": "node server.js",
|
||||||
"test": "node --test"
|
"test": "node --test"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"pg": "8.23.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
const http = require('node:http');
|
const http = require('node:http');
|
||||||
const fs = require('node:fs');
|
const fs = require('node:fs');
|
||||||
const path = require('node:path');
|
const path = require('node:path');
|
||||||
const { DatabaseSync } = require('node:sqlite');
|
const { Pool } = require('pg');
|
||||||
|
|
||||||
const MAX_BODY = 10 * 1024;
|
const MAX_BODY = 10 * 1024;
|
||||||
const REQUIRED = ['name', 'email', 'phone', 'company'];
|
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 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'] };
|
const PAGES = { '/': ['index.html', 'text/html; charset=utf-8'], '/logo.png': ['logo.png', 'image/png'] };
|
||||||
|
|
||||||
function openDb(dbPath) {
|
// Kept identical to docs/schema.sql (a test compares the two).
|
||||||
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
const SCHEMA = `CREATE TABLE IF NOT EXISTS leads (
|
||||||
const db = new DatabaseSync(dbPath);
|
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||||
// WAL: an export (reader) never blocks inserts. busy_timeout blocks the event loop while waiting,
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
// ponytail: fine for one low-traffic pod; move to Postgres if this ever needs concurrency.
|
name TEXT NOT NULL,
|
||||||
db.exec('PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;');
|
email TEXT NOT NULL,
|
||||||
db.exec(`CREATE TABLE IF NOT EXISTS leads (
|
phone TEXT NOT NULL,
|
||||||
id INTEGER PRIMARY KEY,
|
company TEXT NOT NULL,
|
||||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
service TEXT,
|
||||||
name TEXT NOT NULL, email TEXT NOT NULL, phone TEXT NOT NULL, company TEXT NOT NULL,
|
referrer TEXT,
|
||||||
service TEXT, referrer TEXT,
|
utm_source TEXT,
|
||||||
utm_source TEXT, utm_medium TEXT, utm_campaign TEXT
|
utm_medium TEXT,
|
||||||
)`);
|
utm_campaign TEXT
|
||||||
return db;
|
)`;
|
||||||
}
|
|
||||||
|
|
||||||
function validate(lead) {
|
function validate(lead) {
|
||||||
for (const f of REQUIRED) {
|
for (const f of REQUIRED) {
|
||||||
@@ -56,7 +55,7 @@ function readBody(req) {
|
|||||||
const chunks = [];
|
const chunks = [];
|
||||||
req.on('data', (c) => {
|
req.on('data', (c) => {
|
||||||
size += c.length;
|
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 }));
|
if (size > MAX_BODY) reject(Object.assign(new Error('too large'), { status: 413 }));
|
||||||
else chunks.push(c);
|
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
|
// load static files up front: a missing file fails at startup instead of crashing on a request
|
||||||
const files = {};
|
const files = {};
|
||||||
for (const [url, [file, type]] of Object.entries(PAGES)) {
|
for (const [url, [file, type]] of Object.entries(PAGES)) {
|
||||||
files[url] = { body: fs.readFileSync(path.join(__dirname, 'public', file)), type };
|
files[url] = { body: fs.readFileSync(path.join(__dirname, 'public', file)), type };
|
||||||
}
|
}
|
||||||
const db = openDb(dbPath);
|
const pool = new Pool({ connectionString: databaseUrl, max: 5, connectionTimeoutMillis: 5000 });
|
||||||
const insert = db.prepare(`INSERT INTO leads
|
// an idle connection dropped by Postgres (restart, failover) must not crash the process
|
||||||
(name, email, phone, company, service, referrer, utm_source, utm_medium, utm_campaign)
|
pool.on('error', (e) => console.error('postgres pool error:', e.message));
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
try {
|
||||||
|
await pool.query(SCHEMA);
|
||||||
|
} catch (e) {
|
||||||
|
await pool.end();
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
const server = http.createServer(async (req, res) => {
|
const server = http.createServer(async (req, res) => {
|
||||||
const url = req.url.split('?')[0];
|
const url = req.url.split('?')[0];
|
||||||
@@ -96,8 +100,11 @@ function createServer(dbPath) {
|
|||||||
if (error) return send(res, 400, { error });
|
if (error) return send(res, 400, { error });
|
||||||
try {
|
try {
|
||||||
const t = (f) => (lead[f] ? lead[f].trim() : null);
|
const t = (f) => (lead[f] ? lead[f].trim() : null);
|
||||||
insert.run(t('name'), t('email'), t('phone'), t('company'), t('service'),
|
await pool.query(`INSERT INTO leads
|
||||||
t('referrer'), t('utm_source'), t('utm_medium'), t('utm_campaign'));
|
(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) {
|
} catch (e) {
|
||||||
console.error('lead insert failed:', e.message);
|
console.error('lead insert failed:', e.message);
|
||||||
return send(res, 500, { error: 'Could not save, please try again' });
|
return send(res, 500, { error: 'Could not save, please try again' });
|
||||||
@@ -106,7 +113,7 @@ function createServer(dbPath) {
|
|||||||
}
|
}
|
||||||
send(res, 404, { error: 'Not found' });
|
send(res, 404, { error: 'Not found' });
|
||||||
});
|
});
|
||||||
server.on('close', () => db.close());
|
server.on('close', () => pool.end());
|
||||||
return server;
|
return server;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -114,8 +121,17 @@ module.exports = { createServer };
|
|||||||
|
|
||||||
if (require.main === module) {
|
if (require.main === module) {
|
||||||
const port = Number(process.env.PORT ?? 3000);
|
const port = Number(process.env.PORT ?? 3000);
|
||||||
const server = createServer(process.env.DB_PATH || path.join(__dirname, 'data', 'leads.db'));
|
if (!process.env.DATABASE_URL) {
|
||||||
server.listen(port, () => console.log(`listening on :${port}`));
|
console.error('DATABASE_URL is not set');
|
||||||
// node as PID 1 ignores SIGTERM by default; exit cleanly so k8s rollouts don't wait 30s
|
process.exit(1);
|
||||||
process.on('SIGTERM', () => server.close(() => process.exit(0)));
|
}
|
||||||
|
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);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
+50
-47
@@ -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 { test, before, after } = require('node:test');
|
||||||
const assert = require('node:assert');
|
const assert = require('node:assert');
|
||||||
const fs = require('node:fs');
|
const fs = require('node:fs');
|
||||||
const os = require('node:os');
|
const os = require('node:os');
|
||||||
const path = require('node:path');
|
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 { createServer } = require('./server');
|
||||||
|
|
||||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ins-leads-'));
|
const adminUrl = process.env.TEST_DATABASE_URL;
|
||||||
const dbPath = path.join(dir, 'leads.db');
|
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;
|
let server, base;
|
||||||
|
|
||||||
before(async () => {
|
before(async () => {
|
||||||
server = createServer(dbPath);
|
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||||
|
server = await createServer(dbUrl);
|
||||||
await new Promise((r) => server.listen(0, r));
|
await new Promise((r) => server.listen(0, r));
|
||||||
base = `http://127.0.0.1:${server.address().port}`;
|
base = `http://127.0.0.1:${server.address().port}`;
|
||||||
});
|
});
|
||||||
after(() => {
|
after(async () => {
|
||||||
server.close();
|
await new Promise((r) => server.close(r));
|
||||||
fs.rmSync(dir, { recursive: true, force: true });
|
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
|
||||||
|
await admin.end();
|
||||||
});
|
});
|
||||||
|
|
||||||
const valid = {
|
const valid = {
|
||||||
@@ -33,16 +47,11 @@ const valid = {
|
|||||||
const post = (body) =>
|
const post = (body) =>
|
||||||
fetch(`${base}/api/leads`, {
|
fetch(`${base}/api/leads`, {
|
||||||
method: 'POST',
|
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),
|
body: typeof body === 'string' ? body : JSON.stringify(body),
|
||||||
});
|
});
|
||||||
|
|
||||||
const rows = () => {
|
const rows = async () => (await admin.query(`SELECT * FROM ${schema}.leads ORDER BY id`)).rows;
|
||||||
const db = new DatabaseSync(dbPath);
|
|
||||||
const r = db.prepare('SELECT * FROM leads').all();
|
|
||||||
db.close();
|
|
||||||
return r;
|
|
||||||
};
|
|
||||||
|
|
||||||
test('serves the landing page', async () => {
|
test('serves the landing page', async () => {
|
||||||
const res = await fetch(`${base}/`);
|
const res = await fetch(`${base}/`);
|
||||||
@@ -53,22 +62,22 @@ test('serves the landing page', async () => {
|
|||||||
test('valid lead is stored', async () => {
|
test('valid lead is stored', async () => {
|
||||||
const res = await post(valid);
|
const res = await post(valid);
|
||||||
assert.strictEqual(res.status, 201);
|
assert.strictEqual(res.status, 201);
|
||||||
const r = rows();
|
const r = await rows();
|
||||||
assert.strictEqual(r.length, 1);
|
assert.strictEqual(r.length, 1);
|
||||||
assert.strictEqual(r[0].name, valid.name);
|
assert.strictEqual(r[0].name, valid.name);
|
||||||
assert.strictEqual(r[0].company, valid.company);
|
assert.strictEqual(r[0].company, valid.company);
|
||||||
assert.strictEqual(r[0].service, 'Cloud IP PABX');
|
assert.strictEqual(r[0].service, 'Cloud IP PABX');
|
||||||
assert.strictEqual(r[0].utm_source, 'google');
|
assert.strictEqual(r[0].utm_source, 'google');
|
||||||
assert.strictEqual(r[0].referrer, 'https://www.google.com/');
|
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 () => {
|
test('missing required field is rejected', async () => {
|
||||||
const before = rows().length;
|
const before = (await rows()).length;
|
||||||
const res = await post({ ...valid, phone: '' });
|
const res = await post({ ...valid, phone: '' });
|
||||||
assert.strictEqual(res.status, 400);
|
assert.strictEqual(res.status, 400);
|
||||||
assert.ok((await res.json()).error);
|
assert.ok((await res.json()).error);
|
||||||
assert.strictEqual(rows().length, before);
|
assert.strictEqual((await rows()).length, before);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('invalid email is rejected', async () => {
|
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 () => {
|
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' });
|
const res = await post({ ...valid, website: 'http://spam.example' });
|
||||||
assert.strictEqual(res.status, 200);
|
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', async () => {
|
||||||
|
|
||||||
test('missing page file fails at startup, not on a request', () => {
|
|
||||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ins-nopage-'));
|
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ins-nopage-'));
|
||||||
fs.copyFileSync(path.join(__dirname, 'server.js'), path.join(tmp, 'server.js'));
|
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'));
|
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 });
|
fs.rmSync(tmp, { recursive: true, force: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
test('insert waits for a lock held by another process (e.g. an export)', async () => {
|
test('unreachable database fails at startup', async () => {
|
||||||
const lock = spawn(process.execPath, ['--disable-warning=ExperimentalWarning', '-e', `
|
await assert.rejects(() => createServer('postgres://nobody:nothing@127.0.0.1:1/none'));
|
||||||
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('exits promptly on SIGTERM', async () => {
|
test('exits promptly on SIGTERM', async () => {
|
||||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ins-term-'));
|
const child = spawn(process.execPath, [path.join(__dirname, 'server.js')], {
|
||||||
const child = spawn(process.execPath, ['--disable-warning=ExperimentalWarning', path.join(__dirname, 'server.js')], {
|
env: { ...process.env, PORT: '0', DATABASE_URL: dbUrl },
|
||||||
env: { ...process.env, PORT: '0', DB_PATH: path.join(tmp, 'leads.db') },
|
|
||||||
});
|
});
|
||||||
await new Promise((r) => child.stdout.once('data', r));
|
await new Promise((r) => child.stdout.once('data', r));
|
||||||
const start = Date.now();
|
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)));
|
const code = await new Promise((r) => child.on('exit', (c) => r(c)));
|
||||||
assert.strictEqual(code, 0);
|
assert.strictEqual(code, 0);
|
||||||
assert.ok(Date.now() - start < 2000);
|
assert.ok(Date.now() - start < 2000);
|
||||||
fs.rmSync(tmp, { recursive: true, force: true });
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test('docs/schema.sql matches the table the server creates', () => {
|
test('docs/schema.sql matches the table the server creates', async () => {
|
||||||
const cols = (db) => db.prepare('PRAGMA table_info(leads)').all().map((c) => [c.name, c.type, c.notnull, c.dflt_value, c.pk]);
|
const docSchema = `${schema}_doc`;
|
||||||
const fromDoc = new DatabaseSync(':memory:');
|
const cols = async (s) => (await admin.query(
|
||||||
fromDoc.exec(fs.readFileSync(path.join(__dirname, 'docs', 'schema.sql'), 'utf8'));
|
`SELECT column_name, data_type, is_nullable, column_default, is_identity
|
||||||
const fromServer = new DatabaseSync(dbPath, { readOnly: true });
|
FROM information_schema.columns WHERE table_schema = $1 AND table_name = 'leads' ORDER BY ordinal_position`, [s])).rows;
|
||||||
assert.deepStrictEqual(cols(fromDoc), cols(fromServer));
|
const doc = new Pool({ connectionString: withSchema(docSchema) });
|
||||||
fromDoc.close();
|
try {
|
||||||
fromServer.close();
|
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`);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
Reference in new issue
Block a user