From e31c2eabc26b8a800c53670129ca09dc9c2a61c4 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Mon, 16 Nov 2026 20:44:41 +0000 Subject: [PATCH 1/3] docs(repo): add a shop example workspace examples/shop runs Postgres, a migrate init task, a seed init task, an API and a web app, served over HTTPS on *.shop.local. It shows init tasks in a dependency chain, an extraCompose file with a health check, readiness probes and service discovery through LO1_SERVICE_*_PROXY_URL. The seed truncates before inserting, so `lo1 restart seed` resets the data. A CLI test validates every example's lo1.yaml and dependency graph. --- examples/shop/.gitignore | 2 + examples/shop/README.md | 48 +++++++ examples/shop/api/db.js | 5 + examples/shop/api/migrate.js | 13 ++ examples/shop/api/package-lock.json | 159 +++++++++++++++++++++ examples/shop/api/package.json | 8 ++ examples/shop/api/seed.js | 17 +++ examples/shop/api/server.js | 28 ++++ examples/shop/infra.compose.yaml | 14 ++ examples/shop/lo1.yaml | 54 +++++++ examples/shop/web/index.html | 31 ++++ examples/shop/web/server.js | 16 +++ packages/cli/tests/config/examples.test.ts | 24 ++++ 13 files changed, 419 insertions(+) create mode 100644 examples/shop/.gitignore create mode 100644 examples/shop/README.md create mode 100644 examples/shop/api/db.js create mode 100644 examples/shop/api/migrate.js create mode 100644 examples/shop/api/package-lock.json create mode 100644 examples/shop/api/package.json create mode 100644 examples/shop/api/seed.js create mode 100644 examples/shop/api/server.js create mode 100644 examples/shop/infra.compose.yaml create mode 100644 examples/shop/lo1.yaml create mode 100644 examples/shop/web/index.html create mode 100644 examples/shop/web/server.js create mode 100644 packages/cli/tests/config/examples.test.ts diff --git a/examples/shop/.gitignore b/examples/shop/.gitignore new file mode 100644 index 0000000..6a73841 --- /dev/null +++ b/examples/shop/.gitignore @@ -0,0 +1,2 @@ +node_modules/ +.lo1/ diff --git a/examples/shop/README.md b/examples/shop/README.md new file mode 100644 index 0000000..fa008da --- /dev/null +++ b/examples/shop/README.md @@ -0,0 +1,48 @@ +# Shop example + +A small system for trying lo1: a web frontend, an API and Postgres, with a database migration and seed data that run before the API starts. + +``` +postgres (infra.compose.yaml) + └─ migrate (init task) ─ seed (init task) ─ api ─ web +``` + +You need Node.js 24+ and Docker. Run `lo1 doctor` to check. + +## Run it + +```bash +npx degit newstack-cloud/lo1/examples/shop shop +cd shop +lo1 up +``` + +`lo1 up` asks for `sudo` once, to add `api.shop.local` and `web.shop.local` to your hosts file and trust lo1's local certificate authority. It then starts Postgres, runs `migrate` and `seed`, starts the API, waits for its health check, and starts the web app: + +``` + Workspace shop is ready in 4.1s + infrastructure 2.4s · services 1.7s + + Services: + api https://api.shop.local + web https://web.shop.local +``` + +Open https://web.shop.local to see the products, read from Postgres through the API. + +## Things to try + +| Command | What it does | +| ------------------------ | --------------------------------------------------------------- | +| `lo1 status` | Shows each service's health. Exits 0 when everything is up. | +| `lo1 logs api` | Tails the API's log. | +| `lo1 restart seed` | Runs the seed again, putting the products back how they started. | +| `lo1 restart api` | Restarts the API and waits for its health check. | +| `lo1 up --detach` | Starts everything in the background and returns once it's ready. | +| `lo1 down` | Stops everything. Add `--clean` to delete the database volume. | + +## How it fits together + +- [`lo1.yaml`](./lo1.yaml) lists the services. `migrate` and `seed` are init tasks: they run once, in order, and must exit 0 before anything that depends on them starts. +- [`infra.compose.yaml`](./infra.compose.yaml) is an ordinary Docker Compose file for Postgres. lo1 waits for its health check before running the migration. +- The web app finds the API through `LO1_SERVICE_API_PROXY_URL`, which lo1 sets for every service. See [`web/server.js`](./web/server.js). diff --git a/examples/shop/api/db.js b/examples/shop/api/db.js new file mode 100644 index 0000000..6edeb5f --- /dev/null +++ b/examples/shop/api/db.js @@ -0,0 +1,5 @@ +import pg from "pg"; + +export function connect() { + return new pg.Client({ connectionString: process.env.DATABASE_URL }); +} diff --git a/examples/shop/api/migrate.js b/examples/shop/api/migrate.js new file mode 100644 index 0000000..2cf6260 --- /dev/null +++ b/examples/shop/api/migrate.js @@ -0,0 +1,13 @@ +import { connect } from "./db.js"; + +const db = connect(); +await db.connect(); +await db.query(` + CREATE TABLE IF NOT EXISTS products ( + id SERIAL PRIMARY KEY, + name TEXT NOT NULL, + price_pence INTEGER NOT NULL + ) +`); +await db.end(); +console.log("migrations applied"); diff --git a/examples/shop/api/package-lock.json b/examples/shop/api/package-lock.json new file mode 100644 index 0000000..1ae2212 --- /dev/null +++ b/examples/shop/api/package-lock.json @@ -0,0 +1,159 @@ +{ + "name": "shop-api", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "shop-api", + "dependencies": { + "pg": "8.23.1" + } + }, + "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" + } + } + } +} diff --git a/examples/shop/api/package.json b/examples/shop/api/package.json new file mode 100644 index 0000000..5f383ec --- /dev/null +++ b/examples/shop/api/package.json @@ -0,0 +1,8 @@ +{ + "name": "shop-api", + "private": true, + "type": "module", + "dependencies": { + "pg": "8.23.1" + } +} diff --git a/examples/shop/api/seed.js b/examples/shop/api/seed.js new file mode 100644 index 0000000..aa50cd4 --- /dev/null +++ b/examples/shop/api/seed.js @@ -0,0 +1,17 @@ +import { connect } from "./db.js"; + +const products = [ + ["Loopback mug", 1200], + ["IPv6 sticker pack", 400], + ["127.0.0.1 hoodie", 3800], +]; + +const db = connect(); +await db.connect(); +// Start from a known state every time, so `lo1 restart seed` resets the data. +await db.query("TRUNCATE products RESTART IDENTITY"); +for (const [name, pricePence] of products) { + await db.query("INSERT INTO products (name, price_pence) VALUES ($1, $2)", [name, pricePence]); +} +await db.end(); +console.log(`seeded ${products.length} products`); diff --git a/examples/shop/api/server.js b/examples/shop/api/server.js new file mode 100644 index 0000000..3f8623b --- /dev/null +++ b/examples/shop/api/server.js @@ -0,0 +1,28 @@ +import { createServer } from "node:http"; +import { connect } from "./db.js"; + +const db = connect(); +await db.connect(); + +function send(res, status, body) { + res.writeHead(status, { + "content-type": "application/json", + // The web app is served from its own domain, so allow it to call the API. + "access-control-allow-origin": "*", + }); + res.end(JSON.stringify(body)); +} + +const server = createServer(async (req, res) => { + if (req.url === "/health") return send(res, 200, { ok: true }); + if (req.url === "/products") { + const { rows } = await db.query("SELECT id, name, price_pence FROM products ORDER BY id"); + return send(res, 200, rows); + } + send(res, 404, { error: "not found" }); +}); + +const port = Number(process.env.PORT ?? 4100); +server.listen(port, () => console.log(`api listening on ${port}`)); + +process.on("SIGTERM", () => server.close(() => db.end().then(() => process.exit(0)))); diff --git a/examples/shop/infra.compose.yaml b/examples/shop/infra.compose.yaml new file mode 100644 index 0000000..847d351 --- /dev/null +++ b/examples/shop/infra.compose.yaml @@ -0,0 +1,14 @@ +services: + postgres: + image: postgres:17-alpine + environment: + POSTGRES_USER: shop + POSTGRES_PASSWORD: shop + POSTGRES_DB: shop + ports: + # An uncommon host port, so it doesn't clash with a local Postgres. + - "54329:5432" + healthcheck: + test: ["CMD", "pg_isready", "-U", "shop"] + interval: 2s + retries: 15 diff --git a/examples/shop/lo1.yaml b/examples/shop/lo1.yaml new file mode 100644 index 0000000..71e963d --- /dev/null +++ b/examples/shop/lo1.yaml @@ -0,0 +1,54 @@ +# yaml-language-server: $schema=https://unpkg.com/@lo1/sdk/schemas/lo1.v1.schema.json +# +# A small shop: Postgres, a migration and seed step, an API and a web frontend. +# Run `lo1 up`, then open https://web.shop.local. +version: "1" +name: shop + +# Postgres, as an ordinary Docker Compose file. +extraCompose: ./infra.compose.yaml + +services: + # Init tasks run once, in dependency order, and must exit 0 before + # anything that depends on them starts. + migrate: + type: service + path: ./api + command: npm install --no-audit --no-fund --loglevel=error && node migrate.js + initTask: true + env: + DATABASE_URL: postgres://shop:shop@localhost:54329/shop + + seed: + type: service + path: ./api + command: node seed.js + initTask: true + dependsOn: [migrate] + env: + DATABASE_URL: postgres://shop:shop@localhost:54329/shop + + api: + type: service + path: ./api + port: 4100 + command: node server.js + readinessProbe: http://localhost:4100/health + dependsOn: [seed] + env: + PORT: "4100" + DATABASE_URL: postgres://shop:shop@localhost:54329/shop + + web: + type: app + path: ./web + port: 4200 + command: node server.js + dependsOn: [api] + env: + PORT: "4200" + +proxy: + tld: local + tls: + enabled: true diff --git a/examples/shop/web/index.html b/examples/shop/web/index.html new file mode 100644 index 0000000..fce6287 --- /dev/null +++ b/examples/shop/web/index.html @@ -0,0 +1,31 @@ + + + + + + lo1 shop + + + +

lo1 shop

+

Products below come from Postgres, through the API, over HTTPS.

+ + + + diff --git a/examples/shop/web/server.js b/examples/shop/web/server.js new file mode 100644 index 0000000..dfc27e2 --- /dev/null +++ b/examples/shop/web/server.js @@ -0,0 +1,16 @@ +import { createServer } from "node:http"; +import { readFile } from "node:fs/promises"; + +// lo1 tells every service where the others are. The browser needs the API's +// public URL, through the proxy, so pass it to the page. +const apiUrl = process.env.LO1_SERVICE_API_PROXY_URL ?? "http://localhost:4100"; +const page = await readFile(new URL("./index.html", import.meta.url), "utf-8"); + +const server = createServer((req, res) => { + res.writeHead(200, { "content-type": "text/html; charset=utf-8" }); + res.end(page.replace("__API_URL__", apiUrl)); +}); + +const port = Number(process.env.PORT ?? 4200); +server.listen(port, () => console.log(`web listening on ${port}, using API at ${apiUrl}`)); +process.on("SIGTERM", () => server.close(() => process.exit(0))); diff --git a/packages/cli/tests/config/examples.test.ts b/packages/cli/tests/config/examples.test.ts new file mode 100644 index 0000000..40f3e0d --- /dev/null +++ b/packages/cli/tests/config/examples.test.ts @@ -0,0 +1,24 @@ +import { describe, it, expect } from "bun:test"; +import { readdirSync } from "node:fs"; +import { join } from "node:path"; +import { loadWorkspaceConfig } from "../../src/config/loader"; +import { buildDag } from "../../src/dag/index"; + +const examplesDir = join(import.meta.dir, "..", "..", "..", "..", "examples"); +const examples = readdirSync(examplesDir, { withFileTypes: true }) + .filter((entry) => entry.isDirectory()) + .map((entry) => entry.name); + +describe("examples", () => { + it("should include at least one example", () => { + expect(examples.length).toBeGreaterThan(0); + }); + + for (const example of examples) { + it(`should have a valid lo1.yaml with no dependency cycles: ${example}`, async () => { + const config = await loadWorkspaceConfig(join(examplesDir, example, "lo1.yaml")); + + expect(() => buildDag(config)).not.toThrow(); + }); + } +}); From 4d0f00cb6b7433a2df43993f964ff7868c1d52f5 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Tue, 17 Nov 2026 09:51:36 +0000 Subject: [PATCH 2/3] chore(ci): exclude the examples from Sonar analysis --- examples/shop/api/db.js | 5 ----- examples/shop/api/migrate.js | 13 ------------- examples/shop/api/seed.js | 17 ----------------- examples/shop/api/server.js | 28 ---------------------------- examples/shop/web/index.html | 31 ------------------------------- examples/shop/web/server.js | 16 ---------------- sonar-project.properties | 4 +++- 7 files changed, 3 insertions(+), 111 deletions(-) delete mode 100644 examples/shop/api/db.js delete mode 100644 examples/shop/api/migrate.js delete mode 100644 examples/shop/api/seed.js delete mode 100644 examples/shop/api/server.js delete mode 100644 examples/shop/web/index.html delete mode 100644 examples/shop/web/server.js diff --git a/examples/shop/api/db.js b/examples/shop/api/db.js deleted file mode 100644 index 6edeb5f..0000000 --- a/examples/shop/api/db.js +++ /dev/null @@ -1,5 +0,0 @@ -import pg from "pg"; - -export function connect() { - return new pg.Client({ connectionString: process.env.DATABASE_URL }); -} diff --git a/examples/shop/api/migrate.js b/examples/shop/api/migrate.js deleted file mode 100644 index 2cf6260..0000000 --- a/examples/shop/api/migrate.js +++ /dev/null @@ -1,13 +0,0 @@ -import { connect } from "./db.js"; - -const db = connect(); -await db.connect(); -await db.query(` - CREATE TABLE IF NOT EXISTS products ( - id SERIAL PRIMARY KEY, - name TEXT NOT NULL, - price_pence INTEGER NOT NULL - ) -`); -await db.end(); -console.log("migrations applied"); diff --git a/examples/shop/api/seed.js b/examples/shop/api/seed.js deleted file mode 100644 index aa50cd4..0000000 --- a/examples/shop/api/seed.js +++ /dev/null @@ -1,17 +0,0 @@ -import { connect } from "./db.js"; - -const products = [ - ["Loopback mug", 1200], - ["IPv6 sticker pack", 400], - ["127.0.0.1 hoodie", 3800], -]; - -const db = connect(); -await db.connect(); -// Start from a known state every time, so `lo1 restart seed` resets the data. -await db.query("TRUNCATE products RESTART IDENTITY"); -for (const [name, pricePence] of products) { - await db.query("INSERT INTO products (name, price_pence) VALUES ($1, $2)", [name, pricePence]); -} -await db.end(); -console.log(`seeded ${products.length} products`); diff --git a/examples/shop/api/server.js b/examples/shop/api/server.js deleted file mode 100644 index 3f8623b..0000000 --- a/examples/shop/api/server.js +++ /dev/null @@ -1,28 +0,0 @@ -import { createServer } from "node:http"; -import { connect } from "./db.js"; - -const db = connect(); -await db.connect(); - -function send(res, status, body) { - res.writeHead(status, { - "content-type": "application/json", - // The web app is served from its own domain, so allow it to call the API. - "access-control-allow-origin": "*", - }); - res.end(JSON.stringify(body)); -} - -const server = createServer(async (req, res) => { - if (req.url === "/health") return send(res, 200, { ok: true }); - if (req.url === "/products") { - const { rows } = await db.query("SELECT id, name, price_pence FROM products ORDER BY id"); - return send(res, 200, rows); - } - send(res, 404, { error: "not found" }); -}); - -const port = Number(process.env.PORT ?? 4100); -server.listen(port, () => console.log(`api listening on ${port}`)); - -process.on("SIGTERM", () => server.close(() => db.end().then(() => process.exit(0)))); diff --git a/examples/shop/web/index.html b/examples/shop/web/index.html deleted file mode 100644 index fce6287..0000000 --- a/examples/shop/web/index.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - lo1 shop - - - -

lo1 shop

-

Products below come from Postgres, through the API, over HTTPS.

- - - - diff --git a/examples/shop/web/server.js b/examples/shop/web/server.js deleted file mode 100644 index dfc27e2..0000000 --- a/examples/shop/web/server.js +++ /dev/null @@ -1,16 +0,0 @@ -import { createServer } from "node:http"; -import { readFile } from "node:fs/promises"; - -// lo1 tells every service where the others are. The browser needs the API's -// public URL, through the proxy, so pass it to the page. -const apiUrl = process.env.LO1_SERVICE_API_PROXY_URL ?? "http://localhost:4100"; -const page = await readFile(new URL("./index.html", import.meta.url), "utf-8"); - -const server = createServer((req, res) => { - res.writeHead(200, { "content-type": "text/html; charset=utf-8" }); - res.end(page.replace("__API_URL__", apiUrl)); -}); - -const port = Number(process.env.PORT ?? 4200); -server.listen(port, () => console.log(`web listening on ${port}, using API at ${apiUrl}`)); -process.on("SIGTERM", () => server.close(() => process.exit(0))); diff --git a/sonar-project.properties b/sonar-project.properties index 6bf37a7..415e75a 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -8,8 +8,10 @@ sonar.tests=packages,plugins sonar.inclusions=packages/*/src/**,plugins/*/src/** sonar.test.inclusions=packages/*/tests/**/*.test.ts,plugins/*/tests/**/*.test.ts -# Exclusions from analysis +# Exclusions from analysis. Examples are sample projects for trying lo1, not +# part of the product, so they stay out even if sonar.sources widens. sonar.exclusions=\ + examples/**,\ **/node_modules/**,\ **/dist/**,\ **/*.js,\ From 944e7a1406e15e774e34a66c9c11cd5a4378a1c3 Mon Sep 17 00:00:00 2001 From: Andre Sutherland Date: Tue, 17 Nov 2026 09:51:37 +0000 Subject: [PATCH 3/3] refactor(repo): lay the shop example out the way a real service would be Each module now has one job and is given its dependencies: config is read once, a router dispatches from a table of routes, a repository holds all the product SQL, migrations are numbered and recorded so each runs once, and the server files only wire things together. The web app serves static files with a content security policy and renders with textContent. The API is tested against a throwaway Postgres started from api/test/compose.yaml, each test file in its own schema, and both services' tests go over real HTTP. --- examples/shop/README.md | 26 ++++++++- examples/shop/api/package-lock.json | 3 + examples/shop/api/package.json | 11 ++++ examples/shop/api/src/app.js | 21 +++++++ examples/shop/api/src/config.js | 19 +++++++ examples/shop/api/src/db.js | 6 ++ examples/shop/api/src/health/routes.js | 17 ++++++ examples/shop/api/src/http/router.js | 34 ++++++++++++ examples/shop/api/src/migrate.js | 13 +++++ .../api/src/migrations/001-create-products.js | 11 ++++ examples/shop/api/src/migrations/index.js | 4 ++ examples/shop/api/src/migrations/run.js | 28 ++++++++++ examples/shop/api/src/products/repository.js | 31 +++++++++++ examples/shop/api/src/products/routes.js | 13 +++++ examples/shop/api/src/products/seed-data.js | 6 ++ examples/shop/api/src/seed.js | 14 +++++ examples/shop/api/src/server.js | 17 ++++++ examples/shop/api/src/transaction.js | 18 ++++++ examples/shop/api/test/api.test.js | 54 ++++++++++++++++++ examples/shop/api/test/compose.yaml | 21 +++++++ examples/shop/api/test/migrations.test.js | 33 +++++++++++ examples/shop/api/test/products.test.js | 46 ++++++++++++++++ examples/shop/api/test/router.test.js | 49 +++++++++++++++++ examples/shop/api/test/support/database.js | 44 +++++++++++++++ examples/shop/api/test/support/http.js | 26 +++++++++ examples/shop/lo1.yaml | 16 +++--- examples/shop/web/package.json | 12 ++++ examples/shop/web/public/app.js | 39 +++++++++++++ examples/shop/web/public/index.html | 15 +++++ examples/shop/web/public/styles.css | 17 ++++++ examples/shop/web/src/config.js | 11 ++++ examples/shop/web/src/handler.js | 53 ++++++++++++++++++ examples/shop/web/src/server.js | 17 ++++++ examples/shop/web/test/handler.test.js | 55 +++++++++++++++++++ 34 files changed, 791 insertions(+), 9 deletions(-) create mode 100644 examples/shop/api/src/app.js create mode 100644 examples/shop/api/src/config.js create mode 100644 examples/shop/api/src/db.js create mode 100644 examples/shop/api/src/health/routes.js create mode 100644 examples/shop/api/src/http/router.js create mode 100644 examples/shop/api/src/migrate.js create mode 100644 examples/shop/api/src/migrations/001-create-products.js create mode 100644 examples/shop/api/src/migrations/index.js create mode 100644 examples/shop/api/src/migrations/run.js create mode 100644 examples/shop/api/src/products/repository.js create mode 100644 examples/shop/api/src/products/routes.js create mode 100644 examples/shop/api/src/products/seed-data.js create mode 100644 examples/shop/api/src/seed.js create mode 100644 examples/shop/api/src/server.js create mode 100644 examples/shop/api/src/transaction.js create mode 100644 examples/shop/api/test/api.test.js create mode 100644 examples/shop/api/test/compose.yaml create mode 100644 examples/shop/api/test/migrations.test.js create mode 100644 examples/shop/api/test/products.test.js create mode 100644 examples/shop/api/test/router.test.js create mode 100644 examples/shop/api/test/support/database.js create mode 100644 examples/shop/api/test/support/http.js create mode 100644 examples/shop/web/package.json create mode 100644 examples/shop/web/public/app.js create mode 100644 examples/shop/web/public/index.html create mode 100644 examples/shop/web/public/styles.css create mode 100644 examples/shop/web/src/config.js create mode 100644 examples/shop/web/src/handler.js create mode 100644 examples/shop/web/src/server.js create mode 100644 examples/shop/web/test/handler.test.js diff --git a/examples/shop/README.md b/examples/shop/README.md index fa008da..b0a8b1a 100644 --- a/examples/shop/README.md +++ b/examples/shop/README.md @@ -45,4 +45,28 @@ Open https://web.shop.local to see the products, read from Postgres through the - [`lo1.yaml`](./lo1.yaml) lists the services. `migrate` and `seed` are init tasks: they run once, in order, and must exit 0 before anything that depends on them starts. - [`infra.compose.yaml`](./infra.compose.yaml) is an ordinary Docker Compose file for Postgres. lo1 waits for its health check before running the migration. -- The web app finds the API through `LO1_SERVICE_API_PROXY_URL`, which lo1 sets for every service. See [`web/server.js`](./web/server.js). +- The web app finds the API through `LO1_SERVICE_API_PROXY_URL`, which lo1 sets for every service, and the API only accepts browser requests from the web app's URL, `LO1_SERVICE_WEB_PROXY_URL`. See [`web/src/config.js`](./web/src/config.js) and [`api/src/config.js`](./api/src/config.js). + +## How the code is organised + +The services are small, but they're laid out the way a real one would be. Each module has one job, and each depends only on what it's given. + +| File | Its one job | +| --- | --- | +| [`api/src/config.js`](./api/src/config.js) | Reads the environment, once. Nothing else touches `process.env`. | +| [`api/src/server.js`](./api/src/server.js) | The composition root: creates the pool and starts the server. | +| [`api/src/app.js`](./api/src/app.js) | Wires repositories and routes together into a request handler. | +| [`api/src/http/router.js`](./api/src/http/router.js) | Dispatches requests to routes. A new endpoint is a new route; the router doesn't change. | +| [`api/src/products/`](./api/src/products/) | The product routes, and the repository that holds all the product SQL. | +| [`api/src/migrations/`](./api/src/migrations/) | Numbered migrations, recorded in `schema_migrations` so each runs once. To change the schema, add a file. | +| [`web/src/handler.js`](./web/src/handler.js) | Serves the page's files and `/config.json`, with a content security policy. | +| [`web/public/app.js`](./web/public/app.js) | Fetches the products and renders them with `textContent`, never `innerHTML`. | + +## Run the tests + +```bash +cd api && npm install && npm test # starts a throwaway Postgres in Docker first +cd web && npm test +``` + +The API's tests run against real Postgres, from [`api/test/compose.yaml`](./api/test/compose.yaml), on port 54330, so they can run alongside `lo1 up`. Each test file works in its own schema. Stop the test database with `npm run test:db:down`. diff --git a/examples/shop/api/package-lock.json b/examples/shop/api/package-lock.json index 1ae2212..428be8c 100644 --- a/examples/shop/api/package-lock.json +++ b/examples/shop/api/package-lock.json @@ -7,6 +7,9 @@ "name": "shop-api", "dependencies": { "pg": "8.23.1" + }, + "engines": { + "node": ">=24" } }, "node_modules/pg": { diff --git a/examples/shop/api/package.json b/examples/shop/api/package.json index 5f383ec..2c92b45 100644 --- a/examples/shop/api/package.json +++ b/examples/shop/api/package.json @@ -2,6 +2,17 @@ "name": "shop-api", "private": true, "type": "module", + "engines": { + "node": ">=24" + }, + "scripts": { + "start": "node src/server.js", + "migrate": "node src/migrate.js", + "seed": "node src/seed.js", + "test": "npm run test:db:up --silent && node --test \"test/**/*.test.js\"", + "test:db:up": "docker compose -f test/compose.yaml up -d --wait --quiet-pull", + "test:db:down": "docker compose -f test/compose.yaml down -v" + }, "dependencies": { "pg": "8.23.1" } diff --git a/examples/shop/api/src/app.js b/examples/shop/api/src/app.js new file mode 100644 index 0000000..2ff5204 --- /dev/null +++ b/examples/shop/api/src/app.js @@ -0,0 +1,21 @@ +import { createRouter } from "./http/router.js"; +import { healthRoutes } from "./health/routes.js"; +import { createProductRepository } from "./products/repository.js"; +import { productRoutes } from "./products/routes.js"; + +/** + * Wires the API together: repositories on top of the pool, routes on top of + * the repositories. Returns a Node request handler. The pool and settings + * come from the caller, so tests can run the real API on a test database. + */ +export function createApp({ pool, allowedOrigin, onError }) { + const products = createProductRepository(pool); + + return createRouter( + [...healthRoutes(() => pool.query("SELECT 1")), ...productRoutes(products)], + { + headers: { "access-control-allow-origin": allowedOrigin, vary: "Origin" }, + onError, + }, + ); +} diff --git a/examples/shop/api/src/config.js b/examples/shop/api/src/config.js new file mode 100644 index 0000000..7d8d25f --- /dev/null +++ b/examples/shop/api/src/config.js @@ -0,0 +1,19 @@ +/** + * Reads the API's settings from the environment, once. The rest of the code + * is given these values and never reads `process.env` itself. + */ +export function loadConfig(env = process.env) { + return { + port: Number(env.PORT ?? 4100), + databaseUrl: required(env, "DATABASE_URL"), + // lo1 gives every service each other service's URLs. The web app's public + // URL is the only origin allowed to call this API from a browser. + allowedOrigin: env.LO1_SERVICE_WEB_PROXY_URL ?? "http://localhost:4200", + }; +} + +function required(env, name) { + const value = env[name]; + if (!value) throw new Error(`${name} is not set`); + return value; +} diff --git a/examples/shop/api/src/db.js b/examples/shop/api/src/db.js new file mode 100644 index 0000000..479043d --- /dev/null +++ b/examples/shop/api/src/db.js @@ -0,0 +1,6 @@ +import pg from "pg"; + +/** A connection pool for Postgres. Everything else takes the pool as a parameter. */ +export function createPool(databaseUrl) { + return new pg.Pool({ connectionString: databaseUrl, max: 5 }); +} diff --git a/examples/shop/api/src/health/routes.js b/examples/shop/api/src/health/routes.js new file mode 100644 index 0000000..2ab2da9 --- /dev/null +++ b/examples/shop/api/src/health/routes.js @@ -0,0 +1,17 @@ +/** + * `GET /health`, which lo1's readiness probe calls. It only reports healthy + * when the database answers, so lo1 waits for a working API, not just a + * listening one. + */ +export function healthRoutes(checkDatabase) { + return [ + { + method: "GET", + path: "/health", + handle: async () => { + await checkDatabase(); + return { body: { ok: true } }; + }, + }, + ]; +} diff --git a/examples/shop/api/src/http/router.js b/examples/shop/api/src/http/router.js new file mode 100644 index 0000000..36fef07 --- /dev/null +++ b/examples/shop/api/src/http/router.js @@ -0,0 +1,34 @@ +/** + * Builds a Node request handler from a list of routes. + * + * A route is `{ method, path, handle }`. `handle(req)` returns + * `{ status?, body }` and never touches the response, so a route can be + * tested without a server. Adding an endpoint means adding a route; the + * router itself doesn't change. + */ +export function createRouter(routes, { headers = {}, onError = console.error } = {}) { + const byKey = new Map(routes.map((route) => [routeKey(route.method, route.path), route])); + + return async (req, res) => { + const { pathname } = new URL(req.url, "http://localhost"); + const route = byKey.get(routeKey(req.method, pathname)); + if (!route) return sendJson(res, 404, { error: "not found" }, headers); + + try { + const { status = 200, body } = await route.handle(req); + sendJson(res, status, body, headers); + } catch (err) { + onError(err); + sendJson(res, 500, { error: "internal error" }, headers); + } + }; +} + +function routeKey(method, path) { + return `${method} ${path}`; +} + +function sendJson(res, status, body, headers) { + res.writeHead(status, { ...headers, "content-type": "application/json; charset=utf-8" }); + res.end(JSON.stringify(body)); +} diff --git a/examples/shop/api/src/migrate.js b/examples/shop/api/src/migrate.js new file mode 100644 index 0000000..3a6e9d6 --- /dev/null +++ b/examples/shop/api/src/migrate.js @@ -0,0 +1,13 @@ +import { loadConfig } from "./config.js"; +import { createPool } from "./db.js"; +import { migrations } from "./migrations/index.js"; +import { runMigrations } from "./migrations/run.js"; + +// Run by lo1 as the `migrate` init task, before `seed` and the API start. +const pool = createPool(loadConfig().databaseUrl); +try { + await runMigrations(pool, migrations); + console.log("migrations applied"); +} finally { + await pool.end(); +} diff --git a/examples/shop/api/src/migrations/001-create-products.js b/examples/shop/api/src/migrations/001-create-products.js new file mode 100644 index 0000000..acd54e7 --- /dev/null +++ b/examples/shop/api/src/migrations/001-create-products.js @@ -0,0 +1,11 @@ +export const name = "001-create-products"; + +export async function up(db) { + await db.query(` + CREATE TABLE IF NOT EXISTS products ( + id SERIAL PRIMARY KEY, + name TEXT NOT NULL, + price_pence INTEGER NOT NULL CHECK (price_pence >= 0) + ) + `); +} diff --git a/examples/shop/api/src/migrations/index.js b/examples/shop/api/src/migrations/index.js new file mode 100644 index 0000000..88e3a11 --- /dev/null +++ b/examples/shop/api/src/migrations/index.js @@ -0,0 +1,4 @@ +import * as createProducts from "./001-create-products.js"; + +/** Every migration, in the order they run. To change the schema, add a file and list it here. */ +export const migrations = [createProducts]; diff --git a/examples/shop/api/src/migrations/run.js b/examples/shop/api/src/migrations/run.js new file mode 100644 index 0000000..f5c00a4 --- /dev/null +++ b/examples/shop/api/src/migrations/run.js @@ -0,0 +1,28 @@ +import { withTransaction } from "../transaction.js"; + +/** + * Applies the migrations that haven't run yet, each in its own transaction, + * and records them in `schema_migrations` so they never run twice. + * Returns the names of the migrations it applied. + */ +export async function runMigrations(pool, migrations) { + await pool.query(` + CREATE TABLE IF NOT EXISTS schema_migrations ( + name TEXT PRIMARY KEY, + applied_at TIMESTAMPTZ NOT NULL DEFAULT now() + ) + `); + const { rows } = await pool.query("SELECT name FROM schema_migrations"); + const done = new Set(rows.map((row) => row.name)); + + const applied = []; + for (const migration of migrations) { + if (done.has(migration.name)) continue; + await withTransaction(pool, async (client) => { + await migration.up(client); + await client.query("INSERT INTO schema_migrations (name) VALUES ($1)", [migration.name]); + }); + applied.push(migration.name); + } + return applied; +} diff --git a/examples/shop/api/src/products/repository.js b/examples/shop/api/src/products/repository.js new file mode 100644 index 0000000..923c258 --- /dev/null +++ b/examples/shop/api/src/products/repository.js @@ -0,0 +1,31 @@ +import { withTransaction } from "../transaction.js"; + +/** + * Reads and writes products in Postgres. The routes and the seed script use + * these methods, so they never need to know about SQL or column names. + */ +export function createProductRepository(pool) { + return { + async list() { + const { rows } = await pool.query("SELECT id, name, price_pence FROM products ORDER BY id"); + return rows.map(toProduct); + }, + + /** Replaces every product in one transaction, so nobody sees a half-written table. */ + async replaceAll(products) { + await withTransaction(pool, async (client) => { + await client.query("TRUNCATE products RESTART IDENTITY"); + for (const product of products) { + await client.query("INSERT INTO products (name, price_pence) VALUES ($1, $2)", [ + product.name, + product.pricePence, + ]); + } + }); + }, + }; +} + +function toProduct(row) { + return { id: row.id, name: row.name, pricePence: row.price_pence }; +} diff --git a/examples/shop/api/src/products/routes.js b/examples/shop/api/src/products/routes.js new file mode 100644 index 0000000..891f007 --- /dev/null +++ b/examples/shop/api/src/products/routes.js @@ -0,0 +1,13 @@ +/** + * The product endpoints. They depend on a repository with a `list()` method, + * not on Postgres, so tests can pass in a fake one. + */ +export function productRoutes(products) { + return [ + { + method: "GET", + path: "/products", + handle: async () => ({ body: await products.list() }), + }, + ]; +} diff --git a/examples/shop/api/src/products/seed-data.js b/examples/shop/api/src/products/seed-data.js new file mode 100644 index 0000000..6b9f33c --- /dev/null +++ b/examples/shop/api/src/products/seed-data.js @@ -0,0 +1,6 @@ +/** The products `lo1 restart seed` puts back. */ +export const seedProducts = [ + { name: "Loopback mug", pricePence: 1200 }, + { name: "IPv6 sticker pack", pricePence: 400 }, + { name: "127.0.0.1 hoodie", pricePence: 3800 }, +]; diff --git a/examples/shop/api/src/seed.js b/examples/shop/api/src/seed.js new file mode 100644 index 0000000..f72885b --- /dev/null +++ b/examples/shop/api/src/seed.js @@ -0,0 +1,14 @@ +import { loadConfig } from "./config.js"; +import { createPool } from "./db.js"; +import { createProductRepository } from "./products/repository.js"; +import { seedProducts } from "./products/seed-data.js"; + +// Run by lo1 as the `seed` init task. It replaces the data every time, so +// `lo1 restart seed` puts the products back how they started. +const pool = createPool(loadConfig().databaseUrl); +try { + await createProductRepository(pool).replaceAll(seedProducts); + console.log(`seeded ${seedProducts.length} products`); +} finally { + await pool.end(); +} diff --git a/examples/shop/api/src/server.js b/examples/shop/api/src/server.js new file mode 100644 index 0000000..1ea257e --- /dev/null +++ b/examples/shop/api/src/server.js @@ -0,0 +1,17 @@ +import { createServer } from "node:http"; +import { createApp } from "./app.js"; +import { loadConfig } from "./config.js"; +import { createPool } from "./db.js"; + +// The composition root: the one place that reads the settings and creates +// the real resources. Everything below it takes them as parameters. +const config = loadConfig(); +const pool = createPool(config.databaseUrl); + +const server = createServer(createApp({ pool, allowedOrigin: config.allowedOrigin })); +server.listen(config.port, () => console.log(`api listening on ${config.port}`)); + +// lo1 sends SIGTERM on `lo1 down` and `lo1 restart`; finish in-flight requests first. +for (const signal of ["SIGTERM", "SIGINT"]) { + process.once(signal, () => server.close(() => pool.end().finally(() => process.exit(0)))); +} diff --git a/examples/shop/api/src/transaction.js b/examples/shop/api/src/transaction.js new file mode 100644 index 0000000..9863a7a --- /dev/null +++ b/examples/shop/api/src/transaction.js @@ -0,0 +1,18 @@ +/** + * Runs `work` inside a transaction on one pooled connection: committed if it + * succeeds, rolled back if it throws. + */ +export async function withTransaction(pool, work) { + const client = await pool.connect(); + try { + await client.query("BEGIN"); + const result = await work(client); + await client.query("COMMIT"); + return result; + } catch (err) { + await client.query("ROLLBACK"); + throw err; + } finally { + client.release(); + } +} diff --git a/examples/shop/api/test/api.test.js b/examples/shop/api/test/api.test.js new file mode 100644 index 0000000..a637dfd --- /dev/null +++ b/examples/shop/api/test/api.test.js @@ -0,0 +1,54 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import pg from "pg"; +import { createApp } from "../src/app.js"; +import { createProductRepository } from "../src/products/repository.js"; +import { seedProducts } from "../src/products/seed-data.js"; +import { useTestDatabase } from "./support/database.js"; +import { useServer } from "./support/http.js"; + +const pool = useTestDatabase({ migrated: true }); +const request = useServer(() => + createApp({ pool: pool(), allowedOrigin: "https://web.shop.local", onError: () => {} }), +); + +describe("the API, against Postgres", () => { + it("serves the seeded products to the web app's origin", async () => { + await createProductRepository(pool()).replaceAll(seedProducts); + + const res = await request("/products"); + + assert.equal(res.status, 200); + assert.equal(res.headers.get("access-control-allow-origin"), "https://web.shop.local"); + const products = await res.json(); + assert.deepEqual( + products.map(({ name, pricePence }) => ({ name, pricePence })), + seedProducts, + ); + }); + + it("is healthy while the database answers", async () => { + const res = await request("/health"); + + assert.equal(res.status, 200); + assert.deepEqual(await res.json(), { ok: true }); + }); +}); + +describe("the API's health check without a database", () => { + // Nothing listens on port 1, so every query fails. + const unreachable = new pg.Pool({ + connectionString: "postgres://shop:shop@127.0.0.1:1/shop", + connectionTimeoutMillis: 500, + }); + const requestUnhealthy = useServer(() => + createApp({ pool: unreachable, allowedOrigin: "https://web.shop.local", onError: () => {} }), + ); + + it("fails, so lo1's readiness probe keeps waiting", async () => { + const res = await requestUnhealthy("/health"); + + assert.equal(res.status, 500); + await unreachable.end(); + }); +}); diff --git a/examples/shop/api/test/compose.yaml b/examples/shop/api/test/compose.yaml new file mode 100644 index 0000000..1ca78d7 --- /dev/null +++ b/examples/shop/api/test/compose.yaml @@ -0,0 +1,21 @@ +# A throwaway Postgres for the API's integration tests, separate from the lo1 +# workspace so tests can run with or without `lo1 up`. Data lives in memory +# (tmpfs), so every `npm run test:db:down` starts the next run from nothing. +name: shop-api-test + +services: + postgres: + image: postgres:17-alpine + environment: + POSTGRES_USER: shop + POSTGRES_PASSWORD: shop + POSTGRES_DB: shop_test + ports: + # Not 54329, which the workspace's own Postgres uses. + - "54330:5432" + tmpfs: + - /var/lib/postgresql/data + healthcheck: + test: ["CMD", "pg_isready", "-U", "shop", "-d", "shop_test"] + interval: 1s + retries: 30 diff --git a/examples/shop/api/test/migrations.test.js b/examples/shop/api/test/migrations.test.js new file mode 100644 index 0000000..fb0234d --- /dev/null +++ b/examples/shop/api/test/migrations.test.js @@ -0,0 +1,33 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { migrations } from "../src/migrations/index.js"; +import { runMigrations } from "../src/migrations/run.js"; +import { useTestDatabase } from "./support/database.js"; + +const pool = useTestDatabase(); + +describe("runMigrations", () => { + it("creates the schema and records each migration", async () => { + const applied = await runMigrations(pool(), migrations); + + assert.deepEqual(applied, ["001-create-products"]); + const { rows } = await pool().query("SELECT name FROM schema_migrations"); + assert.deepEqual(rows, [{ name: "001-create-products" }]); + await pool().query("SELECT id, name, price_pence FROM products"); + }); + + it("applies nothing the second time", async () => { + const applied = await runMigrations(pool(), migrations); + + assert.deepEqual(applied, []); + }); + + it("rolls back a migration that fails, so it runs again next time", async () => { + const broken = { name: "002-broken", up: (db) => db.query("ALTER TABLE missing ADD x INT") }; + + await assert.rejects(runMigrations(pool(), [...migrations, broken]), /missing/); + + const { rows } = await pool().query("SELECT name FROM schema_migrations ORDER BY name"); + assert.deepEqual(rows, [{ name: "001-create-products" }]); + }); +}); diff --git a/examples/shop/api/test/products.test.js b/examples/shop/api/test/products.test.js new file mode 100644 index 0000000..958961b --- /dev/null +++ b/examples/shop/api/test/products.test.js @@ -0,0 +1,46 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { createProductRepository } from "../src/products/repository.js"; +import { useTestDatabase } from "./support/database.js"; + +const pool = useTestDatabase({ migrated: true }); + +describe("createProductRepository", () => { + it("lists the products it stored, in order", async () => { + const products = createProductRepository(pool()); + + await products.replaceAll([ + { name: "Loopback mug", pricePence: 1200 }, + { name: "IPv6 sticker pack", pricePence: 400 }, + ]); + + assert.deepEqual(await products.list(), [ + { id: 1, name: "Loopback mug", pricePence: 1200 }, + { id: 2, name: "IPv6 sticker pack", pricePence: 400 }, + ]); + }); + + it("replaces everything, restarting the ids", async () => { + const products = createProductRepository(pool()); + + await products.replaceAll([{ name: "127.0.0.1 hoodie", pricePence: 3800 }]); + + assert.deepEqual(await products.list(), [{ id: 1, name: "127.0.0.1 hoodie", pricePence: 3800 }]); + }); + + it("keeps the previous products when a replacement is rejected", async () => { + const products = createProductRepository(pool()); + const before = await products.list(); + + // The schema rejects negative prices; the whole replacement is rolled back. + await assert.rejects( + products.replaceAll([ + { name: "Fine", pricePence: 100 }, + { name: "Broken", pricePence: -1 }, + ]), + /price_pence/, + ); + + assert.deepEqual(await products.list(), before); + }); +}); diff --git a/examples/shop/api/test/router.test.js b/examples/shop/api/test/router.test.js new file mode 100644 index 0000000..a4bca41 --- /dev/null +++ b/examples/shop/api/test/router.test.js @@ -0,0 +1,49 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { createRouter } from "../src/http/router.js"; +import { useServer } from "./support/http.js"; + +const errors = []; +const request = useServer(() => + createRouter( + [ + { method: "GET", path: "/hello", handle: async () => ({ body: { hi: true } }) }, + { method: "POST", path: "/things", handle: async () => ({ status: 201, body: { id: 1 } }) }, + { method: "GET", path: "/boom", handle: async () => Promise.reject(new Error("db down")) }, + ], + { + headers: { "access-control-allow-origin": "https://web.shop.local" }, + onError: (err) => errors.push(err.message), + }, + ), +); + +describe("createRouter", () => { + it("sends a route's body as JSON with the shared headers", async () => { + const res = await request("/hello?ignored=1"); + + assert.equal(res.status, 200); + assert.deepEqual(await res.json(), { hi: true }); + assert.equal(res.headers.get("access-control-allow-origin"), "https://web.shop.local"); + assert.equal(res.headers.get("content-type"), "application/json; charset=utf-8"); + }); + + it("uses the status a route returns", async () => { + const res = await request("/things", { method: "POST" }); + + assert.equal(res.status, 201); + }); + + it("answers 404 for an unknown path or method", async () => { + assert.equal((await request("/nope")).status, 404); + assert.equal((await request("/hello", { method: "DELETE" })).status, 404); + }); + + it("answers 500 without leaking the error when a route throws", async () => { + const res = await request("/boom"); + + assert.equal(res.status, 500); + assert.deepEqual(await res.json(), { error: "internal error" }); + assert.deepEqual(errors, ["db down"]); + }); +}); diff --git a/examples/shop/api/test/support/database.js b/examples/shop/api/test/support/database.js new file mode 100644 index 0000000..063a5f9 --- /dev/null +++ b/examples/shop/api/test/support/database.js @@ -0,0 +1,44 @@ +import { randomUUID } from "node:crypto"; +import { after, before } from "node:test"; +import pg from "pg"; +import { migrations } from "../../src/migrations/index.js"; +import { runMigrations } from "../../src/migrations/run.js"; + +const DATABASE_URL = + process.env.TEST_DATABASE_URL ?? "postgres://shop:shop@localhost:54330/shop_test"; + +/** + * Gives a test file its own empty schema in the test database, so files can + * run in parallel without seeing each other's data. The schema is dropped + * when the file finishes. With `{ migrated: true }` the schema starts with + * every migration applied. + * + * Returns a getter for the pool, which exists once `before` has run. + */ +export function useTestDatabase({ migrated = false } = {}) { + const schema = `test_${randomUUID().replaceAll("-", "")}`; + let pool; + + before(async () => { + const admin = new pg.Client({ connectionString: DATABASE_URL }); + await admin.connect().catch((err) => { + throw new Error( + `Can't reach the test database at ${DATABASE_URL} (${err.message}). ` + + "Run the tests with npm test, which starts it.", + ); + }); + await admin.query(`CREATE SCHEMA ${schema}`); + await admin.end(); + + // Every connection in this pool works inside the file's own schema. + pool = new pg.Pool({ connectionString: DATABASE_URL, options: `-c search_path=${schema}` }); + if (migrated) await runMigrations(pool, migrations); + }); + + after(async () => { + await pool?.query(`DROP SCHEMA ${schema} CASCADE`); + await pool?.end(); + }); + + return () => pool; +} diff --git a/examples/shop/api/test/support/http.js b/examples/shop/api/test/support/http.js new file mode 100644 index 0000000..c13be17 --- /dev/null +++ b/examples/shop/api/test/support/http.js @@ -0,0 +1,26 @@ +import { createServer } from "node:http"; +import { after, before } from "node:test"; + +/** + * Serves `createHandler()` on a free local port for the duration of a test + * file. Returns a function that fetches a path from it. + * + * The handler is built on the first request rather than in `before`: hooks + * at the top of a file don't wait for each other, and the handler usually + * needs the test database, which another hook sets up. + */ +export function useServer(createHandler) { + let server; + let baseUrl; + let handler; + + before(async () => { + server = createServer((req, res) => (handler ??= createHandler())(req, res)); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + baseUrl = `http://127.0.0.1:${server.address().port}`; + }); + + after(() => new Promise((resolve) => server.close(resolve))); + + return (path, init) => fetch(`${baseUrl}${path}`, init); +} diff --git a/examples/shop/lo1.yaml b/examples/shop/lo1.yaml index 71e963d..c270082 100644 --- a/examples/shop/lo1.yaml +++ b/examples/shop/lo1.yaml @@ -14,36 +14,36 @@ services: migrate: type: service path: ./api - command: npm install --no-audit --no-fund --loglevel=error && node migrate.js + command: npm install --no-audit --no-fund --loglevel=error && node src/migrate.js initTask: true - env: + # Defined once here and reused below with *database. + env: &database DATABASE_URL: postgres://shop:shop@localhost:54329/shop seed: type: service path: ./api - command: node seed.js + command: node src/seed.js initTask: true dependsOn: [migrate] - env: - DATABASE_URL: postgres://shop:shop@localhost:54329/shop + env: *database api: type: service path: ./api port: 4100 - command: node server.js + command: node src/server.js readinessProbe: http://localhost:4100/health dependsOn: [seed] env: + <<: *database PORT: "4100" - DATABASE_URL: postgres://shop:shop@localhost:54329/shop web: type: app path: ./web port: 4200 - command: node server.js + command: node src/server.js dependsOn: [api] env: PORT: "4200" diff --git a/examples/shop/web/package.json b/examples/shop/web/package.json new file mode 100644 index 0000000..8e1325a --- /dev/null +++ b/examples/shop/web/package.json @@ -0,0 +1,12 @@ +{ + "name": "shop-web", + "private": true, + "type": "module", + "engines": { + "node": ">=24" + }, + "scripts": { + "start": "node src/server.js", + "test": "node --test \"test/**/*.test.js\"" + } +} diff --git a/examples/shop/web/public/app.js b/examples/shop/web/public/app.js new file mode 100644 index 0000000..327b195 --- /dev/null +++ b/examples/shop/web/public/app.js @@ -0,0 +1,39 @@ +const list = document.getElementById("products"); +const price = new Intl.NumberFormat("en-GB", { style: "currency", currency: "GBP" }); + +async function fetchJson(url) { + const res = await fetch(url); + if (!res.ok) throw new Error(`${url} answered ${res.status}`); + return res.json(); +} + +/** Asks the web server where the API is, then fetches the products from it. */ +async function loadProducts() { + const { apiUrl } = await fetchJson("/config.json"); + return fetchJson(`${apiUrl}/products`); +} + +// Text goes in with textContent, never innerHTML, so a product name can't inject markup. +function listItem(...cells) { + const item = document.createElement("li"); + for (const text of cells) { + const cell = document.createElement("span"); + cell.textContent = text; + item.append(cell); + } + return item; +} + +function showProducts(products) { + list.replaceChildren( + ...products.map((product) => listItem(product.name, price.format(product.pricePence / 100))), + ); +} + +function showError(err) { + const item = listItem(`Could not reach the API: ${err.message}`); + item.className = "error"; + list.replaceChildren(item); +} + +loadProducts().then(showProducts, showError); diff --git a/examples/shop/web/public/index.html b/examples/shop/web/public/index.html new file mode 100644 index 0000000..51ebb2c --- /dev/null +++ b/examples/shop/web/public/index.html @@ -0,0 +1,15 @@ + + + + + + lo1 shop + + + + +

lo1 shop

+

Products below come from Postgres, through the API, over HTTPS.

+
  • Loading…
+ + diff --git a/examples/shop/web/public/styles.css b/examples/shop/web/public/styles.css new file mode 100644 index 0000000..4f05d77 --- /dev/null +++ b/examples/shop/web/public/styles.css @@ -0,0 +1,17 @@ +body { + font-family: system-ui, sans-serif; + max-width: 40rem; + margin: 3rem auto; + padding: 0 1rem; +} + +li { + display: flex; + justify-content: space-between; + padding: 0.5rem 0; + border-bottom: 1px solid #ddd; +} + +.error { + color: #b00020; +} diff --git a/examples/shop/web/src/config.js b/examples/shop/web/src/config.js new file mode 100644 index 0000000..d9fb9f4 --- /dev/null +++ b/examples/shop/web/src/config.js @@ -0,0 +1,11 @@ +/** + * Reads the web app's settings from the environment, once. + */ +export function loadConfig(env = process.env) { + return { + port: Number(env.PORT ?? 4200), + // lo1 gives every service each other service's URLs. The browser has to + // reach the API through the proxy, so it needs the API's public URL. + apiUrl: env.LO1_SERVICE_API_PROXY_URL ?? "http://localhost:4100", + }; +} diff --git a/examples/shop/web/src/handler.js b/examples/shop/web/src/handler.js new file mode 100644 index 0000000..29317a8 --- /dev/null +++ b/examples/shop/web/src/handler.js @@ -0,0 +1,53 @@ +import { readFile } from "node:fs/promises"; + +const PUBLIC_DIR = new URL("../public/", import.meta.url); + +/** The files the page needs. Only these are served, so no path can reach anything else. */ +const PUBLIC_FILES = { + "/": { file: "index.html", type: "text/html; charset=utf-8" }, + "/app.js": { file: "app.js", type: "text/javascript; charset=utf-8" }, + "/styles.css": { file: "styles.css", type: "text/css; charset=utf-8" }, +}; + +/** Reads the public files into memory once, at startup. */ +export async function loadPublicFiles(dir = PUBLIC_DIR) { + const entries = await Promise.all( + Object.entries(PUBLIC_FILES).map(async ([path, { file, type }]) => [ + path, + { type, body: await readFile(new URL(file, dir)) }, + ]), + ); + return new Map(entries); +} + +/** + * Builds the web app's request handler. It serves the public files, plus + * `/config.json`, which tells the page where the API is. + */ +export function createWebHandler({ files, apiUrl }) { + const config = Buffer.from(JSON.stringify({ apiUrl })); + const headers = securityHeaders(apiUrl); + + return (req, res) => { + const { pathname } = new URL(req.url, "http://localhost"); + if (req.method !== "GET") return send(res, 405, "text/plain", "method not allowed", headers); + if (pathname === "/config.json") return send(res, 200, "application/json", config, headers); + + const page = files.get(pathname); + if (!page) return send(res, 404, "text/plain", "not found", headers); + send(res, 200, page.type, page.body, headers); + }; +} + +/** Lets the page load only its own files and call only the API. */ +function securityHeaders(apiUrl) { + return { + "content-security-policy": `default-src 'self'; connect-src 'self' ${new URL(apiUrl).origin}`, + "x-content-type-options": "nosniff", + }; +} + +function send(res, status, type, body, headers) { + res.writeHead(status, { ...headers, "content-type": type }); + res.end(body); +} diff --git a/examples/shop/web/src/server.js b/examples/shop/web/src/server.js new file mode 100644 index 0000000..d47049e --- /dev/null +++ b/examples/shop/web/src/server.js @@ -0,0 +1,17 @@ +import { createServer } from "node:http"; +import { loadConfig } from "./config.js"; +import { createWebHandler, loadPublicFiles } from "./handler.js"; + +// The composition root: reads the settings and files, then starts serving. +const config = loadConfig(); +const handler = createWebHandler({ files: await loadPublicFiles(), apiUrl: config.apiUrl }); + +const server = createServer(handler); +server.listen(config.port, () => + console.log(`web listening on ${config.port}, using API at ${config.apiUrl}`), +); + +// lo1 sends SIGTERM on `lo1 down` and `lo1 restart`; finish in-flight requests first. +for (const signal of ["SIGTERM", "SIGINT"]) { + process.once(signal, () => server.close(() => process.exit(0))); +} diff --git a/examples/shop/web/test/handler.test.js b/examples/shop/web/test/handler.test.js new file mode 100644 index 0000000..b5dcf47 --- /dev/null +++ b/examples/shop/web/test/handler.test.js @@ -0,0 +1,55 @@ +import { after, before, describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import { createWebHandler, loadPublicFiles } from "../src/handler.js"; + +let server; +let baseUrl; + +before(async () => { + const handler = createWebHandler({ + files: await loadPublicFiles(), + apiUrl: "https://api.shop.local", + }); + server = createServer(handler); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + baseUrl = `http://127.0.0.1:${server.address().port}`; +}); + +after(() => new Promise((resolve) => server.close(resolve))); + +const request = (path, init) => fetch(`${baseUrl}${path}`, init); + +describe("the web app", () => { + it("serves the page and its own files", async () => { + const page = await request("/"); + + assert.equal(page.status, 200); + assert.match(page.headers.get("content-type"), /text\/html/); + assert.match(await page.text(), /
    { + const res = await request("/config.json"); + + assert.deepEqual(await res.json(), { apiUrl: "https://api.shop.local" }); + }); + + it("only lets the page load its own files and call the API", async () => { + const res = await request("/"); + + assert.equal( + res.headers.get("content-security-policy"), + "default-src 'self'; connect-src 'self' https://api.shop.local", + ); + assert.equal(res.headers.get("x-content-type-options"), "nosniff"); + }); + + it("serves nothing outside its public files", async () => { + assert.equal((await request("/%2e%2e/src/config.js")).status, 404); + assert.equal((await request("/package.json")).status, 404); + assert.equal((await request("/", { method: "POST" })).status, 405); + }); +});