diff --git a/.claude/skills/new-service/SKILL.md b/.claude/skills/new-service/SKILL.md index ea3e129..2a237e0 100644 --- a/.claude/skills/new-service/SKILL.md +++ b/.claude/skills/new-service/SKILL.md @@ -61,7 +61,7 @@ The script refuses invalid names, existing members and unknown contracts. It wri | `src//worker.py` (worker) | `handle` / `process_one` / `run` consume loop | | `tests/test_.py` | starter tests (health check / consume loop) | | root `pyproject.toml` | adds the import name to ruff `known-first-party` and `apps//src` to `mypy_path` | -| `compose.yaml` | service entry; host port = highest used + 1; broker services get the shared `*broker-env` / `*broker-depends` anchors, so they follow whichever broker is selected | +| `compose.yaml` | service entry; host port = highest app port (`"N:8000"`) + 1; broker services get the shared `*broker-env` / `*broker-depends` anchors, so they follow whichever broker is selected | | `pyproject.toml` + `Dockerfile` (broker services) | `redis` / `rabbitmq` extras and the `BROKER_EXTRAS` build arg, so images can carry any broker client | CI (`scripts/ci/affected.py`) and the workspace glob pick up the new member automatically. diff --git a/.claude/skills/new-service/scripts/scaffold.py b/.claude/skills/new-service/scripts/scaffold.py index 24f3213..132b3df 100644 --- a/.claude/skills/new-service/scripts/scaffold.py +++ b/.claude/skills/new-service/scripts/scaffold.py @@ -352,7 +352,9 @@ def append_to_toml_list(text: str, key: str, item: str) -> str: def next_host_port(compose: str) -> int: - ports = [int(p) for p in re.findall(r'"(\d+):\d+"', compose)] + # Only count app ports (every service listens on 8000 inside its container), so + # infrastructure ports such as RabbitMQ's management UI (15672) don't push it up. + ports = [int(p) for p in re.findall(r'"(\d+):8000"', compose)] return max([8000, *ports]) + 1 diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 417ef38..ff22175 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -44,6 +44,8 @@ flowchart LR root --> rootfiles["pyproject.toml
(workspace + ruff/mypy/pytest config)
uv.lock · compose.yaml · .env"] root --> brokers["brokers/
redis.env · rabbitmq.env · tcp.env"] root --> ci[".github/workflows/ci.yml
scripts/ci/affected.py
scripts/ci/compose_smoke.sh"] + root --> tooling[".claude/skills/new-service/
(scaffold a wired-in service)"] + root --> docs["docs/
demo.gif · brokers.gif (+ .mp4)
demo/player.html · demo/record.mjs"] root --> pkgs["packages/ (libraries)"] root --> apps["apps/ (deployables)"] @@ -161,8 +163,23 @@ The broker is a work queue: each event goes to exactly one worker replica, so ru `notifier-worker` replicas spreads the load rather than sending duplicate notifications. Every backend keeps that promise, so the flow above is identical whichever broker is configured. +```mermaid +flowchart LR + orders["orders-api
(any number of replicas)"] -->|"publish OrderPlaced #1 #2 #3 #4"| q[("orders.placed queue
Redis list · RabbitMQ queue · tcp-broker FIFO")] + q -->|"#1, #3"| w1["notifier-worker replica 1"] + q -->|"#2, #4"| w2["notifier-worker replica 2"] +``` + +This is a real run (two replicas on the TCP broker, four orders), from +[`docs/brokers.mp4`](docs/brokers.mp4): replica 1 notified ada and alan, replica 2 grace and +linus, and nobody was notified twice. + ## Messaging: a pluggable transport +![Demo: the same services on Redis, then on the TCP broker, two worker replicas sharing a queue, and the contract tests](docs/brokers.gif) + +Real commands and output (also as an [MP4](docs/brokers.mp4)). Regenerate with `node docs/demo/record.mjs brokers`. + `packages/messaging` separates *what* a service does with messages from *how* they travel. Services see one abstract class, `Broker`, with `publish(topic, message)`, `receive(topic, timeout)` and `close()`. Each backend implements it on top of one technology: @@ -222,6 +239,46 @@ flowchart LR | RabbitMQ | `amqp://user:pass@host:5672/vhost` | each message to one consumer | yes (durable queue, persistent messages) | `rabbitmq` extra + a RabbitMQ server | | TCP | `tcp://host:7000` | each message to one consumer | no (queues live in the server's memory) | the `tcp-broker` image, no client library | +Swapping is just a matter of where `BROKER_URL` points. Without Docker, using the +stdlib TCP broker (or `redis-server` and `redis://localhost:6379/0`): + +```bash +uv run tcp-broker & +export BROKER_URL=tcp://localhost:7000 +PORT=8001 uv run catalog-api & PORT=8002 uv run orders-api & uv run notifier-worker & +# the worker logs: listening on orders.placed via TcpBroker +``` + +An unknown scheme fails at start-up, not at the first message: +`BrokerError: unsupported broker URL 'kafka://localhost:9092'; known schemes: amqp, amqps, memory, redis, rediss, tcp`. + +### The TCP broker + +`apps/tcp-broker` is a small, standard-library-only server for `tcp://` URLs: no client library, +no external image. It keeps one FIFO queue per topic in memory and speaks one JSON object per +line in each direction: + +```mermaid +sequenceDiagram + participant P as orders-api
(TcpBroker client) + participant S as tcp-broker
(TcpBrokerServer) + participant C as notifier-worker
(TcpBroker client) + + C->>S: {"op": "receive", "topic": "orders.placed", "timeout": 1.0} + Note over S: queue empty: hold the request
up to timeout (max 30 s) + P->>S: {"op": "publish", "topic": "orders.placed", "message": "{...}"} + S-->>P: {"ok": true} + S-->>C: {"ok": true, "message": "{...}"} + Note over S,C: if the reply can't be written (client gone),
the message goes back to the front of the queue + C->>S: {"op": "receive", ...} + S-->>C: {"ok": true, "message": null} after the timeout + Note over S: {"op": "ping"} → {"ok": true} is the Docker HEALTHCHECK
(tcp-broker --check). Errors → {"ok": false, "error": "..."} +``` + +Clients hold one connection, are thread-safe and reconnect once if the link drops. Because +queues live in the server's memory, messages are lost if it restarts; use Redis or RabbitMQ +where that matters. + All four pass the same contract tests (`packages/messaging/tests/test_messaging.py`): FIFO order, timeouts, independent topics, large and non-ASCII payloads, and concurrent publishers. @@ -272,22 +329,23 @@ flowchart TD changes -->|"matrix: affected members"| t1["test messaging"] changes --> t2["test orders-api"] changes --> t3["test notifier-worker"] + changes --> t4["test tcp-broker"] changes -.->|"unaffected members skipped"| skip["(no job)"] changes -->|"messaging affected"| brk["brokers job
contract tests vs real
Redis + RabbitMQ services"] changes -->|"notifier-worker affected"| e2e["compose job · matrix
redis · rabbitmq · tcp
scripts/ci/compose_smoke.sh"] - t1 & t2 & t3 --> ok{"CI OK
(required check)"} + t1 & t2 & t3 & t4 --> ok{"CI OK
(required check)"} brk & e2e --> ok lint --> ok ok -->|"all success / skipped"| merge["PR can be merged into main"] ok -->|"any failure"| fix["Fix and push again"] ``` -The matrix shown is what a change to `packages/messaging` produces: messaging plus its -dependents (tcp-broker too, left out of the picture), while catalog-api, cli and the other -libraries are skipped. Two more jobs guard the transport: **brokers** runs the messaging +The matrix shown is what a change to `packages/messaging` produces: messaging plus its three +dependents, while catalog-api, cli and the other libraries are skipped. Two more jobs guard the transport: **brokers** runs the messaging contract tests against real Redis and RabbitMQ containers, and **compose** builds the real -images and sends an order from `orders-api` to `notifier-worker` over each broker in turn. To see what CI would +images and sends an order from `orders-api` to `notifier-worker` over each broker in turn. The +unit test job already covers the in-memory, fakeredis and TCP backends. To see what CI would test for your branch, run `python3 scripts/ci/affected.py --base origin/main`. ## Container build @@ -448,4 +506,7 @@ To do it by hand: so it follows whichever broker is selected, and copy the `redis` / `rabbitmq` extras and the `BROKER_EXTRAS` lines from `apps/notifier-worker`. -CI picks the new member up automatically. +With `--broker` (or for any worker), the scaffold wires the compose entry to the shared +`*broker-env` / `*broker-depends` anchors and copies the broker extras into the app, so the new +service follows whichever broker is selected. HTTP services get the next free app port +(`8003`, `8004`, ...). CI picks the new member up automatically. diff --git a/README.md b/README.md index 64bc5dc..ac6a76d 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ while still testing, building and deploying each one on its own. It ships a smal realistic microservice system so you can see every piece working together: - **`catalog-api`** lists products, **`orders-api`** places orders (calling the catalog over - HTTP) and publishes an `order.placed` event, and **`notifier-worker`** consumes that event + HTTP) and publishes an `OrderPlaced` event, and **`notifier-worker`** consumes that event and sends a notification. - The services share code only through libraries in `packages/`: typed **contracts** (pydantic models for API payloads and events), a pluggable **messaging** layer (Redis, @@ -38,9 +38,11 @@ Pick the path that matches what you want to do: | **Deploy services separately** | Build each app's image on its own and version/scale it independently; see [Deploying services independently](#deploying-services-independently). | | **Keep CI fast as the repo grows** | Nothing to do: CI works out which members a change affects from the `pyproject.toml` files. See [CI](#ci). | -![Demo: services talking over HTTP and Redis, CI testing only affected members, and scaffolding a new service](docs/demo.gif) +![Demo: services talking over HTTP and a broker, swapping Redis for the TCP broker, CI testing only affected members, and scaffolding a new service](docs/demo.gif) -Real commands and output, replayed by [`docs/demo/player.html`](docs/demo/player.html). Also available as an [MP4](docs/demo.mp4). Regenerate with `node docs/demo/record.mjs`. +Real commands and output, replayed by [`docs/demo/player.html`](docs/demo/player.html). Also available as an [MP4](docs/demo.mp4). +A second video, [`docs/brokers.gif`](docs/brokers.gif) ([MP4](docs/brokers.mp4)), walks through the pluggable transport: +Redis, the TCP broker, scaling workers and the contract tests. Regenerate both with `node docs/demo/record.mjs`. See **[ARCHITECTURE.md](ARCHITECTURE.md)** for diagrams of the layout, dependency graph, runtime flow, CI and deployment. @@ -53,6 +55,8 @@ runtime flow, CI and deployment. ├── uv.lock # single lockfile for the whole workspace ├── compose.yaml # run all services together locally (one profile per broker) ├── .env, brokers/*.env # which broker compose starts and BROKER_URL points at +├── .claude/skills/ # new-service: scaffold a fully wired service (Claude Code skill) +├── docs/ # demo videos (+ the player/recorder that renders them) ├── packages/ # reusable libraries │ ├── contracts/ # shared pydantic models: API payloads + events │ ├── messaging/ # Broker interface + Redis / RabbitMQ / TCP / in-memory backends @@ -95,6 +99,15 @@ docker compose --env-file brokers/tcp.env up --build # built-in TCP broke docker compose --profile "*" down # stop, whichever is running ``` +Without Docker, run the services with `uv run` and point them at any broker you have, for +example the built-in TCP broker: + +```bash +uv run tcp-broker & +export BROKER_URL=tcp://localhost:7000 # or redis://localhost:6379/0 +PORT=8001 uv run catalog-api & PORT=8002 uv run orders-api & uv run notifier-worker & +``` + See [ARCHITECTURE.md](ARCHITECTURE.md#messaging-a-pluggable-transport) for how the transport is plugged in and how to add another one. diff --git a/docs/brokers.gif b/docs/brokers.gif new file mode 100644 index 0000000..3bf1869 Binary files /dev/null and b/docs/brokers.gif differ diff --git a/docs/brokers.mp4 b/docs/brokers.mp4 new file mode 100644 index 0000000..c4724a2 Binary files /dev/null and b/docs/brokers.mp4 differ diff --git a/docs/demo.gif b/docs/demo.gif index d9ff3c5..22b9064 100644 Binary files a/docs/demo.gif and b/docs/demo.gif differ diff --git a/docs/demo.mp4 b/docs/demo.mp4 index d2d4fb1..cde13e0 100644 Binary files a/docs/demo.mp4 and b/docs/demo.mp4 differ diff --git a/docs/demo/player.html b/docs/demo/player.html index 75982ee..63593ac 100644 --- a/docs/demo/player.html +++ b/docs/demo/player.html @@ -6,7 +6,10 @@ @@ -82,9 +91,9 @@
catalog-api
HTTP
◀──
orders-api
-
event
──▶
-
Redis
-
event
──▶
+
publish
──▶
+
Redis
+
consume
──▶
notifier-worker
@@ -96,7 +105,10 @@