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..b0a8b1a --- /dev/null +++ b/examples/shop/README.md @@ -0,0 +1,72 @@ +# 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, 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 new file mode 100644 index 0000000..428be8c --- /dev/null +++ b/examples/shop/api/package-lock.json @@ -0,0 +1,162 @@ +{ + "name": "shop-api", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "shop-api", + "dependencies": { + "pg": "8.23.1" + }, + "engines": { + "node": ">=24" + } + }, + "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..2c92b45 --- /dev/null +++ b/examples/shop/api/package.json @@ -0,0 +1,19 @@ +{ + "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/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..c270082 --- /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 src/migrate.js + initTask: true + # 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 src/seed.js + initTask: true + dependsOn: [migrate] + env: *database + + api: + type: service + path: ./api + port: 4100 + command: node src/server.js + readinessProbe: http://localhost:4100/health + dependsOn: [seed] + env: + <<: *database + PORT: "4100" + + web: + type: app + path: ./web + port: 4200 + command: node src/server.js + dependsOn: [api] + env: + PORT: "4200" + +proxy: + tld: local + tls: + enabled: true 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 @@ + + +
+ + +Products below come from Postgres, through the API, over HTTPS.
+