From 2ead541db82e1f65fc8e545c963f294ac55e9bfa Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 20:33:17 +0000 Subject: [PATCH] Add a new-broker skill that scaffolds a fully wired messaging backend .claude/skills/new-broker/ has a SKILL.md (check that the transport fits the Broker contract, scaffold, implement, test, verify, update the docs) and a stdlib-only scaffold.py. In one command it creates the backend module and its test file, then registers the scheme(s) in broker.py (_BACKENDS, _EXTRAS, docstring) and adds the client extra to packages/messaging and the dev group (with an optional mypy override). It also adds the extra to every app that carries broker extras, plus their Dockerfile BROKER_EXTRAS; adds the compose BROKER_EXTRAS defaults, a profile-gated server and the x-broker-depends anchor; writes brokers/.env; adds the REAL_BROKERS contract-test entry; and adds a CI service container, test URL and compose-matrix entry. --dry-run prints a diff of every change. To make those edits reliable: - tests/conftest.py: the real-server brokers are now a REAL_BROKERS table (same test ids and skips as before). - The new-service scaffold reads the broker extras from packages/messaging/pyproject.toml instead of hard-coding redis/rabbitmq. - compose_smoke.sh's usage lists brokers/*.env instead of a fixed set. README and ARCHITECTURE point to the skill. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SE2PhJQLSccvNwV1Eoauuj --- .claude/skills/new-broker/SKILL.md | 161 ++++++ .claude/skills/new-broker/scripts/scaffold.py | 521 ++++++++++++++++++ .claude/skills/new-service/SKILL.md | 2 +- .../skills/new-service/scripts/scaffold.py | 33 +- ARCHITECTURE.md | 17 +- README.md | 4 +- packages/messaging/tests/conftest.py | 27 +- scripts/ci/compose_smoke.sh | 4 +- 8 files changed, 740 insertions(+), 29 deletions(-) create mode 100644 .claude/skills/new-broker/SKILL.md create mode 100644 .claude/skills/new-broker/scripts/scaffold.py diff --git a/.claude/skills/new-broker/SKILL.md b/.claude/skills/new-broker/SKILL.md new file mode 100644 index 0000000..389b373 --- /dev/null +++ b/.claude/skills/new-broker/SKILL.md @@ -0,0 +1,161 @@ +--- +name: new-broker +description: Add a new message-broker backend (transport) to packages/messaging - such as NATS, SQS, Kafka, Pulsar or a custom protocol - fully wired in: Broker subclass, URL scheme, optional client-library extra, app extras and Dockerfiles, compose profile and env file, contract tests and CI, and docs - and verified with ruff, mypy and pytest. Use when the user asks to add, create, support or plug in a new broker, transport, message queue or BROKER_URL scheme. +--- + +# Add a new broker backend + +Services only see `messaging.Broker`; `BROKER_URL`'s scheme picks the backend at start-up +(see `ARCHITECTURE.md`, "Pluggable transport"). A new backend touches a dozen files, so a +scaffold script does the wiring and you write the transport logic, tests and docs. +**No service code changes.** If you find yourself editing `apps/*/src`, stop and rethink. + +## 1. Check that the transport fits the contract + +Every backend must keep the behaviour in `packages/messaging/tests/test_messaging.py`: + +- **Work queue**: each message goes to exactly one consumer, even with many worker replicas + (no fan-out). More replicas spread the load. +- **FIFO per topic**, independent topics, payloads of any size (to several MB) and any Unicode. +- **`receive(topic, timeout)`** returns one message, or `None` after `timeout` seconds. The + topic is chosen on every call, and messages published before the first `receive` must wait. +- **`publish`** returns once the server has accepted the message. Several threads may call + it at the same time. +- **`from_url` does not connect.** Connect on first use, and reconnect once if the link drops. + +Most queues fit directly (RabbitMQ, Redis lists, SQS, NATS JetStream work-queue streams, +Pulsar shared subscriptions). Log-based systems such as Kafka need care: one consumer group +for every replica, one partition per topic (or keyed messages) to keep FIFO, +`auto.offset.reset=earliest`, a commit after every message and a flush on every publish. Also, +joining a group can take longer than a 1 s `receive`. If the transport can't meet a rule, tell +the user before you start. Don't loosen the contract tests to make a backend pass. + +Ask the user only about what you can't decide yourself, usually the client library. Prefer a +maintained **synchronous** client with type hints. The interface is sync, and the RabbitMQ +backend shows the pattern for a blocking client. + +## 2. Scaffold + +From the repo root. Try `--dry-run` first: it prints a diff of every change. + +```bash +python3 .claude/skills/new-broker/scripts/scaffold.py --title \ + --dependency ">=" \ + --image --port --healthcheck "" +``` + +| Option | Meaning | +| --- | --- | +| `` | lowercase id, e.g. `nats`. Used as the extra, compose service and profile, and `brokers/.env` | +| `--scheme` | URL scheme, repeatable (`--scheme nats --scheme tls`). Default: `` | +| `--title`, `--class`, `--module` | display name, class (default `Broker`), module under `messaging/backends/` (default `<name>`) | +| `--dependency` | client-library requirement. Leave it out for a stdlib-only transport (then no extras are added) | +| `--client-import` + `--untyped` | add a mypy `ignore_missing_imports` override for a client without type hints | +| `--image`, `--port`, `--healthcheck`, `--container-env K=V` | the server for compose and the CI service container | +| `--compose-url`, `--test-url`, `--test-env` | defaults: `<scheme>://<name>:<port>`, `<scheme>://localhost:<port>`, `MESSAGING_TEST_<NAME>_URL` | + +It refuses to run if the scheme, extra, module, compose service or test file name already +exists. It writes: + +| File | Change | +| --- | --- | +| `packages/messaging/src/messaging/backends/<module>.py` | a `Broker` subclass with `from_url`; `publish`/`receive` raise `NotImplementedError` | +| `packages/messaging/tests/test_<module>.py` | scheme → class registry test, plus a test against a real server (skipped unless `--test-env` is set) | +| `packages/messaging/src/messaging/broker.py` | `_BACKENDS` entries, `_EXTRAS` (for the "install the extra" hint), the docstring's URL list | +| `packages/messaging/pyproject.toml` | the `<name>` extra | +| `packages/messaging/tests/conftest.py` | a `REAL_BROKERS` entry, so every contract test also runs against a real server when the URL is set | +| root `pyproject.toml` | the client in the `dev` group (so everything is testable locally), and the mypy override if `--untyped` | +| `apps/*` that carry broker extras | a `<name> = ["messaging[<name>]"]` extra, plus `<name>` added to `ARG BROKER_EXTRAS` in their Dockerfile | +| `compose.yaml` | `BROKER_EXTRAS` defaults, a `profiles: [<name>]` server, and the `x-broker-depends` anchor | +| `brokers/<name>.env` | `COMPOSE_PROFILES` + `BROKER_URL`, for `docker compose --env-file brokers/<name>.env up` | +| `.github/workflows/ci.yml` | service container + `MESSAGING_TEST_*` URL in the `brokers` job, `<name>` in the `compose` matrix | + +New services pick the extra up automatically: the new-service scaffold reads the extras +from `packages/messaging/pyproject.toml`. + +### Without `--image` + +The script then leaves compose and CI alone, and writes `brokers/<name>.env` only if you +pass `--compose-url`. Wire them by hand: + +- **A server you write yourself** (like `apps/tcp-broker`): create it with the new-service + skill, then add a `profiles: [<name>]` compose service that builds it, like `tcp-broker`. + Add a `HEALTHCHECK` and a `x-broker-depends` entry, plus `<name>` to the CI compose matrix. + If it can run in-process, add an always-on param to `any_broker` (see `"tcp"` in `conftest.py`). +- **A managed cloud service** (e.g. SQS): use an emulator image for compose and CI if one + exists (e.g. LocalStack), and pass it as `--image`. Otherwise say plainly that only the + unit tests run. + +## 3. Implement the backend + +Read `backends/rabbitmq.py` (blocking client: lazy connection, one lock, reconnect and retry +once) and `backends/redis_broker.py` (client that is already thread-safe) first, and follow +their structure: + +- Map topics 1:1 onto the transport's queue concept, and create them on first use (idempotently). +- Keep the delivery guarantee the others have (at-most-once: ack/remove as soon as it is + received), or document a stronger one in the module docstring. Fill in the docstring's TODOs. +- `receive` must return within about `timeout`. If the client has no blocking get with a + timeout, poll with a short sleep, as RabbitMQ does with `process_data_events`. +- Hold a lock around a connection that isn't thread-safe. `close()` must be idempotent. +- If the client is asyncio-only, run one event loop on a daemon thread and submit work to it + with `asyncio.run_coroutine_threadsafe(...).result(timeout)`. Don't call `asyncio.run` per call. +- Let a constructor argument take a fake connection or client (as `RabbitMQBroker` takes a + `connection_factory`), so the logic is unit-testable without a server. +- `third-party deps`: only through the extra. The core of `messaging` stays dependency-free + (just pydantic). + +## 4. Tests + +- **Contract**: the `REAL_BROKERS` entry runs all of `test_messaging.py` against a real server + when `MESSAGING_TEST_<NAME>_URL` is set. If an in-process fake of the server exists (like + `fakeredis`), add it as an always-on param of `any_broker` so the contract also runs without one. +- **Backend-specific** (`tests/test_<module>.py`): keep the registry and "messages wait for a + later consumer" tests, and add tests for reconnecting after a dropped connection, for the + URL parsing (credentials, TLS scheme, defaults), and for a missing host, as + `test_rabbitmq.py` and `test_registry.py` do. Annotate everything (mypy strict). +- Test file names must be unique across the repo (mypy reports duplicate modules). + +## 5. Verify (all must pass before you report done) + +```bash +uv lock && uv sync --all-packages # the new client library; commit uv.lock +uv run ruff check . && uv run ruff format --check . +uv run mypy +uv run pytest packages/messaging apps +uv lock --check +``` + +If Docker is available, run the real-server tests and the end-to-end smoke test too: + +```bash +docker run -d --rm --name <name>-test -p <port>:<port> <image> +MESSAGING_TEST_<NAME>_URL=<test-url> uv run pytest packages/messaging +docker stop <name>-test +scripts/ci/compose_smoke.sh <name> # an order travels orders-api -> <name> -> notifier-worker +``` + +If Docker isn't available, say so. Don't claim the backend works against a real server +without having run it there. Unit tests alone don't show that. + +## 6. Update the docs + +- `ARCHITECTURE.md` "Pluggable transport": the `classDiagram` (class + `Broker <|--` edge), + the `broker_from_url()` flowchart, the backend table (URL, delivery, survives a broker + restart, needs), and the "known schemes" line in the error example. +- `README.md`: the summary line and the "Use a different message broker" row, the + `messaging/` comment in **Layout**, and the env-file list under **Running it**. +- The comments that list the brokers: `packages/messaging/pyproject.toml` `description`, + the compose.yaml header, the `BROKER_EXTRAS` comments in the app Dockerfiles, and the + `brokers` job comment in `ci.yml`. + +## 7. Wrap up + +Commit everything together: the backend and its tests, `broker.py`, the pyprojects, +`uv.lock`, Dockerfiles, `compose.yaml`, `brokers/<name>.env`, `ci.yml` and the docs. Then +summarise for the user: + +- the URL scheme(s) and an example `BROKER_URL` +- the delivery guarantee +- how to run the stack on the new broker: `docker compose --env-file brokers/<name>.env up --build` +- which checks ran, and which (real server, compose) could not diff --git a/.claude/skills/new-broker/scripts/scaffold.py b/.claude/skills/new-broker/scripts/scaffold.py new file mode 100644 index 0000000..dca1773 --- /dev/null +++ b/.claude/skills/new-broker/scripts/scaffold.py @@ -0,0 +1,521 @@ +#!/usr/bin/env python3 +"""Scaffold a new message-broker backend (transport) for packages/messaging. + +Creates the backend module and its test file, then wires the backend into every place a +broker appears, so that only the transport logic and the docs are left to write: + +- packages/messaging: ``_BACKENDS`` / ``_EXTRAS`` / module docstring in ``broker.py``, + the optional extra in ``pyproject.toml``, and ``REAL_BROKERS`` in ``tests/conftest.py`` +- root pyproject.toml: the client library in the ``dev`` group (and a mypy override) +- every app that carries broker extras: its extra and its Dockerfile ``BROKER_EXTRAS`` +- compose.yaml: the ``BROKER_EXTRAS`` defaults, a broker service with its own profile, + and the ``x-broker-depends`` anchor; plus ``brokers/<name>.env`` +- .github/workflows/ci.yml: a service container and test URL in the ``brokers`` job, and + the broker in the ``compose`` matrix + +The new-service scaffold reads the broker extras from packages/messaging, so new services +pick the backend up automatically. + +Standard library only, so it runs before ``uv sync``. + +Usage: + scaffold.py nats --title NATS --dependency "nats-py>=2.9" \\ + --image nats:2-alpine --port 4222 --healthcheck "wget -q -O- localhost:8222/healthz" + scaffold.py <name> --scheme <s> [--scheme <s2>] ... (default scheme: <name>) + add --dry-run to print a diff of every change without writing anything. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import re +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[4] +MESSAGING = ROOT / "packages/messaging" +NAME_RE = re.compile(r"^[a-z][a-z0-9]*$") +SCHEME_RE = re.compile(r"^[a-z][a-z0-9+.-]*$") +ENV_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=.*$") + +# --------------------------------------------------------------------------- templates +# Placeholders are __UPPER__ tokens so Python and YAML syntax survives. + +BACKEND = '''\ +"""__TITLE__ backend: TODO say how topics map onto __TITLE__ (e.g. one queue per topic). + +TODO describe the delivery guarantee (compare the Redis and RabbitMQ backends, which are +at-most-once: a message is removed from the queue as soon as it is received). + +Contract every backend must keep (``messaging.Broker``, tests/test_messaging.py): + +- ``publish(topic, message)``: when it returns, the server has accepted the message. +- ``receive(topic, timeout)``: the next message on ``topic``, delivered to exactly one + consumer even with many replicas (work-queue semantics, not fan-out), FIFO per topic; + ``None`` once ``timeout`` seconds pass without one. +- ``close()``: releases the connection and is safe to call more than once. +- Thread-safe: FastAPI runs sync routes on a thread pool, so guard a shared connection. +- ``from_url`` must not connect (the registry tests build every backend offline); + connect on first use and reconnect once if the link has dropped. +""" + +from __future__ import annotations + +import threading +from typing import Self + +from messaging.broker import Broker + + +class __CLASS__(Broker): + def __init__(self, url: str) -> None: + self._url = url + self._lock = threading.Lock() + + @classmethod + def from_url(cls, url: str) -> Self: + return cls(url) + + def publish(self, topic: str, message: str) -> None: + raise NotImplementedError("TODO: publish with the __TITLE__ client") + + def receive(self, topic: str, timeout: float = 1.0) -> str | None: + raise NotImplementedError("TODO: receive with the __TITLE__ client") + + def close(self) -> None: + pass +''' + +BACKEND_TEST = '''\ +"""__TITLE__-specific behaviour. + +The shared contract tests (test_messaging.py) also run against a real server when +__ENV__ is set, as CI's broker integration job does: + + __ENV__=__TEST_URL__ uv run pytest packages/messaging +""" + +import os + +import pytest + +from messaging import broker_from_url +from messaging.backends.__MODULE__ import __CLASS__ + +URL = os.environ.get("__ENV__") + + +@pytest.mark.parametrize("url", [__SCHEME_URLS__]) +def test_url_selects___MODULE__(url: str) -> None: + # Building a broker never connects; the first publish/receive does. + with broker_from_url(url) as broker: + assert isinstance(broker, __CLASS__) + + +@pytest.mark.skipif(not URL, reason="__ENV__ not set") +def test_messages_wait_for_a_later_consumer(topic: str) -> None: + assert URL + with broker_from_url(URL) as producer: + producer.publish(topic, "queued") + with broker_from_url(URL) as consumer: + assert consumer.receive(topic, timeout=2) == "queued" +''' + +ENV_FILE = """\ +# docker compose --env-file brokers/__NAME__.env up --build +COMPOSE_PROFILES=__NAME__ +BROKER_URL=__COMPOSE_URL__ +""" + + +# --------------------------------------------------------------------------- helpers + + +def fail(message: str) -> None: + print(f"error: {message}", file=sys.stderr) + sys.exit(1) + + +def render(template: str, values: dict[str, str]) -> str: + out = template + for key, value in values.items(): + out = out.replace(f"__{key}__", value) + return out + + +def rel(path: Path) -> str: + return str(path.relative_to(ROOT)) + + +class Changes: + """New file contents, keyed by path; edits to one file accumulate.""" + + def changed(self) -> dict[Path, str]: + return {p: c for p, c in self.files.items() if p in self.created or c != p.read_text()} + + def __init__(self) -> None: + self.files: dict[Path, str] = {} + self.created: set[Path] = set() + + def text(self, path: Path) -> str: + if path not in self.files: + self.files[path] = path.read_text() + return self.files[path] + + def set(self, path: Path, content: str) -> None: + self.text(path) + self.files[path] = content + + def create(self, path: Path, content: str) -> None: + if path.exists(): + fail(f"{rel(path)} already exists") + self.files[path] = content + self.created.add(path) + + +def sub_once(text: str, pattern: str, repl: str, where: str, flags: int = re.M) -> str: + """Apply a regex substitution that must match exactly once, or stop with an error.""" + new, count = re.subn(pattern, repl, text, count=1, flags=flags) + if count != 1: + fail(f"could not find where to edit {where}; edit it by hand (see SKILL.md)") + return new + + +def tidy(paths: list[Path]) -> None: + """Sort imports and format the edited Python files (long lines get wrapped).""" + files = [rel(p) for p in paths if p.suffix == ".py"] + for cmd in (["ruff", "check", "--fix", "--select", "I", *files], ["ruff", "format", *files]): + try: + subprocess.run( + ["uv", "run", "--no-sync", *cmd], cwd=ROOT, check=True, capture_output=True + ) + except (OSError, subprocess.CalledProcessError): + print(f" note: could not run `{' '.join(cmd[:2])}`; run it yourself", file=sys.stderr) + return + + +# --------------------------------------------------------------------------- edits + + +def edit_registry(ch: Changes, a: argparse.Namespace) -> None: + path = MESSAGING / "src/messaging/broker.py" + text = ch.text(path) + backends = re.search(r"^_BACKENDS: .*? = \{\n(.*?)^\}", text, re.M | re.S) + if backends is None: + fail("could not find `_BACKENDS = {...}` in broker.py") + raise AssertionError # unreachable, for type checkers + for scheme in a.schemes: + if re.search(rf'^\s*"{re.escape(scheme)}":', backends.group(1), re.M): + fail(f"scheme {scheme!r} is already registered in broker.py") + entries = "".join( + f' "{s}": "messaging.backends.{a.module}:{a.class_name}",\n' for s in a.schemes + ) + text = text[: backends.end(1)] + entries + text[backends.end(1) :] + + if a.dependency: + entry = rf'\1, "{a.module}": "{a.name}"}}' + text = sub_once(text, r"^(_EXTRAS = \{.*?)\}", entry, "_EXTRAS in broker.py") + + # Module docstring: the list of example URLs, one per backend. + doc_end = text.index('"""', 3) + lines = text[:doc_end].split("\n") + url_rows = [i for i, line in enumerate(lines) if re.match(r"^ \S+://", line)] + if url_rows: + last = lines[url_rows[-1]] + column = len(last) - len(last.split("://", 1)[1].split(" ", 1)[1].lstrip()) + url = a.compose_url or f"{a.schemes[0]}://..." + note = f"{a.title} (needs messaging[{a.name}])" if a.dependency else a.title + lines.insert(url_rows[-1] + 1, f" {url}".ljust(max(column, len(url) + 6)) + note) + text = "\n".join(lines) + text[doc_end:] + ch.set(path, text) + + +def edit_messaging_pyproject(ch: Changes, a: argparse.Namespace) -> None: + if not a.dependency: + return + path = MESSAGING / "pyproject.toml" + text = ch.text(path) + if re.search(rf"^{a.name}\s*=", text, re.M): + fail(f"packages/messaging already has an extra named {a.name!r}") + text = sub_once( + text, + r"(^\[project\.optional-dependencies\]\n(?:[^\n\[][^\n]*\n)*)", + rf'\g<1>{a.name} = ["{a.dependency}"]\n', + "[project.optional-dependencies] in packages/messaging/pyproject.toml", + ) + ch.set(path, text) + + +def edit_root_pyproject(ch: Changes, a: argparse.Namespace) -> None: + path = ROOT / "pyproject.toml" + text = ch.text(path) + if a.dependency: + text = sub_once( + text, + r"(^ # Every broker client.*\n)", + rf'\g<1> "{a.dependency}",\n', + 'the "# Every broker client" comment in the dev group of pyproject.toml', + ) + if a.untyped: + override = ( + "[[tool.mypy.overrides]]\n" + f'module = ["{a.client_import}", "{a.client_import}.*"] # ships no type hints\n' + "ignore_missing_imports = true\n\n" + ) + text = sub_once( + text, + r"(^# -+ pytest\n)", + override.replace("\\", "\\\\") + r"\1", + "the pytest section of pyproject.toml", + ) + ch.set(path, text) + + +def edit_apps(ch: Changes, a: argparse.Namespace) -> list[str]: + """Give every app that carries broker extras the new one too.""" + touched = [] + if not a.dependency: + return touched + for pyproject in sorted(ROOT.glob("apps/*/pyproject.toml")): + text = ch.text(pyproject) + rows = list(re.finditer(r'^\w+ = \["messaging\[\w+\]"\]\n', text, re.M)) + if not rows: + continue + end = rows[-1].end() + ch.set(pyproject, text[:end] + f'{a.name} = ["messaging[{a.name}]"]\n' + text[end:]) + dockerfile = pyproject.parent / "Dockerfile" + if dockerfile.exists(): + ch.set( + dockerfile, + sub_once( + ch.text(dockerfile), + r'^(ARG BROKER_EXTRAS=")([^"]*)"', + rf'\1\2 {a.name}"', + f"ARG BROKER_EXTRAS in {rel(dockerfile)}", + ), + ) + touched.append(pyproject.parent.name) + return touched + + +def edit_compose(ch: Changes, a: argparse.Namespace) -> None: + path = ROOT / "compose.yaml" + text = ch.text(path) + if a.dependency: + text = re.sub(r"\$\{BROKER_EXTRAS:-([^}]*)\}", rf"${{BROKER_EXTRAS:-\1 {a.name}}}", text) + if a.image: + if re.search(rf"^ {re.escape(a.name)}:\s*$", text, re.M): + fail(f"compose.yaml already has a service named {a.name!r}") + block = [f" {a.name}:", f" profiles: [{a.name}]", f" image: {a.image}"] + if a.container_env: + block.append(" environment:") + block += [f" {k}: {json.dumps(v)}" for k, v in a.container_env] + if a.healthcheck: + block += [ + " healthcheck:", + f' test: ["CMD-SHELL", {json.dumps(a.healthcheck)}]', + " interval: 5s", + " timeout: 10s", + " retries: 12", + ] + text = sub_once( + text, + r"(^ # -+ services\n)", + "\n".join(block).replace("\\", "\\\\") + r"\n\n\1", + "the `# --- services` marker in compose.yaml", + ) + condition = "service_healthy" if a.healthcheck else "service_started" + text = sub_once( + text, + r"(^x-broker-depends: &broker-depends\n(?: .*\n)*)", + rf"\g<1> {a.name}: {{ condition: {condition}, required: false }}\n", + "the x-broker-depends anchor in compose.yaml", + ) + ch.set(path, text) + + +def edit_conftest(ch: Changes, a: argparse.Namespace) -> None: + path = MESSAGING / "tests/conftest.py" + ch.set( + path, + sub_once( + ch.text(path), + r"(^REAL_BROKERS = \{\n(?: .*\n)*)", + rf'\g<1> "{a.name}": "{a.test_env}",\n', + "REAL_BROKERS in packages/messaging/tests/conftest.py", + ), + ) + + +def edit_ci(ch: Changes, a: argparse.Namespace) -> None: + path = ROOT / ".github/workflows/ci.yml" + if not path.exists() or not a.image: + return + text = ch.text(path) + job = re.search(r"^ brokers:\n(?:(?: .*|[ \t]*)\n)*", text, re.M) + if job is None: + fail("could not find the `brokers` job in ci.yml") + raise AssertionError # unreachable, for type checkers + body = job.group(0) + service = [ + f" {a.name}:", + f" image: {a.image}", + f' ports: ["{a.port}:{a.port}"]', + ] + if a.container_env: + service.append(" env:") + service += [f" {k}: {json.dumps(v)}" for k, v in a.container_env] + if a.healthcheck: + service += [ + " options: >-", + f" --health-cmd {json.dumps(a.healthcheck)} --health-interval 5s", + " --health-timeout 10s --health-retries 20", + ] + body = sub_once( + body, + r"(^ steps:\n)", + "\n".join(service).replace("\\", "\\\\") + r"\n\1", + "`steps:` of the brokers job in ci.yml", + ) + rows = list(re.finditer(r"^ MESSAGING_TEST_\w+: .*\n", body, re.M)) + if not rows: + fail("could not find the MESSAGING_TEST_* env vars of the brokers job in ci.yml") + end = rows[-1].end() + body = body[:end] + f" {a.test_env}: {a.test_url}\n" + body[end:] + body = re.sub(r"(name: Broker integration \([^)]*)\)", rf"\1 + {a.title})", body, count=1) + text = text[: job.start()] + body + text[job.end() :] + text = sub_once( + text, + r"^( broker: \[)([^\]]*)\]", + rf"\1\2, {a.name}]", + "the compose job's broker matrix in ci.yml", + ) + ch.set(path, text) + + +# --------------------------------------------------------------------------- main + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("name", help="short lowercase id: extra, compose service, env file") + parser.add_argument("--title", help="display name, e.g. NATS (default: Name)") + parser.add_argument("--scheme", action="append", dest="schemes", help="URL scheme (repeatable)") + parser.add_argument("--class", dest="class_name", help="default: <Title>Broker") + parser.add_argument("--module", help="module under messaging/backends (default: name)") + parser.add_argument("--dependency", help='client library requirement, e.g. "nats-py>=2.9"') + parser.add_argument("--client-import", help="top-level import name of the client library") + parser.add_argument("--untyped", action="store_true", help="add a mypy ignore override") + parser.add_argument("--image", help="Docker image of the server (compose + CI)") + parser.add_argument("--port", type=int, help="the server's client port (with --image)") + parser.add_argument("--healthcheck", help="shell command that succeeds once it is ready") + parser.add_argument( + "--container-env", action="append", default=[], help="KEY=VALUE for the server" + ) + parser.add_argument("--compose-url", help="BROKER_URL inside compose") + parser.add_argument("--test-url", help="URL the integration tests use (from the host)") + parser.add_argument("--test-env", help="default: MESSAGING_TEST_<NAME>_URL") + parser.add_argument("--dry-run", action="store_true") + a = parser.parse_args() + + if not NAME_RE.match(a.name): + fail(f"{a.name!r} must be lowercase letters and digits, e.g. nats or sqs") + a.title = a.title or a.name.capitalize() + a.schemes = [s.lower() for s in (a.schemes or [a.name])] + for scheme in a.schemes: + if not SCHEME_RE.match(scheme): + fail(f"{scheme!r} is not a valid URL scheme") + a.module = a.module or a.name + if not a.module.isidentifier(): + fail(f"--module {a.module!r} is not a Python identifier") + a.class_name = a.class_name or re.sub(r"\W", "", a.title.title()) + "Broker" + if not a.class_name.isidentifier(): + fail(f"--class {a.class_name!r} is not a Python identifier") + if a.untyped and not a.client_import: + fail("--untyped needs --client-import (the module mypy should ignore)") + if a.image and not a.port: + fail("--image needs --port (the port clients connect to)") + if a.healthcheck and '"' in a.healthcheck: + fail("--healthcheck must not contain double quotes") + for item in a.container_env: + if not ENV_RE.match(item): + fail(f"--container-env {item!r} is not KEY=VALUE") + a.container_env = [tuple(item.split("=", 1)) for item in a.container_env] + if a.image: + a.compose_url = a.compose_url or f"{a.schemes[0]}://{a.name}:{a.port}" + a.test_url = a.test_url or f"{a.schemes[0]}://localhost:{a.port}" + a.test_env = a.test_env or f"MESSAGING_TEST_{a.name.upper()}_URL" + return a + + +def main() -> int: + a = parse_args() + backend = MESSAGING / f"src/messaging/backends/{a.module}.py" + test = MESSAGING / f"tests/test_{a.module}.py" + if backend.exists(): + fail(f"{rel(backend)} already exists; pick another name or --module") + clash = [p for p in ROOT.glob(f"*/*/tests/**/{test.name}") if ".venv" not in p.parts] + if clash: + fail(f"{rel(clash[0])} exists; test file names must be unique (use --module)") + + values = { + "TITLE": a.title, + "CLASS": a.class_name, + "MODULE": a.module, + "NAME": a.name, + "ENV": a.test_env, + "TEST_URL": a.test_url or f"{a.schemes[0]}://localhost", + "COMPOSE_URL": a.compose_url or "", + "SCHEME_URLS": ", ".join(json.dumps(f"{s}://localhost") for s in a.schemes), + } + ch = Changes() + ch.create(backend, render(BACKEND, values)) + ch.create(test, render(BACKEND_TEST, values)) + edit_registry(ch, a) + edit_messaging_pyproject(ch, a) + edit_root_pyproject(ch, a) + apps = edit_apps(ch, a) + edit_compose(ch, a) + edit_conftest(ch, a) + edit_ci(ch, a) + if a.compose_url: + ch.create(ROOT / f"brokers/{a.name}.env", render(ENV_FILE, values)) + + if a.dry_run: + for path, new in ch.changed().items(): + old = "" if path in ch.created else path.read_text() + sys.stdout.writelines( + difflib.unified_diff( + old.splitlines(keepends=True), + new.splitlines(keepends=True), + "/dev/null" if path in ch.created else f"a/{rel(path)}", + f"b/{rel(path)}", + ) + ) + return 0 + + changed = ch.changed() + for path, content in changed.items(): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content) + print(f" {'created' if path in ch.created else 'updated'} {rel(path)}") + tidy(list(changed)) + + print(f"\nRegistered {', '.join(s + '://' for s in a.schemes)} -> {a.class_name}.") + if apps: + print(f"Broker extra `{a.name}` added to: {', '.join(apps)}.") + if not a.image: + print("No --image: compose.yaml and CI have no server for it; see SKILL.md step 3.") + print( + f"\nNext: implement {rel(backend)}, then run\n" + " uv lock && uv sync --all-packages && uv run ruff check . && uv run mypy " + "&& uv run pytest packages/messaging" + ) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.claude/skills/new-service/SKILL.md b/.claude/skills/new-service/SKILL.md index 2a237e0..8a4a343 100644 --- a/.claude/skills/new-service/SKILL.md +++ b/.claude/skills/new-service/SKILL.md @@ -62,7 +62,7 @@ The script refuses invalid names, existing members and unknown contracts. It wri | `tests/test_<pkg>.py` | starter tests (health check / consume loop) | | root `pyproject.toml` | adds the import name to ruff `known-first-party` and `apps/<name>/src` to `mypy_path` | | `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 | +| `pyproject.toml` + `Dockerfile` (broker services) | one extra per broker client (read from `packages/messaging/pyproject.toml`) 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. Nothing to edit there. diff --git a/.claude/skills/new-service/scripts/scaffold.py b/.claude/skills/new-service/scripts/scaffold.py index 132b3df..5e6959b 100644 --- a/.claude/skills/new-service/scripts/scaffold.py +++ b/.claude/skills/new-service/scripts/scaffold.py @@ -20,6 +20,7 @@ import re import subprocess import sys +import tomllib from pathlib import Path ROOT = Path(__file__).resolve().parents[4] @@ -299,18 +300,19 @@ def runner() -> None: depends_on: *broker-depends """ +# The broker extras are read from packages/messaging/pyproject.toml (see broker_extras()), +# so a backend added with the new-broker skill is picked up here automatically. BROKER_EXTRAS_TOML = """ # Broker client libraries, picked at image build time (Dockerfile ARG BROKER_EXTRAS). # The code only uses the `messaging.Broker` interface; BROKER_URL picks the backend. [project.optional-dependencies] -redis = ["messaging[redis]"] -rabbitmq = ["messaging[rabbitmq]"] +__EXTRA_LINES__ """ DOCKER_BROKER_DOC = """# # BROKER_EXTRAS chooses which broker client libraries go into the image (default: all, -# so BROKER_URL alone picks redis://, amqp:// or tcp://). memory:// and tcp:// need none. -# docker build --build-arg BROKER_EXTRAS=rabbitmq -f apps/__NAME__/Dockerfile -t __NAME__ . +# so BROKER_URL alone picks the backend). memory:// and tcp:// need none. +# docker build --build-arg BROKER_EXTRAS=__FIRST_EXTRA__ -f apps/__NAME__/Dockerfile -t __NAME__ . """ COMPOSE_WORKER = """ @@ -371,6 +373,12 @@ def tidy(app_dir: Path) -> None: return +def broker_extras() -> list[str]: + """The optional extras of packages/messaging: one per broker client library.""" + data = tomllib.loads((ROOT / "packages/messaging/pyproject.toml").read_text()) + return list(data.get("project", {}).get("optional-dependencies", {})) + + def contracts_exports() -> set[str]: init = ROOT / "packages/contracts/src/contracts/__init__.py" return set(re.findall(r'"([A-Za-z_][A-Za-z0-9_]*)"', init.read_text())) @@ -419,6 +427,7 @@ def main() -> int: ) description = description.replace('"', "'") uses_broker = is_worker or args.broker + extras = broker_extras() if uses_broker else [] deps = ["contracts"] if uses_broker: @@ -439,9 +448,19 @@ def main() -> int: else "" ), "SOURCES": sources, - "BROKER_EXTRAS_TOML": BROKER_EXTRAS_TOML if uses_broker else "", - "DOCKER_BROKER_DOC": DOCKER_BROKER_DOC.replace("__NAME__", name) if uses_broker else "", - "DOCKER_BROKER_ARG": 'ARG BROKER_EXTRAS="redis rabbitmq"\n' if uses_broker else "", + "BROKER_EXTRAS_TOML": ( + BROKER_EXTRAS_TOML.replace( + "__EXTRA_LINES__", "\n".join(f'{e} = ["messaging[{e}]"]' for e in extras) + ) + if uses_broker and extras + else "" + ), + "DOCKER_BROKER_DOC": ( + DOCKER_BROKER_DOC.replace("__NAME__", name).replace("__FIRST_EXTRA__", extras[0]) + if uses_broker and extras + else "" + ), + "DOCKER_BROKER_ARG": f'ARG BROKER_EXTRAS="{" ".join(extras)}"\n' if uses_broker else "", "DOCKER_BROKER_ARG_STAGE": "ARG BROKER_EXTRAS\n" if uses_broker else "", "DOCKER_EXTRA_FLAGS": ( ' $(for e in ${BROKER_EXTRAS}; do printf -- "--extra %s " "$e"; done)' diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index ff22175..624eab3 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -44,7 +44,7 @@ flowchart LR root --> rootfiles["pyproject.toml<br/>(workspace + ruff/mypy/pytest config)<br/>uv.lock · compose.yaml · .env"] root --> brokers["brokers/<br/>redis.env · rabbitmq.env · tcp.env"] root --> ci[".github/workflows/ci.yml<br/>scripts/ci/affected.py<br/>scripts/ci/compose_smoke.sh"] - root --> tooling[".claude/skills/new-service/<br/>(scaffold a wired-in service)"] + root --> tooling[".claude/skills/<br/>new-service · new-broker<br/>(scaffold a wired-in service or backend)"] root --> docs["docs/<br/>demo.gif · brokers.gif (+ .mp4)<br/>demo/player.html · demo/record.mjs"] root --> pkgs["packages/ (libraries)"] root --> apps["apps/ (deployables)"] @@ -284,13 +284,24 @@ order, timeouts, independent topics, large and non-ASCII payloads, and concurren ### Adding another broker (Kafka, NATS, SQS, ...) +With Claude Code, ask it to add the broker: the `new-broker` skill (`.claude/skills/new-broker/`) +checks that the transport fits the contract, does every step below and verifies the result. The +wiring alone is one command (`--dry-run` prints the diff first): + +```bash +python3 .claude/skills/new-broker/scripts/scaffold.py nats --title NATS --dependency "nats-py>=2.9" \ + --image nats:2-alpine --port 4222 --healthcheck "wget -q -O- localhost:8222/healthz" +``` + +It leaves you the `publish`/`receive` logic, the backend's own tests and the docs. By hand: + 1. Add `packages/messaging/src/messaging/backends/<name>.py` with a `Broker` subclass and a `from_url(cls, url)` classmethod. 2. Map its URL scheme in `_BACKENDS` in `messaging/broker.py` (or call `register_backend("nats", NatsBroker.from_url)` from your own code), and add the client library as a new extra in `packages/messaging/pyproject.toml` and the apps' extras. -3. Add it to the `any_broker` fixture in `packages/messaging/tests/conftest.py`, so the - contract tests run against it. +3. Add it to `REAL_BROKERS` (or, for an in-process fake, the `any_broker` params) in + `packages/messaging/tests/conftest.py`, so the contract tests run against it. 4. Add a service with a `profiles: [<name>]` entry to `compose.yaml` and a `brokers/<name>.env`, and add it to the `compose` matrix in CI. diff --git a/README.md b/README.md index ac6a76d..5a14bce 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ Pick the path that matches what you want to do: | **Add a new HTTP API or worker** | Scaffold one that is fully wired in (package, Dockerfile, compose, lint/type config, tests): `python3 .claude/skills/new-service/scripts/scaffold.py inventory-api --kind http` (or `--kind worker --event ... --topic ...`). With Claude Code, just ask it to "add a new service"; the bundled `new-service` skill does the whole job. See [Adding a new service](ARCHITECTURE.md#adding-a-new-service). | | **Add a shared library** | Create it under `packages/` and depend on it from your apps; see [Adding a member](#adding-a-member). | | **Share data between services** | Put request/response models and events in `packages/contracts`, so producer and consumer use the same typed definition. | -| **Use a different message broker** | Switch between Redis, RabbitMQ and TCP with an env file (see below), or add a new backend (Kafka, NATS, SQS, ...) by implementing the `Broker` interface; see [ARCHITECTURE.md](ARCHITECTURE.md#adding-another-broker-kafka-nats-sqs-). | +| **Use a different message broker** | Switch between Redis, RabbitMQ and TCP with an env file (see below), or add a new backend (Kafka, NATS, SQS, ...) by implementing the `Broker` interface. The bundled `new-broker` skill wires it into packages, images, compose, tests and CI (ask Claude Code to "add a NATS broker"); see [ARCHITECTURE.md](ARCHITECTURE.md#adding-another-broker-kafka-nats-sqs-). | | **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). | @@ -55,7 +55,7 @@ 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) +├── .claude/skills/ # Claude Code skills: new-service and new-broker scaffold fully wired members ├── docs/ # demo videos (+ the player/recorder that renders them) ├── packages/ # reusable libraries │ ├── contracts/ # shared pydantic models: API payloads + events diff --git a/packages/messaging/tests/conftest.py b/packages/messaging/tests/conftest.py index 2c79fb4..b1cb52f 100644 --- a/packages/messaging/tests/conftest.py +++ b/packages/messaging/tests/conftest.py @@ -20,8 +20,12 @@ from messaging.backends.redis_broker import RedisBroker from messaging.backends.tcp import TcpBrokerServer -REDIS_URL = os.environ.get("MESSAGING_TEST_REDIS_URL") -AMQP_URL = os.environ.get("MESSAGING_TEST_AMQP_URL") +# Real servers the contract tests also run against: backend -> env var holding its URL. +# Each one is skipped unless its variable is set. The new-broker skill adds entries here. +REAL_BROKERS = { + "redis": "MESSAGING_TEST_REDIS_URL", + "rabbitmq": "MESSAGING_TEST_AMQP_URL", +} @pytest.fixture @@ -39,13 +43,12 @@ def tcp_server() -> Iterator[TcpBrokerServer]: "memory", "fakeredis", "tcp", - pytest.param( - "redis", - marks=pytest.mark.skipif(not REDIS_URL, reason="MESSAGING_TEST_REDIS_URL not set"), - ), - pytest.param( - "rabbitmq", - marks=pytest.mark.skipif(not AMQP_URL, reason="MESSAGING_TEST_AMQP_URL not set"), + *( + pytest.param( + kind, + marks=pytest.mark.skipif(not os.environ.get(var), reason=f"{var} not set"), + ) + for kind, var in REAL_BROKERS.items() ), ] ) @@ -60,12 +63,8 @@ def any_broker(request: pytest.FixtureRequest) -> Iterator[Broker]: elif kind == "tcp": server: TcpBrokerServer = request.getfixturevalue("tcp_server") broker = broker_from_url(f"tcp://127.0.0.1:{server.port}") - elif kind == "redis": - assert REDIS_URL - broker = broker_from_url(REDIS_URL) else: - assert AMQP_URL - broker = broker_from_url(AMQP_URL) + broker = broker_from_url(os.environ[REAL_BROKERS[kind]]) with broker: yield broker diff --git a/scripts/ci/compose_smoke.sh b/scripts/ci/compose_smoke.sh index 1763cea..c0e67ae 100755 --- a/scripts/ci/compose_smoke.sh +++ b/scripts/ci/compose_smoke.sh @@ -1,11 +1,11 @@ #!/usr/bin/env bash # End-to-end check of the compose stack with one broker: -# scripts/ci/compose_smoke.sh redis|rabbitmq|tcp +# scripts/ci/compose_smoke.sh <broker> (any brokers/<broker>.env, e.g. redis) # Starts the stack with brokers/<name>.env, places an order through orders-api and # waits for notifier-worker to log the confirmation, then tears everything down. set -euo pipefail -broker="${1:?usage: $0 redis|rabbitmq|tcp}" +broker="${1:?usage: $0 <broker> (one of: $(cd brokers && ls *.env | sed "s/\.env$//" | tr "\n" " "))}" env_file="brokers/${broker}.env" [ -f "$env_file" ] || { echo "no such broker env file: $env_file" >&2; exit 2; } compose=(docker compose --env-file "$env_file")