From 13a8af4d7159d365e4d8853fde993193f7b34689 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 4 Nov 2026 19:48:05 +0000 Subject: [PATCH] Make the messaging transport pluggable (Redis, RabbitMQ, TCP, in-memory) Services now depend only on the abstract `messaging.Broker` interface. The backend is chosen at start-up from the BROKER_URL scheme: - redis:// and rediss:// -> RedisBroker (messaging[redis] extra) - amqp:// and amqps:// -> RabbitMQBroker via pika (messaging[rabbitmq] extra) - tcp://host:port -> TcpBroker, talking to the new apps/tcp-broker server - memory:// -> InMemoryBroker, for tests Backends are imported lazily and can be added with register_backend(). Every backend runs the same contract tests; real Redis and RabbitMQ join in when MESSAGING_TEST_REDIS_URL / MESSAGING_TEST_AMQP_URL are set. Docker and compose: - orders-api and notifier-worker Dockerfiles take a BROKER_EXTRAS build arg (default "redis rabbitmq") that decides which client libraries are baked in. - compose.yaml has one profile per broker; .env (default Redis) and brokers/{redis,rabbitmq,tcp}.env set COMPOSE_PROFILES and BROKER_URL. CI gains a broker integration job (Redis + RabbitMQ service containers) and an end-to-end compose job per broker. The new-service scaffold, README and ARCHITECTURE.md (with new diagrams) are updated to match. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SE2PhKYV7M9PYq4fFJu19d --- .claude/skills/new-service/SKILL.md | 3 +- .../skills/new-service/scripts/scaffold.py | 48 +++- .env | 5 + .github/workflows/ci.yml | 49 +++- .gitignore | 2 + ARCHITECTURE.md | 196 +++++++++++++-- README.md | 21 +- apps/notifier-worker/Dockerfile | 12 +- apps/notifier-worker/pyproject.toml | 7 + .../src/notifier_worker/main.py | 4 +- .../src/notifier_worker/worker.py | 8 +- apps/notifier-worker/tests/test_worker.py | 2 +- apps/orders-api/Dockerfile | 12 +- apps/orders-api/pyproject.toml | 7 + apps/orders-api/src/orders_api/app.py | 1 + apps/tcp-broker/Dockerfile | 35 +++ apps/tcp-broker/pyproject.toml | 20 ++ apps/tcp-broker/src/tcp_broker/__init__.py | 1 + apps/tcp-broker/src/tcp_broker/main.py | 56 +++++ apps/tcp-broker/src/tcp_broker/py.typed | 0 apps/tcp-broker/tests/test_tcp_broker.py | 39 +++ brokers/rabbitmq.env | 3 + brokers/redis.env | 3 + brokers/tcp.env | 3 + compose.yaml | 59 ++++- packages/messaging/pyproject.toml | 11 +- packages/messaging/src/messaging/__init__.py | 25 +- .../src/messaging/backends/__init__.py | 6 + .../src/messaging/backends/memory.py | 38 +++ .../src/messaging/backends/rabbitmq.py | 114 +++++++++ .../src/messaging/backends/redis_broker.py | 31 +++ .../messaging/src/messaging/backends/tcp.py | 236 ++++++++++++++++++ packages/messaging/src/messaging/broker.py | 122 ++++++--- packages/messaging/tests/conftest.py | 76 ++++++ packages/messaging/tests/test_messaging.py | 101 +++++--- packages/messaging/tests/test_rabbitmq.py | 32 +++ packages/messaging/tests/test_registry.py | 71 ++++++ packages/messaging/tests/test_tcp.py | 128 ++++++++++ pyproject.toml | 9 + scripts/ci/compose_smoke.sh | 40 +++ uv.lock | 62 ++++- 41 files changed, 1560 insertions(+), 138 deletions(-) create mode 100644 .env create mode 100644 apps/tcp-broker/Dockerfile create mode 100644 apps/tcp-broker/pyproject.toml create mode 100644 apps/tcp-broker/src/tcp_broker/__init__.py create mode 100644 apps/tcp-broker/src/tcp_broker/main.py create mode 100644 apps/tcp-broker/src/tcp_broker/py.typed create mode 100644 apps/tcp-broker/tests/test_tcp_broker.py create mode 100644 brokers/rabbitmq.env create mode 100644 brokers/redis.env create mode 100644 brokers/tcp.env create mode 100644 packages/messaging/src/messaging/backends/__init__.py create mode 100644 packages/messaging/src/messaging/backends/memory.py create mode 100644 packages/messaging/src/messaging/backends/rabbitmq.py create mode 100644 packages/messaging/src/messaging/backends/redis_broker.py create mode 100644 packages/messaging/src/messaging/backends/tcp.py create mode 100644 packages/messaging/tests/conftest.py create mode 100644 packages/messaging/tests/test_rabbitmq.py create mode 100644 packages/messaging/tests/test_registry.py create mode 100644 packages/messaging/tests/test_tcp.py create mode 100755 scripts/ci/compose_smoke.sh diff --git a/.claude/skills/new-service/SKILL.md b/.claude/skills/new-service/SKILL.md index 2beb617..ea3e129 100644 --- a/.claude/skills/new-service/SKILL.md +++ b/.claude/skills/new-service/SKILL.md @@ -61,7 +61,8 @@ 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_URL` + redis dependency when needed | +| `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 | +| `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. Nothing to edit there. diff --git a/.claude/skills/new-service/scripts/scaffold.py b/.claude/skills/new-service/scripts/scaffold.py index 5b07dc6..24f3213 100644 --- a/.claude/skills/new-service/scripts/scaffold.py +++ b/.claude/skills/new-service/scripts/scaffold.py @@ -35,7 +35,7 @@ description = "__DESCRIPTION__" requires-python = ">=3.13" __DEPS_COMMENT__dependencies = [__DEPS__] - +__BROKER_EXTRAS_TOML__ [project.scripts] __NAME__ = "__PKG__.main:main" @@ -55,13 +55,13 @@ # Build from the repo root so the workspace lockfile and sibling packages are in context: # docker build -f apps/__NAME__/Dockerfile -t __NAME__ . # Only this app and the workspace packages it depends on are installed. - +__DOCKER_BROKER_DOC__ ARG PYTHON_VERSION=3.13 ARG APP=__NAME__ - +__DOCKER_BROKER_ARG__ FROM ghcr.io/astral-sh/uv:python${PYTHON_VERSION}-bookworm-slim AS builder ARG APP -ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy UV_PYTHON_DOWNLOADS=0 +__DOCKER_BROKER_ARG_STAGE__ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy UV_PYTHON_DOWNLOADS=0 WORKDIR /app # 1) Third-party deps only (cached layer, rebuilt only when the lock changes). @@ -70,12 +70,12 @@ --mount=type=bind,source=pyproject.toml,target=pyproject.toml \\ --mount=type=bind,source=packages,target=packages \\ --mount=type=bind,source=apps,target=apps \\ - uv sync --frozen --no-dev --no-install-workspace --package ${APP} + uv sync --frozen --no-dev --no-install-workspace --package ${APP}__DOCKER_EXTRA_FLAGS__ # 2) This app + its workspace deps, installed as real (non-editable) wheels. COPY . . RUN --mount=type=cache,target=/root/.cache/uv \\ - uv sync --frozen --no-dev --no-editable --package ${APP} + uv sync --frozen --no-dev --no-editable --package ${APP}__DOCKER_EXTRA_FLAGS__ FROM python:${PYTHON_VERSION}-slim-bookworm AS runtime ARG APP @@ -191,6 +191,7 @@ def test_health(client: TestClient) -> None: class Settings(ServiceSettings): service_name: str = "__NAME__" + # The scheme picks the transport: redis://, amqp://, tcp:// or memory://. broker_url: str = "redis://localhost:6379/0" @@ -204,7 +205,8 @@ def handle_signal(signum: int, frame: FrameType | None) -> None: signal.signal(signal.SIGTERM, handle_signal) signal.signal(signal.SIGINT, handle_signal) - run(broker_from_url(settings.broker_url), stop) + with broker_from_url(settings.broker_url) as broker: + run(broker, stop) if __name__ == "__main__": @@ -248,6 +250,7 @@ def run(broker: Broker, stop: threading.Event, handler: Handler = handle) -> Non process_one(broker, handler) except Exception: # keep the worker alive; a real one would dead-letter the event log.exception("failed to process event") + stop.wait(1.0) # don't spin while the broker is unreachable log.info("stopped") ''' @@ -289,11 +292,25 @@ def runner() -> None: ports: ["__HOST_PORT__:8000"] """ +# Uses the anchors defined at the top of compose.yaml, so the service follows whichever +# broker the env file selects (BROKER_URL + COMPOSE_PROFILES). COMPOSE_BROKER = """\ - environment: - BROKER_URL: redis://redis:6379/0 - depends_on: - redis: { condition: service_healthy } + environment: *broker-env + depends_on: *broker-depends +""" + +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]"] +""" + +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__ . """ COMPOSE_WORKER = """ @@ -420,6 +437,15 @@ 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 "", + "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)' + if uses_broker + else "" + ), "RUNTIME_EXTRA": "" if is_worker else HTTP_RUNTIME_EXTRA, "EVENT": args.event or "", "TOPIC": args.topic or "", diff --git a/.env b/.env new file mode 100644 index 0000000..f0301ec --- /dev/null +++ b/.env @@ -0,0 +1,5 @@ +# Default settings for `docker compose` (read automatically from this folder). +# Committed on purpose: it holds no secrets, only which broker the local stack uses. +# To switch broker, pass another file instead: docker compose --env-file brokers/rabbitmq.env up +COMPOSE_PROFILES=redis +BROKER_URL=redis://redis:6379/0 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7d88b8a..63dc77d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -82,12 +82,59 @@ jobs: # Exit code 5 means "no tests collected"; don't fail a package for that. uv run pytest "$PKG_PATH" || [ $? -eq 5 ] + brokers: + # The contract tests in packages/messaging, run against real Redis and RabbitMQ + # servers (the unit test job covers memory, fakeredis and TCP only). + name: Broker integration (Redis + RabbitMQ) + needs: changes + if: contains(needs.changes.outputs.packages, '"messaging"') + runs-on: ubuntu-latest + services: + redis: + image: redis:7-alpine + ports: ["6379:6379"] + options: >- + --health-cmd "redis-cli ping" --health-interval 5s --health-retries 10 + rabbitmq: + image: rabbitmq:4-alpine + ports: ["5672:5672"] + options: >- + --health-cmd "rabbitmq-diagnostics -q ping" --health-interval 5s + --health-timeout 10s --health-retries 20 + steps: + - uses: actions/checkout@v5 + - uses: astral-sh/setup-uv@v7 + with: + enable-cache: true + cache-dependency-glob: uv.lock + - run: uv sync --all-packages + - name: pytest packages/messaging (real brokers) + env: + MESSAGING_TEST_REDIS_URL: redis://localhost:6379/0 + MESSAGING_TEST_AMQP_URL: amqp://guest:guest@localhost:5672/ + run: uv run pytest packages/messaging + + compose: + # Build the real images and send an order from orders-api to notifier-worker + # through each broker, exactly as `docker compose --env-file brokers/.env up` does. + name: End-to-end over ${{ matrix.broker }} + needs: changes + if: contains(needs.changes.outputs.packages, '"notifier-worker"') + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + broker: [redis, rabbitmq, tcp] + steps: + - uses: actions/checkout@v5 + - run: scripts/ci/compose_smoke.sh "${{ matrix.broker }}" + ci-ok: # Single required check for branch protection; passes when tests were # skipped because nothing relevant changed. name: CI OK if: always() - needs: [changes, lint, test] + needs: [changes, lint, test, brokers, compose] runs-on: ubuntu-latest steps: - name: Check results diff --git a/.gitignore b/.gitignore index 36584a9..7be9070 100644 --- a/.gitignore +++ b/.gitignore @@ -24,3 +24,5 @@ htmlcov/ # Env .env +# ...except the root one, which only holds non-secret compose defaults. +!/.env diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 6e1cff8..417ef38 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -11,9 +11,10 @@ The example system is a tiny shop: | `apps/catalog-api` | HTTP service | Owns the product list and prices. | | `apps/orders-api` | HTTP service | Accepts orders, prices them by calling `catalog-api`, publishes an `OrderPlaced` event. | | `apps/notifier-worker` | Background worker | Consumes `OrderPlaced` events and sends a confirmation to the customer. | +| `apps/tcp-broker` | Broker server | Optional, dependency-free message broker for `tcp://` URLs. | | `apps/cli` | Command-line app | The original "hello" example. | | `packages/contracts` | Library | Shared pydantic models: API payloads (`Product`, `Order`, ...) and events (`OrderPlaced`). | -| `packages/messaging` | Library | `Broker` interface with Redis (production) and in-memory (tests) implementations, plus typed `publish_event` / `receive_event`. | +| `packages/messaging` | Library | Transport-neutral `Broker` interface, backends for Redis, RabbitMQ, TCP and in-memory picked by `BROKER_URL`, plus typed `publish_event` / `receive_event`. | | `packages/servicekit` | Library | Settings from env vars, uniform logging, and (with the `http` extra) a FastAPI app factory with `/health`. | | `packages/core` | Library | The original greeting helper used by `apps/cli`. | @@ -24,11 +25,14 @@ The example system is a tiny shop: 2. **Services talk over the network, not through imports.** `orders-api` calls `catalog-api` over HTTP and reaches `notifier-worker` through the message broker. What they share is the *shape* of the data, in `packages/contracts`. -3. **One lockfile, one version of each dependency.** Every member resolves against the same +3. **Infrastructure is a plug, not a dependency.** Services code against the `Broker` + interface only. Which broker carries the messages (Redis, RabbitMQ, TCP, ...) is + configuration (`BROKER_URL`), so swapping it needs no code change. +4. **One lockfile, one version of each dependency.** Every member resolves against the same `uv.lock`, so there is no "works with my version" drift between services. -4. **Each app ships alone.** Every app has its own `Dockerfile` that installs only that app and +5. **Each app ships alone.** Every app has its own `Dockerfile` that installs only that app and the libraries it depends on, so each one is built, released and scaled on its own. -5. **CI tests what a change can break.** A change to a library re-tests the library and every +6. **CI tests what a change can break.** A change to a library re-tests the library and every app that depends on it; untouched members are skipped. ## Repository layout @@ -37,8 +41,9 @@ The example system is a tiny shop: flowchart LR root(["python-monorepo/"]) - root --> rootfiles["pyproject.toml
(workspace + ruff/mypy/pytest config)
uv.lock · compose.yaml"] - root --> ci[".github/workflows/ci.yml
scripts/ci/affected.py"] + 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 --> pkgs["packages/ (libraries)"] root --> apps["apps/ (deployables)"] @@ -50,6 +55,7 @@ flowchart LR apps --> catalog["catalog-api/"] apps --> orders["orders-api/"] apps --> notifier["notifier-worker/"] + apps --> tcpb["tcp-broker/"] apps --> cli["cli/"] orders --> member["Every member has the same shape:
pyproject.toml
src/<import_name>/
tests/
Dockerfile (apps only)"] @@ -66,6 +72,7 @@ flowchart TB catalog["catalog-api"] orders["orders-api"] notifier["notifier-worker"] + tcpb["tcp-broker"] cli["cli"] end @@ -81,6 +88,7 @@ flowchart TB settings(["pydantic-settings"]) fastapi(["fastapi + uvicorn"]) redis(["redis"]) + pika(["pika"]) httpx(["httpx"]) end @@ -93,23 +101,29 @@ flowchart TB notifier --> contracts notifier --> messaging notifier --> servicekit + tcpb --> messaging + tcpb --> servicekit cli --> core contracts --> pydantic messaging --> pydantic - messaging --> redis + messaging -. "redis extra" .-> redis + messaging -. "rabbitmq extra" .-> pika servicekit --> settings servicekit -. "http extra only" .-> fastapi ``` `notifier-worker` depends on plain `servicekit` (without the `http` extra), so FastAPI and -uvicorn never end up in its image. +uvicorn never end up in its image. In the same way, `messaging` itself needs only pydantic: +the Redis and RabbitMQ client libraries are extras (`messaging[redis]`, `messaging[rabbitmq]`) +that each app re-exports as its own `redis` / `rabbitmq` extras, and the Dockerfile decides +which ones go into the image. `tcp-broker` uses neither. | If you change... | CI tests... | | --- | --- | | `packages/contracts` | contracts, catalog-api, orders-api, notifier-worker | -| `packages/messaging` | messaging, orders-api, notifier-worker | -| `packages/servicekit` | servicekit, catalog-api, orders-api, notifier-worker | +| `packages/messaging` | messaging, orders-api, notifier-worker, tcp-broker (+ broker integration and end-to-end jobs) | +| `packages/servicekit` | servicekit, catalog-api, orders-api, notifier-worker, tcp-broker | | `packages/core` | core, cli | | `apps/orders-api` | orders-api only | | root `pyproject.toml`, `uv.lock`, CI files, `compose.yaml` | everything | @@ -123,7 +137,7 @@ sequenceDiagram actor Customer participant Orders as orders-api participant Catalog as catalog-api - participant Redis as Redis (broker) + participant Broker as Broker (Redis / RabbitMQ / TCP) participant Notifier as notifier-worker Customer->>Orders: POST /orders {customer_email, items} @@ -135,16 +149,95 @@ sequenceDiagram Orders-->>Customer: 422 unknown product else all SKUs found Orders->>Orders: compute total, store Order - Orders->>Redis: LPUSH orders.placed OrderPlaced(JSON) + Orders->>Broker: publish("orders.placed", OrderPlaced JSON) Orders-->>Customer: 201 Order - Notifier->>Redis: BRPOP orders.placed - Redis-->>Notifier: OrderPlaced + Notifier->>Broker: receive("orders.placed", timeout=1s) + Broker-->>Notifier: OrderPlaced Notifier->>Notifier: render message and send it end ``` The broker is a work queue: each event goes to exactly one worker replica, so running more -`notifier-worker` replicas spreads the load rather than sending duplicate notifications. +`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. + +## Messaging: a pluggable transport + +`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: + +```mermaid +classDiagram + direction LR + class Broker { + <> + +publish(topic, message) + +receive(topic, timeout) str | None + +close() + } + class InMemoryBroker { + memory:// + process-local, for tests + } + class RedisBroker { + redis:// rediss:// + LPUSH / BRPOP on a list + } + class RabbitMQBroker { + amqp:// amqps:// + durable queue, persistent messages + } + class TcpBroker { + tcp://host:port + JSON lines to apps/tcp-broker + } + Broker <|-- InMemoryBroker + Broker <|-- RedisBroker + Broker <|-- RabbitMQBroker + Broker <|-- TcpBroker +``` + +`broker_from_url(settings.broker_url)` reads the URL scheme and builds the matching backend. +Backends are imported lazily, so an image that left out the RabbitMQ client still starts with +`redis://` (and fails with a clear "install the `rabbitmq` extra" error if pointed at `amqp://`). + +```mermaid +flowchart LR + env["BROKER_URL env var"] --> settings["Settings.broker_url"] + settings --> factory{"broker_from_url()
looks at the scheme"} + factory -- "memory://" --> mem["InMemoryBroker"] + factory -- "redis://" --> red["RedisBroker"] --> r[("Redis")] + factory -- "amqp://" --> rab["RabbitMQBroker"] --> q[("RabbitMQ")] + factory -- "tcp://" --> tcp["TcpBroker"] --> t[("apps/tcp-broker")] + factory -- "anything registered" --> custom["your backend"] + mem & red & rab & tcp & custom --> iface[["Broker interface"]] + iface --> svc["OrderService / worker loop
(unchanged)"] +``` + +| Backend | URL | Delivery | Survives broker restart | Needs | +| --- | --- | --- | --- | --- | +| In-memory | `memory://` | one process only | no | nothing (tests) | +| Redis | `redis://host:6379/0` | each message to one consumer | if Redis persistence is on | `redis` extra + a Redis server | +| 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 | + +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. + +### Adding another broker (Kafka, NATS, SQS, ...) + +1. Add `packages/messaging/src/messaging/backends/.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. +4. Add a service with a `profiles: []` entry to `compose.yaml` and a + `brokers/.env`, and add it to the `compose` matrix in CI. + +No service code changes. ### Inside a service @@ -160,7 +253,9 @@ flowchart LR end port1 -- production --> http["HttpCatalog (httpx)"] port1 -. tests .-> fake["FakeCatalog"] - port2 -- production --> rb["RedisBroker"] + port2 -- "BROKER_URL=redis://" --> rb["RedisBroker"] + port2 -- "BROKER_URL=amqp://" --> qb["RabbitMQBroker"] + port2 -- "BROKER_URL=tcp://" --> tb["TcpBroker"] port2 -. tests .-> mb["InMemoryBroker"] ``` @@ -178,15 +273,21 @@ flowchart TD changes --> t2["test orders-api"] changes --> t3["test notifier-worker"] 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)"} + 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 two -dependents, while catalog-api, cli and the other libraries are skipped. To see what CI would +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 +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 test for your branch, run `python3 scripts/ci/affected.py --base origin/main`. ## Container build @@ -202,8 +303,8 @@ flowchart LR end subgraph builder["Stage 1: builder (uv image)"] - s1["uv sync --no-install-workspace --package APP
third-party deps only
(cached until uv.lock changes)"] - s2["uv sync --no-editable --package APP
APP + only the libraries it needs"] + s1["uv sync --no-install-workspace --package APP --extra ...
third-party deps only
(cached until uv.lock changes)"] + s2["uv sync --no-editable --package APP --extra ...
APP + only the libraries it needs"] s1 --> s2 end @@ -211,6 +312,7 @@ flowchart LR venv["/app/.venv
non-root user
ENTRYPOINT = APP"] end + arg["build arg BROKER_EXTRAS
default: redis rabbitmq"] -.-> s1 & s2 lock --> s1 src --> s2 s2 -->|"copy .venv only"| venv @@ -221,14 +323,21 @@ What actually lands in each image: | Image | Workspace libraries | Notable third-party | | --- | --- | --- | | `catalog-api` | contracts, servicekit | fastapi, uvicorn | -| `orders-api` | contracts, messaging, servicekit | fastapi, uvicorn, httpx, redis | -| `notifier-worker` | contracts, messaging, servicekit | redis (no web server) | +| `orders-api` | contracts, messaging, servicekit | fastapi, uvicorn, httpx, + broker clients from `BROKER_EXTRAS` | +| `notifier-worker` | contracts, messaging, servicekit | broker clients from `BROKER_EXTRAS` (no web server) | +| `tcp-broker` | messaging, servicekit | none | | `cli` | core | none | ```bash -docker build -f apps/orders-api/Dockerfile -t orders-api . +docker build -f apps/orders-api/Dockerfile -t orders-api . # redis + pika inside +docker build --build-arg BROKER_EXTRAS=rabbitmq \ + -f apps/orders-api/Dockerfile -t orders-api:rabbitmq . # pika only ``` +By default `BROKER_EXTRAS="redis rabbitmq"`, so one image can be pointed at any broker by +changing `BROKER_URL` at deploy time. Narrow it if you want the smallest image for the +broker you actually run; `tcp://` and `memory://` need no extra at all. + ## Deployment Each image is deployed and scaled on its own. The same topology runs locally with @@ -253,7 +362,7 @@ flowchart LR w1["pod"] w2["pod"] end - redis[("Redis
orders.placed queue")] + broker[("Message broker
Redis, RabbitMQ or tcp-broker
orders.placed queue")] end email(["Email / SMS provider"]) @@ -261,8 +370,8 @@ flowchart LR lb -->|"/products"| cat lb -->|"/orders"| ord ord -->|"HTTP GET /products/{sku}
CATALOG_URL"| cat - ord -->|"publish
BROKER_URL"| redis - redis -->|"consume"| wrk + ord -->|"publish
BROKER_URL"| broker + broker -->|"consume
BROKER_URL"| wrk wrk --> email ``` @@ -278,7 +387,37 @@ Configuration is by environment variable only (`servicekit.ServiceSettings`): | `LOG_LEVEL` | all | `INFO` | | `ENVIRONMENT` | all (shown in `/health`) | `local` | | `CATALOG_URL` | orders-api | `http://localhost:8001` | -| `BROKER_URL` | orders-api, notifier-worker | `memory://` (orders-api), `redis://localhost:6379/0` (worker) | +| `BROKER_URL` | orders-api, notifier-worker | `memory://` (orders-api), `redis://localhost:6379/0` (worker). The scheme picks the backend: `redis://`, `amqp://`, `tcp://`, `memory://` | +| `PORT` | tcp-broker | `7000` | + +### Choosing the broker with Docker Compose + +Each broker is a Compose **profile**, and a small env file per broker sets two variables: +`COMPOSE_PROFILES` (which broker container to start) and `BROKER_URL` (where the services +connect). The app images and services stay the same. + +```mermaid +flowchart LR + subgraph files["env file you pick"] + d[".env (default)
= redis"] + fr["brokers/rabbitmq.env"] + ft["brokers/tcp.env"] + end + files --> compose["docker compose up --build"] + compose -->|"COMPOSE_PROFILES"| start["starts one of:
redis · rabbitmq · tcp-broker"] + compose -->|"BROKER_URL"| apps["orders-api + notifier-worker
(same images)"] + apps -->|"depends_on, required: false
waits for the one that is running"| start +``` + +```bash +docker compose up --build # Redis (default, from .env) +docker compose --env-file brokers/rabbitmq.env up --build # RabbitMQ (UI on :15672, guest/guest) +docker compose --env-file brokers/tcp.env up --build # the stdlib TCP broker +docker compose --profile "*" down # stop, whichever is running +``` + +In Kubernetes or any other platform the same rule applies: run the broker you want, and set +`BROKER_URL` on `orders-api` and `notifier-worker` to point at it. The example services keep their data in memory to stay dependency-free; a real service would put a database behind the same repository class. @@ -305,5 +444,8 @@ To do it by hand: root `pyproject.toml`. 4. If it exchanges data with other services, put the models in `packages/contracts`. 5. Run `uv sync --all-packages`, commit the updated `uv.lock`, and add it to `compose.yaml`. + If it uses the broker, give it `environment: *broker-env` and `depends_on: *broker-depends` + 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. diff --git a/README.md b/README.md index 78f3fa0..ae239c0 100644 --- a/README.md +++ b/README.md @@ -16,16 +16,18 @@ runtime flow, CI and deployment. . ├── pyproject.toml # workspace root (virtual, not published) + ruff/mypy/pytest config ├── uv.lock # single lockfile for the whole workspace -├── compose.yaml # run all services together locally +├── compose.yaml # run all services together locally (one profile per broker) +├── .env, brokers/*.env # which broker compose starts and BROKER_URL points at ├── packages/ # reusable libraries │ ├── contracts/ # shared pydantic models: API payloads + events -│ ├── messaging/ # Broker interface (Redis / in-memory) + typed events +│ ├── messaging/ # Broker interface + Redis / RabbitMQ / TCP / in-memory backends │ ├── servicekit/ # settings, logging, FastAPI app factory with /health │ └── core/ # tiny greeting helper used by apps/cli └── apps/ # deployables, each with its own Dockerfile ├── catalog-api/ # HTTP: product catalog ├── orders-api/ # HTTP: places orders, calls catalog-api, publishes events ├── notifier-worker/ # worker: consumes order events, sends notifications + ├── tcp-broker/ # optional dependency-free broker server for tcp:// URLs └── cli/ # command-line example ``` @@ -49,6 +51,18 @@ curl -X POST localhost:8002/orders -H 'content-type: application/json' \ docker compose logs notifier-worker # -> "notify to=ada@example.com ..." ``` +The services don't care which message broker carries their events; `BROKER_URL` decides. +Redis is the default. To run the same stack on another broker, pick its env file: + +```bash +docker compose --env-file brokers/rabbitmq.env up --build # RabbitMQ +docker compose --env-file brokers/tcp.env up --build # built-in TCP broker +docker compose --profile "*" down # stop, whichever is running +``` + +See [ARCHITECTURE.md](ARCHITECTURE.md#messaging-a-pluggable-transport) for how the transport +is plugged in and how to add another one. + ## Everyday commands ```bash @@ -109,6 +123,9 @@ rebuild the apps that depend on it. To add a service, copy the closest example a from the workspace `pyproject.toml` files, so there is nothing extra to maintain when you add a member. A change to a shared file outside any member (root `pyproject.toml`, `uv.lock`, the workflow itself, ...) runs every member; Markdown and `docs/` changes run none. +- **Brokers / end-to-end**: when `packages/messaging` or a service using it changes, the + messaging tests also run against real Redis and RabbitMQ, and the compose stack is started + once per broker (`scripts/ci/compose_smoke.sh`) to send a real order through it. - **CI OK**: a single summary job to mark as required in branch protection; it passes when test jobs are skipped because nothing relevant changed. diff --git a/apps/notifier-worker/Dockerfile b/apps/notifier-worker/Dockerfile index b8e6d2c..17d1771 100644 --- a/apps/notifier-worker/Dockerfile +++ b/apps/notifier-worker/Dockerfile @@ -2,12 +2,20 @@ # Build from the repo root so the workspace lockfile and sibling packages are in context: # docker build -f apps/notifier-worker/Dockerfile -t notifier-worker . # Only this app and the workspace packages it depends on are installed. +# +# BROKER_EXTRAS chooses which broker client libraries go into the image. The default +# bakes in all of them, so one image can talk to any broker and BROKER_URL alone picks +# which (redis://, amqp://, tcp://). For a slimmer image, keep only the one you deploy: +# docker build --build-arg BROKER_EXTRAS=rabbitmq -f apps/notifier-worker/Dockerfile -t notifier-worker . +# memory:// and tcp:// need no extra, so BROKER_EXTRAS="" is valid too. ARG PYTHON_VERSION=3.13 ARG APP=notifier-worker +ARG BROKER_EXTRAS="redis rabbitmq" FROM ghcr.io/astral-sh/uv:python${PYTHON_VERSION}-bookworm-slim AS builder ARG APP +ARG BROKER_EXTRAS ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy UV_PYTHON_DOWNLOADS=0 WORKDIR /app @@ -17,12 +25,12 @@ RUN --mount=type=cache,target=/root/.cache/uv \ --mount=type=bind,source=pyproject.toml,target=pyproject.toml \ --mount=type=bind,source=packages,target=packages \ --mount=type=bind,source=apps,target=apps \ - uv sync --frozen --no-dev --no-install-workspace --package ${APP} + uv sync --frozen --no-dev --no-install-workspace --package ${APP} $(for e in ${BROKER_EXTRAS}; do printf -- "--extra %s " "$e"; done) # 2) This app + its workspace deps, installed as real (non-editable) wheels. COPY . . RUN --mount=type=cache,target=/root/.cache/uv \ - uv sync --frozen --no-dev --no-editable --package ${APP} + uv sync --frozen --no-dev --no-editable --package ${APP} $(for e in ${BROKER_EXTRAS}; do printf -- "--extra %s " "$e"; done) FROM python:${PYTHON_VERSION}-slim-bookworm AS runtime ARG APP diff --git a/apps/notifier-worker/pyproject.toml b/apps/notifier-worker/pyproject.toml index f43c276..57ac3fd 100644 --- a/apps/notifier-worker/pyproject.toml +++ b/apps/notifier-worker/pyproject.toml @@ -6,6 +6,13 @@ requires-python = ">=3.13" # Plain `servicekit` (no `http` extra): this worker has no web server. dependencies = ["contracts", "messaging", "servicekit"] +# 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. +# memory:// and tcp:// need no extra. +[project.optional-dependencies] +redis = ["messaging[redis]"] +rabbitmq = ["messaging[rabbitmq]"] + [project.scripts] notifier-worker = "notifier_worker.main:main" diff --git a/apps/notifier-worker/src/notifier_worker/main.py b/apps/notifier-worker/src/notifier_worker/main.py index 2f33a61..1e9b97b 100644 --- a/apps/notifier-worker/src/notifier_worker/main.py +++ b/apps/notifier-worker/src/notifier_worker/main.py @@ -11,6 +11,7 @@ class Settings(ServiceSettings): service_name: str = "notifier-worker" + # The scheme picks the transport: redis://, amqp://, tcp:// or memory://. broker_url: str = "redis://localhost:6379/0" @@ -24,7 +25,8 @@ def handle_signal(signum: int, frame: FrameType | None) -> None: signal.signal(signal.SIGTERM, handle_signal) signal.signal(signal.SIGINT, handle_signal) - run(broker_from_url(settings.broker_url), LogNotifier(), stop) + with broker_from_url(settings.broker_url) as broker: + run(broker, LogNotifier(), stop) if __name__ == "__main__": diff --git a/apps/notifier-worker/src/notifier_worker/worker.py b/apps/notifier-worker/src/notifier_worker/worker.py index fe993f9..55d38f2 100644 --- a/apps/notifier-worker/src/notifier_worker/worker.py +++ b/apps/notifier-worker/src/notifier_worker/worker.py @@ -40,12 +40,16 @@ def process_one(broker: Broker, notifier: Notifier, timeout: float = 1.0) -> boo return True -def run(broker: Broker, notifier: Notifier, stop: threading.Event) -> None: +def run( + broker: Broker, notifier: Notifier, stop: threading.Event, error_backoff: float = 1.0 +) -> None: """Process events until ``stop`` is set (e.g. on SIGTERM).""" - log.info("listening on %s", ORDER_PLACED_TOPIC) + log.info("listening on %s via %s", ORDER_PLACED_TOPIC, type(broker).__name__) while not stop.is_set(): try: process_one(broker, notifier) except Exception: # keep the worker alive; a real one would dead-letter the event log.exception("failed to process event") + # Don't spin while the broker is unreachable (restarting, not up yet, ...). + stop.wait(error_backoff) log.info("stopped") diff --git a/apps/notifier-worker/tests/test_worker.py b/apps/notifier-worker/tests/test_worker.py index 2e15277..7fff35b 100644 --- a/apps/notifier-worker/tests/test_worker.py +++ b/apps/notifier-worker/tests/test_worker.py @@ -53,5 +53,5 @@ def send(self, to: str, subject: str, body: str) -> None: if len(notifier.sent) == 2: stop.set() - run(broker, StopWhenDrained(), stop) + run(broker, StopWhenDrained(), stop, error_backoff=0) assert [s[1] for s in notifier.sent] == ["Order first confirmed", "Order second confirmed"] diff --git a/apps/orders-api/Dockerfile b/apps/orders-api/Dockerfile index bd3532f..72bf61d 100644 --- a/apps/orders-api/Dockerfile +++ b/apps/orders-api/Dockerfile @@ -2,12 +2,20 @@ # Build from the repo root so the workspace lockfile and sibling packages are in context: # docker build -f apps/orders-api/Dockerfile -t orders-api . # Only this app and the workspace packages it depends on are installed. +# +# BROKER_EXTRAS chooses which broker client libraries go into the image. The default +# bakes in all of them, so one image can talk to any broker and BROKER_URL alone picks +# which (redis://, amqp://, tcp://). For a slimmer image, keep only the one you deploy: +# docker build --build-arg BROKER_EXTRAS=rabbitmq -f apps/orders-api/Dockerfile -t orders-api . +# memory:// and tcp:// need no extra, so BROKER_EXTRAS="" is valid too. ARG PYTHON_VERSION=3.13 ARG APP=orders-api +ARG BROKER_EXTRAS="redis rabbitmq" FROM ghcr.io/astral-sh/uv:python${PYTHON_VERSION}-bookworm-slim AS builder ARG APP +ARG BROKER_EXTRAS ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy UV_PYTHON_DOWNLOADS=0 WORKDIR /app @@ -17,12 +25,12 @@ RUN --mount=type=cache,target=/root/.cache/uv \ --mount=type=bind,source=pyproject.toml,target=pyproject.toml \ --mount=type=bind,source=packages,target=packages \ --mount=type=bind,source=apps,target=apps \ - uv sync --frozen --no-dev --no-install-workspace --package ${APP} + uv sync --frozen --no-dev --no-install-workspace --package ${APP} $(for e in ${BROKER_EXTRAS}; do printf -- "--extra %s " "$e"; done) # 2) This app + its workspace deps, installed as real (non-editable) wheels. COPY . . RUN --mount=type=cache,target=/root/.cache/uv \ - uv sync --frozen --no-dev --no-editable --package ${APP} + uv sync --frozen --no-dev --no-editable --package ${APP} $(for e in ${BROKER_EXTRAS}; do printf -- "--extra %s " "$e"; done) FROM python:${PYTHON_VERSION}-slim-bookworm AS runtime ARG APP diff --git a/apps/orders-api/pyproject.toml b/apps/orders-api/pyproject.toml index 56f2061..dff50b6 100644 --- a/apps/orders-api/pyproject.toml +++ b/apps/orders-api/pyproject.toml @@ -5,6 +5,13 @@ description = "HTTP service that accepts orders, prices them via catalog-api and requires-python = ">=3.13" dependencies = ["contracts", "messaging", "servicekit[http]", "httpx>=0.28"] +# 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. +# memory:// and tcp:// need no extra. +[project.optional-dependencies] +redis = ["messaging[redis]"] +rabbitmq = ["messaging[rabbitmq]"] + [project.scripts] orders-api = "orders_api.main:main" diff --git a/apps/orders-api/src/orders_api/app.py b/apps/orders-api/src/orders_api/app.py index 40285b4..cddb8dd 100644 --- a/apps/orders-api/src/orders_api/app.py +++ b/apps/orders-api/src/orders_api/app.py @@ -13,6 +13,7 @@ class Settings(ServiceSettings): service_name: str = "orders-api" catalog_url: str = "http://localhost:8001" + # The scheme picks the transport: redis://, amqp://, tcp:// or memory:// (tests). broker_url: str = "memory://" diff --git a/apps/tcp-broker/Dockerfile b/apps/tcp-broker/Dockerfile new file mode 100644 index 0000000..b660d9d --- /dev/null +++ b/apps/tcp-broker/Dockerfile @@ -0,0 +1,35 @@ +# syntax=docker/dockerfile:1.7 +# Build from the repo root so the workspace lockfile and sibling packages are in context: +# docker build -f apps/tcp-broker/Dockerfile -t tcp-broker . +# Only this app and the workspace packages it depends on are installed. + +ARG PYTHON_VERSION=3.13 +ARG APP=tcp-broker + +FROM ghcr.io/astral-sh/uv:python${PYTHON_VERSION}-bookworm-slim AS builder +ARG APP +ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy UV_PYTHON_DOWNLOADS=0 +WORKDIR /app + +# 1) Third-party deps only (cached layer, rebuilt only when the lock changes). +RUN --mount=type=cache,target=/root/.cache/uv \ + --mount=type=bind,source=uv.lock,target=uv.lock \ + --mount=type=bind,source=pyproject.toml,target=pyproject.toml \ + --mount=type=bind,source=packages,target=packages \ + --mount=type=bind,source=apps,target=apps \ + uv sync --frozen --no-dev --no-install-workspace --package ${APP} + +# 2) This app + its workspace deps, installed as real (non-editable) wheels. +COPY . . +RUN --mount=type=cache,target=/root/.cache/uv \ + uv sync --frozen --no-dev --no-editable --package ${APP} + +FROM python:${PYTHON_VERSION}-slim-bookworm AS runtime +ARG APP +RUN useradd --create-home --uid 1000 app +COPY --from=builder --chown=app:app /app/.venv /app/.venv +ENV PATH="/app/.venv/bin:$PATH" PYTHONUNBUFFERED=1 +USER app +EXPOSE 7000 +HEALTHCHECK --interval=5s --timeout=3s --retries=3 CMD ["tcp-broker", "--check"] +ENTRYPOINT ["tcp-broker"] diff --git a/apps/tcp-broker/pyproject.toml b/apps/tcp-broker/pyproject.toml new file mode 100644 index 0000000..77d6eb3 --- /dev/null +++ b/apps/tcp-broker/pyproject.toml @@ -0,0 +1,20 @@ +[project] +name = "tcp-broker" +version = "0.1.0" +description = "Standalone message broker spoken over plain TCP (the server for tcp:// broker URLs)." +requires-python = ">=3.13" +dependencies = ["messaging", "servicekit"] + +[project.scripts] +tcp-broker = "tcp_broker.main:main" + +[tool.uv.sources] +messaging = { workspace = true } +servicekit = { workspace = true } + +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[tool.hatch.build.targets.wheel] +packages = ["src/tcp_broker"] diff --git a/apps/tcp-broker/src/tcp_broker/__init__.py b/apps/tcp-broker/src/tcp_broker/__init__.py new file mode 100644 index 0000000..49e87fa --- /dev/null +++ b/apps/tcp-broker/src/tcp_broker/__init__.py @@ -0,0 +1 @@ +"""TCP broker: the server that ``tcp://`` broker URLs connect to.""" diff --git a/apps/tcp-broker/src/tcp_broker/main.py b/apps/tcp-broker/src/tcp_broker/main.py new file mode 100644 index 0000000..0df9039 --- /dev/null +++ b/apps/tcp-broker/src/tcp_broker/main.py @@ -0,0 +1,56 @@ +"""Process entry point: ``tcp-broker`` (``tcp-broker --check`` for health checks).""" + +import argparse +import logging +import signal +import sys +import threading +from types import FrameType + +from messaging.backends.tcp import DEFAULT_PORT, TcpBroker, TcpBrokerServer +from servicekit import ServiceSettings, configure_logging + +log = logging.getLogger(__name__) + + +class Settings(ServiceSettings): + service_name: str = "tcp-broker" + port: int = DEFAULT_PORT + + +def check(port: int) -> int: + """Exit 0 if a broker answers on localhost:``port`` (used by the Docker HEALTHCHECK).""" + try: + with TcpBroker("127.0.0.1", port, connect_timeout=2.0) as broker: + broker.ping() + except Exception as exc: + print(f"unhealthy: {exc}", file=sys.stderr) + return 1 + return 0 + + +def main(argv: list[str] | None = None) -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true", help="ping a running broker and exit") + args = parser.parse_args(argv) + settings = Settings() + if args.check: + raise SystemExit(check(settings.port)) + + configure_logging(settings.service_name, settings.log_level) + server = TcpBrokerServer(settings.host, settings.port) + + def handle_signal(signum: int, frame: FrameType | None) -> None: + # shutdown() blocks until serve_forever() returns, so call it off the main thread. + threading.Thread(target=server.shutdown, daemon=True).start() + + signal.signal(signal.SIGTERM, handle_signal) + signal.signal(signal.SIGINT, handle_signal) + log.info("listening on %s:%d", settings.host, server.port) + with server: + server.serve_forever() + log.info("stopped") + + +if __name__ == "__main__": + main() diff --git a/apps/tcp-broker/src/tcp_broker/py.typed b/apps/tcp-broker/src/tcp_broker/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/apps/tcp-broker/tests/test_tcp_broker.py b/apps/tcp-broker/tests/test_tcp_broker.py new file mode 100644 index 0000000..69ae140 --- /dev/null +++ b/apps/tcp-broker/tests/test_tcp_broker.py @@ -0,0 +1,39 @@ +import threading +from collections.abc import Iterator + +import pytest + +from messaging import broker_from_url +from messaging.backends.tcp import TcpBrokerServer +from tcp_broker.main import check + + +@pytest.fixture +def server() -> Iterator[TcpBrokerServer]: + srv = TcpBrokerServer("127.0.0.1", 0) + thread = threading.Thread(target=srv.serve_forever, args=(0.05,), daemon=True) + thread.start() + yield srv + srv.shutdown() + srv.server_close() + + +def test_check_reports_a_running_broker(server: TcpBrokerServer) -> None: + assert check(server.port) == 0 + + +def test_check_fails_when_nothing_listens() -> None: + srv = TcpBrokerServer("127.0.0.1", 0) + port = srv.port + srv.server_close() + assert check(port) == 1 + + +def test_services_talk_through_the_server(server: TcpBrokerServer) -> None: + with ( + broker_from_url(f"tcp://127.0.0.1:{server.port}") as producer, + broker_from_url(f"tcp://127.0.0.1:{server.port}") as consumer, + ): + producer.publish("orders.placed", "hello") + assert server.pending("orders.placed") == 1 + assert consumer.receive("orders.placed", timeout=1) == "hello" diff --git a/brokers/rabbitmq.env b/brokers/rabbitmq.env new file mode 100644 index 0000000..02b2ade --- /dev/null +++ b/brokers/rabbitmq.env @@ -0,0 +1,3 @@ +# docker compose --env-file brokers/rabbitmq.env up --build +COMPOSE_PROFILES=rabbitmq +BROKER_URL=amqp://guest:guest@rabbitmq:5672/ diff --git a/brokers/redis.env b/brokers/redis.env new file mode 100644 index 0000000..e5cfa4e --- /dev/null +++ b/brokers/redis.env @@ -0,0 +1,3 @@ +# docker compose --env-file brokers/redis.env up --build +COMPOSE_PROFILES=redis +BROKER_URL=redis://redis:6379/0 diff --git a/brokers/tcp.env b/brokers/tcp.env new file mode 100644 index 0000000..b1cc3b3 --- /dev/null +++ b/brokers/tcp.env @@ -0,0 +1,3 @@ +# docker compose --env-file brokers/tcp.env up --build +COMPOSE_PROFILES=tcp +BROKER_URL=tcp://tcp-broker:7000 diff --git a/compose.yaml b/compose.yaml index 59704cf..3c61870 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,5 +1,12 @@ -# Run every service locally, wired together like production: -# docker compose up --build +# Run every service locally, wired together like production. +# +# Pick the message broker with an env file (each one sets COMPOSE_PROFILES, which +# starts that broker's container, and BROKER_URL, which points the services at it): +# docker compose up --build # Redis (from .env) +# docker compose --env-file brokers/rabbitmq.env up --build +# docker compose --env-file brokers/tcp.env up --build +# The app images are the same in every case; only BROKER_URL changes. +# # Then try: # curl localhost:8001/products # curl -X POST localhost:8002/orders -H 'content-type: application/json' \ @@ -7,31 +14,67 @@ # docker compose logs -f notifier-worker # Scale the worker independently: # docker compose up -d --scale notifier-worker=3 +# Stop everything, whichever broker is running: +# docker compose --profile "*" down + +# Shared by every service that publishes or consumes events. +x-broker-env: &broker-env + BROKER_URL: ${BROKER_URL:-redis://redis:6379/0} + +# Wait for whichever broker is running. `required: false` skips the ones whose +# profile is not enabled, so only the selected broker has to be up. +x-broker-depends: &broker-depends + redis: { condition: service_healthy, required: false } + rabbitmq: { condition: service_healthy, required: false } + tcp-broker: { condition: service_healthy, required: false } services: + # ------------------------------------------------------------ brokers (pick one) redis: + profiles: [redis] image: redis:7-alpine healthcheck: test: ["CMD", "redis-cli", "ping"] interval: 5s + rabbitmq: + profiles: [rabbitmq] + image: rabbitmq:4-management-alpine + ports: ["15672:15672"] # management UI: http://localhost:15672 (guest / guest) + healthcheck: + test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"] + interval: 5s + timeout: 10s + retries: 12 + + tcp-broker: + profiles: [tcp] + build: { context: ., dockerfile: apps/tcp-broker/Dockerfile } + + # ------------------------------------------------------------ services catalog-api: build: { context: ., dockerfile: apps/catalog-api/Dockerfile } ports: ["8001:8000"] orders-api: - build: { context: ., dockerfile: apps/orders-api/Dockerfile } + build: + context: . + dockerfile: apps/orders-api/Dockerfile + args: { BROKER_EXTRAS: "${BROKER_EXTRAS:-redis rabbitmq}" } ports: ["8002:8000"] environment: + <<: *broker-env CATALOG_URL: http://catalog-api:8000 - BROKER_URL: redis://redis:6379/0 depends_on: + <<: *broker-depends catalog-api: { condition: service_healthy } - redis: { condition: service_healthy } notifier-worker: - build: { context: ., dockerfile: apps/notifier-worker/Dockerfile } + build: + context: . + dockerfile: apps/notifier-worker/Dockerfile + args: { BROKER_EXTRAS: "${BROKER_EXTRAS:-redis rabbitmq}" } environment: - BROKER_URL: redis://redis:6379/0 + <<: *broker-env depends_on: - redis: { condition: service_healthy } + <<: *broker-depends diff --git a/packages/messaging/pyproject.toml b/packages/messaging/pyproject.toml index 37bfa6a..ccca912 100644 --- a/packages/messaging/pyproject.toml +++ b/packages/messaging/pyproject.toml @@ -1,9 +1,16 @@ [project] name = "messaging" version = "0.1.0" -description = "Tiny message-broker abstraction (in-memory for tests, Redis in production)." +description = "Transport-neutral message-broker interface with Redis, RabbitMQ, TCP and in-memory backends." requires-python = ">=3.13" -dependencies = ["pydantic>=2.9", "redis>=5.2"] +# The core (interface, in-memory and TCP backends) needs nothing beyond pydantic. +# Client libraries for external brokers are opt-in extras, so an image only carries +# the ones it can actually use. +dependencies = ["pydantic>=2.9"] + +[project.optional-dependencies] +redis = ["redis>=5.2"] +rabbitmq = ["pika>=1.3"] [build-system] requires = ["hatchling"] diff --git a/packages/messaging/src/messaging/__init__.py b/packages/messaging/src/messaging/__init__.py index 661eb79..4e12b89 100644 --- a/packages/messaging/src/messaging/__init__.py +++ b/packages/messaging/src/messaging/__init__.py @@ -1,13 +1,32 @@ -"""Publish and consume typed events through a pluggable broker.""" +"""Publish and consume typed events through a pluggable broker. -from messaging.broker import Broker, InMemoryBroker, RedisBroker, broker_from_url +Application code depends only on :class:`Broker` and the typed helpers. The +transport is picked at start-up from a URL (``BROKER_URL``):: + + broker = broker_from_url("amqp://guest:guest@rabbitmq:5672/") + +See :mod:`messaging.broker` for the supported schemes and how to add one. +""" + +from messaging.backends.memory import InMemoryBroker +from messaging.broker import ( + Broker, + BrokerError, + BrokerFactory, + available_schemes, + broker_from_url, + register_backend, +) from messaging.events import publish_event, receive_event __all__ = [ "Broker", + "BrokerError", + "BrokerFactory", "InMemoryBroker", - "RedisBroker", + "available_schemes", "broker_from_url", "publish_event", "receive_event", + "register_backend", ] diff --git a/packages/messaging/src/messaging/backends/__init__.py b/packages/messaging/src/messaging/backends/__init__.py new file mode 100644 index 0000000..e6378a0 --- /dev/null +++ b/packages/messaging/src/messaging/backends/__init__.py @@ -0,0 +1,6 @@ +"""Concrete transports. Import them through :func:`messaging.broker_from_url`. + +Each module defines one :class:`~messaging.Broker` subclass with a ``from_url`` +classmethod. Modules that need a third-party client import it at module level, +so they are only imported when that backend is selected. +""" diff --git a/packages/messaging/src/messaging/backends/memory.py b/packages/messaging/src/messaging/backends/memory.py new file mode 100644 index 0000000..9021d8d --- /dev/null +++ b/packages/messaging/src/messaging/backends/memory.py @@ -0,0 +1,38 @@ +"""Process-local broker for tests and single-process experiments.""" + +from __future__ import annotations + +import threading +from collections import deque +from typing import Self + +from messaging.broker import Broker + + +class InMemoryBroker(Broker): + """Queues live in this process, so it cannot connect two containers. + + ``receive`` never blocks: it returns ``None`` straight away when the topic is + empty, which keeps tests that poll an empty queue fast. + """ + + def __init__(self) -> None: + self._queues: dict[str, deque[str]] = {} + self._lock = threading.Lock() + + @classmethod + def from_url(cls, url: str) -> Self: + return cls() + + def publish(self, topic: str, message: str) -> None: + with self._lock: + self._queues.setdefault(topic, deque()).append(message) + + def receive(self, topic: str, timeout: float = 1.0) -> str | None: + with self._lock: + queue = self._queues.get(topic) + return queue.popleft() if queue else None + + def pending(self, topic: str) -> int: + with self._lock: + return len(self._queues.get(topic, ())) diff --git a/packages/messaging/src/messaging/backends/rabbitmq.py b/packages/messaging/src/messaging/backends/rabbitmq.py new file mode 100644 index 0000000..646a299 --- /dev/null +++ b/packages/messaging/src/messaging/backends/rabbitmq.py @@ -0,0 +1,114 @@ +"""RabbitMQ backend: one durable queue per topic on the default exchange. + +Publishing uses persistent messages, so they survive a broker restart. Receiving +takes one message with ``basic_get`` and acknowledges it at once, which matches +the Redis backend's at-most-once BRPOP semantics. + +``pika.BlockingConnection`` is not thread-safe, and FastAPI runs sync routes on a +thread pool, so every call holds a lock. If the connection has dropped (broker +restart, missed heartbeats while idle) the call reconnects and retries once. +""" + +from __future__ import annotations + +import contextlib +import threading +import time +from collections.abc import Callable +from typing import Self + +import pika +from pika.adapters.blocking_connection import BlockingChannel +from pika.exceptions import AMQPChannelError, AMQPConnectionError + +from messaging.broker import Broker + +POLL_INTERVAL = 0.05 # seconds between basic_get attempts while waiting for a message + +ConnectionFactory = Callable[[pika.connection.Parameters], pika.BlockingConnection] + + +class RabbitMQBroker(Broker): + def __init__( + self, + parameters: pika.connection.Parameters, + connection_factory: ConnectionFactory = pika.BlockingConnection, + ) -> None: + self._parameters = parameters + self._connect = connection_factory + self._connection: pika.BlockingConnection | None = None + self._channel: BlockingChannel | None = None + self._declared: set[str] = set() + self._lock = threading.Lock() + + @classmethod + def from_url(cls, url: str) -> Self: + return cls(pika.URLParameters(url)) + + # ------------------------------------------------------------------ Broker + + def publish(self, topic: str, message: str) -> None: + properties = pika.BasicProperties( + content_type="application/json", + delivery_mode=pika.DeliveryMode.Persistent, + ) + + def op(channel: BlockingChannel) -> None: + self._declare(channel, topic) + channel.basic_publish( + exchange="", routing_key=topic, body=message.encode(), properties=properties + ) + + self._run(op) + + def receive(self, topic: str, timeout: float = 1.0) -> str | None: + def op(channel: BlockingChannel) -> str | None: + self._declare(channel, topic) + deadline = time.monotonic() + timeout + while True: + _method, _properties, body = channel.basic_get(queue=topic, auto_ack=True) + if body is not None: + return bytes(body).decode() + remaining = deadline - time.monotonic() + if remaining <= 0: + return None + # Sleeps while still servicing heartbeats on this connection. + assert self._connection is not None + self._connection.process_data_events(time_limit=min(POLL_INTERVAL, remaining)) + + return self._run(op) + + def close(self) -> None: + with self._lock: + self._reset() + + # ---------------------------------------------------------------- helpers + + def _run[T](self, op: Callable[[BlockingChannel], T]) -> T: + with self._lock: + try: + return op(self._ensure_channel()) + except (AMQPConnectionError, AMQPChannelError): + self._reset() + return op(self._ensure_channel()) + + def _ensure_channel(self) -> BlockingChannel: + if self._connection is None or self._connection.is_closed: + self._connection = self._connect(self._parameters) + self._channel = None + if self._channel is None or self._channel.is_closed: + self._channel = self._connection.channel() + self._declared.clear() + return self._channel + + def _declare(self, channel: BlockingChannel, topic: str) -> None: + if topic not in self._declared: + channel.queue_declare(queue=topic, durable=True) + self._declared.add(topic) + + def _reset(self) -> None: + connection, self._connection, self._channel = self._connection, None, None + self._declared.clear() + if connection is not None and connection.is_open: + with contextlib.suppress(Exception): # already broken; nothing useful to do + connection.close() diff --git a/packages/messaging/src/messaging/backends/redis_broker.py b/packages/messaging/src/messaging/backends/redis_broker.py new file mode 100644 index 0000000..2de8061 --- /dev/null +++ b/packages/messaging/src/messaging/backends/redis_broker.py @@ -0,0 +1,31 @@ +"""Redis backend: a Redis list per topic, LPUSH to publish and BRPOP to receive.""" + +from __future__ import annotations + +from typing import Self + +import redis + +from messaging.broker import Broker + + +class RedisBroker(Broker): + def __init__(self, client: redis.Redis) -> None: + self._client = client + + @classmethod + def from_url(cls, url: str) -> Self: + return cls(redis.Redis.from_url(url, decode_responses=True)) + + def publish(self, topic: str, message: str) -> None: + self._client.lpush(topic, message) + + def receive(self, topic: str, timeout: float = 1.0) -> str | None: + item = self._client.brpop([topic], timeout=timeout) + if item is None: + return None + value = item[1] + return value.decode() if isinstance(value, bytes) else value + + def close(self) -> None: + self._client.close() diff --git a/packages/messaging/src/messaging/backends/tcp.py b/packages/messaging/src/messaging/backends/tcp.py new file mode 100644 index 0000000..6be5e0c --- /dev/null +++ b/packages/messaging/src/messaging/backends/tcp.py @@ -0,0 +1,236 @@ +"""A tiny broker spoken over plain TCP, using only the standard library. + +It needs no third-party server or client library, which makes it handy for local +development, CI and small deployments. Run the server with ``apps/tcp-broker`` +and point services at ``tcp://:``. Queues are kept in the server's +memory, so messages are lost if the server restarts; use Redis or RabbitMQ when +that matters. + +Wire protocol: one JSON object per line in each direction. + + -> {"op": "publish", "topic": "t", "message": "..."} <- {"ok": true} + -> {"op": "receive", "topic": "t", "timeout": 1.0} <- {"ok": true, "message": "..." | null} + -> {"op": "ping"} <- {"ok": true} + any error <- {"ok": false, "error": "..."} +""" + +from __future__ import annotations + +import contextlib +import json +import logging +import socket +import socketserver +import threading +import time +from collections import deque +from typing import Any, Self +from urllib.parse import urlsplit + +from messaging.broker import Broker, BrokerError + +log = logging.getLogger(__name__) + +DEFAULT_PORT = 7000 +MAX_LINE = 16 * 1024 * 1024 # refuse absurdly large frames instead of buffering forever +NETWORK_GRACE = 5.0 # extra seconds a client waits beyond the receive timeout + + +# --------------------------------------------------------------------- client + + +class TcpBroker(Broker): + """Client for :class:`TcpBrokerServer`. Thread-safe; reconnects once on a dropped link.""" + + def __init__(self, host: str, port: int = DEFAULT_PORT, connect_timeout: float = 5.0) -> None: + self._address = (host, port) + self._connect_timeout = connect_timeout + self._sock: socket.socket | None = None + self._file: Any = None + self._lock = threading.Lock() + + @classmethod + def from_url(cls, url: str) -> Self: + parts = urlsplit(url) + if not parts.hostname: + raise BrokerError(f"tcp broker URL needs a host, e.g. tcp://localhost:7000: {url!r}") + return cls(parts.hostname, parts.port or DEFAULT_PORT) + + def publish(self, topic: str, message: str) -> None: + self._call({"op": "publish", "topic": topic, "message": message}, wait=0.0) + + def receive(self, topic: str, timeout: float = 1.0) -> str | None: + reply = self._call({"op": "receive", "topic": topic, "timeout": timeout}, wait=timeout) + message = reply.get("message") + return message if isinstance(message, str) else None + + def ping(self) -> None: + self._call({"op": "ping"}, wait=0.0) + + def close(self) -> None: + with self._lock: + self._disconnect() + + def _call(self, request: dict[str, Any], wait: float) -> dict[str, Any]: + frame = (json.dumps(request) + "\n").encode() + with self._lock: + # A request that is not a receive is safe to resend; a receive is too, + # because the server re-queues a message it could not deliver. + for attempt in (1, 2): + try: + sock, file = self._connection() + sock.settimeout(wait + NETWORK_GRACE) + sock.sendall(frame) + line = file.readline(MAX_LINE) + if not line: + raise ConnectionError("tcp broker closed the connection") + break + except OSError: + self._disconnect() + if attempt == 2: + raise + reply: dict[str, Any] = json.loads(line) + if not reply.get("ok"): + raise BrokerError(f"tcp broker error: {reply.get('error')}") + return reply + + def _connection(self) -> tuple[socket.socket, Any]: + if self._sock is None: + self._sock = socket.create_connection(self._address, timeout=self._connect_timeout) + self._file = self._sock.makefile("rb") + return self._sock, self._file + + def _disconnect(self) -> None: + sock, self._sock, self._file = self._sock, None, None + if sock is not None: + sock.close() + + +# --------------------------------------------------------------------- server + + +class _Topic: + def __init__(self) -> None: + self.items: deque[str] = deque() + self.ready = threading.Condition() + + def put(self, message: str, front: bool = False) -> None: + with self.ready: + if front: + self.items.appendleft(message) + else: + self.items.append(message) + self.ready.notify() + + def get(self, timeout: float) -> str | None: + deadline = time.monotonic() + timeout + with self.ready: + while not self.items: + remaining = deadline - time.monotonic() + if remaining <= 0: + return None + self.ready.wait(remaining) + return self.items.popleft() + + +class _Handler(socketserver.StreamRequestHandler): + server: TcpBrokerServer + + def setup(self) -> None: + super().setup() + self.server.track(self.connection, add=True) + + def finish(self) -> None: + self.server.track(self.connection, add=False) + super().finish() + + def handle(self) -> None: + while True: + try: + line = self.rfile.readline(MAX_LINE) + except OSError: + return + if not line: + return + reply, undelivered = self.server.dispatch(line) + try: + self.wfile.write((json.dumps(reply) + "\n").encode()) + self.wfile.flush() + except OSError: + # The client went away while we were answering: give the message back. + if undelivered is not None: + self.server.requeue(*undelivered) + return + + +class TcpBrokerServer(socketserver.ThreadingTCPServer): + """Holds one FIFO queue per topic and serves :class:`TcpBroker` clients.""" + + daemon_threads = True + allow_reuse_address = True + max_receive_timeout = 30.0 + + def __init__(self, host: str = "0.0.0.0", port: int = DEFAULT_PORT) -> None: + super().__init__((host, port), _Handler) + self._topics: dict[str, _Topic] = {} + self._topics_lock = threading.Lock() + self._clients: set[socket.socket] = set() + + @property + def port(self) -> int: + return int(self.server_address[1]) + + def pending(self, topic: str) -> int: + return len(self._topic(topic).items) + + def track(self, sock: socket.socket, add: bool) -> None: + with self._topics_lock: + if add: + self._clients.add(sock) + else: + self._clients.discard(sock) + + def server_close(self) -> None: + """Stop listening and drop every client, as a process exit would.""" + super().server_close() + with self._topics_lock: + clients, self._clients = self._clients, set() + for sock in clients: + with contextlib.suppress(OSError): + sock.shutdown(socket.SHUT_RDWR) + + def requeue(self, topic: str, message: str) -> None: + self._topic(topic).put(message, front=True) + + def dispatch(self, line: bytes) -> tuple[dict[str, Any], tuple[str, str] | None]: + """Run one request. Returns the reply and, for a receive, what was taken.""" + try: + request = json.loads(line) + op = request.get("op") + if op == "ping": + return {"ok": True}, None + topic = request["topic"] + if not isinstance(topic, str) or not topic: + raise ValueError("topic must be a non-empty string") + if op == "publish": + message = request["message"] + if not isinstance(message, str): + raise ValueError("message must be a string") + self._topic(topic).put(message) + return {"ok": True}, None + if op == "receive": + timeout = float(request.get("timeout", 1.0)) + timeout = min(max(timeout, 0.0), self.max_receive_timeout) + message = self._topic(topic).get(timeout) + taken = None if message is None else (topic, message) + return {"ok": True, "message": message}, taken + raise ValueError(f"unknown op {op!r}") + except (ValueError, KeyError, TypeError, AttributeError) as exc: + return {"ok": False, "error": str(exc) or type(exc).__name__}, None + + def _topic(self, name: str) -> _Topic: + with self._topics_lock: + topic = self._topics.get(name) + if topic is None: + topic = self._topics[name] = _Topic() + return topic diff --git a/packages/messaging/src/messaging/broker.py b/packages/messaging/src/messaging/broker.py index 8fc121c..3bae6c7 100644 --- a/packages/messaging/src/messaging/broker.py +++ b/packages/messaging/src/messaging/broker.py @@ -1,66 +1,110 @@ -"""Broker implementations. +"""The transport-neutral broker interface and the URL-based backend registry. + +Services only ever see :class:`Broker`. Which technology moves the bytes (Redis, +RabbitMQ, a plain TCP broker, process memory, ...) is chosen at start-up from a +URL, normally the ``BROKER_URL`` environment variable:: + + memory:// in-process, for tests + redis://redis:6379/0 Redis list (needs messaging[redis]) + amqp://guest:guest@rabbitmq:5672/ RabbitMQ queue (needs messaging[rabbitmq]) + tcp://tcp-broker:7000 the stdlib-only TCP broker (apps/tcp-broker) A broker moves opaque string messages through named topics. Each message is delivered to exactly one consumer (work-queue semantics), so running more worker replicas spreads the load instead of duplicating work. """ -from collections import deque -from typing import Protocol +from __future__ import annotations + +import importlib +from abc import ABC, abstractmethod +from collections.abc import Callable +from types import TracebackType +from typing import Self +from urllib.parse import urlsplit -import redis +class BrokerError(Exception): + """Raised for configuration problems, such as an unknown or uninstalled backend.""" -class Broker(Protocol): - def publish(self, topic: str, message: str) -> None: ... +class Broker(ABC): + """What every transport must provide. Application code depends on this alone.""" + + @abstractmethod + def publish(self, topic: str, message: str) -> None: + """Enqueue ``message`` on ``topic``.""" + + @abstractmethod def receive(self, topic: str, timeout: float = 1.0) -> str | None: """Return the next message on ``topic``, or ``None`` after ``timeout`` seconds.""" - ... + def close(self) -> None: # noqa: B027 - optional hook, most backends need nothing + """Release network resources. Safe to call more than once.""" -class InMemoryBroker: - """Process-local broker for tests and local experiments.""" + def __enter__(self) -> Self: + return self - def __init__(self) -> None: - self._queues: dict[str, deque[str]] = {} + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + self.close() - def publish(self, topic: str, message: str) -> None: - self._queues.setdefault(topic, deque()).append(message) - def receive(self, topic: str, timeout: float = 1.0) -> str | None: - queue = self._queues.get(topic) - return queue.popleft() if queue else None +BrokerFactory = Callable[[str], Broker] - def pending(self, topic: str) -> int: - return len(self._queues.get(topic, ())) +# scheme -> "module:Class" (imported lazily so a missing optional client library only +# matters when that backend is actually selected), or a factory registered at runtime. +_BACKENDS: dict[str, str | BrokerFactory] = { + "memory": "messaging.backends.memory:InMemoryBroker", + "redis": "messaging.backends.redis_broker:RedisBroker", + "rediss": "messaging.backends.redis_broker:RedisBroker", + "amqp": "messaging.backends.rabbitmq:RabbitMQBroker", + "amqps": "messaging.backends.rabbitmq:RabbitMQBroker", + "tcp": "messaging.backends.tcp:TcpBroker", +} +# Which optional extra provides the client library for a backend module. +_EXTRAS = {"redis_broker": "redis", "rabbitmq": "rabbitmq"} -class RedisBroker: - """Redis list used as a FIFO queue: LPUSH to publish, BRPOP to receive.""" - def __init__(self, client: redis.Redis) -> None: - self._client = client +def register_backend(scheme: str, factory: BrokerFactory) -> None: + """Plug in another transport (Kafka, NATS, SQS, ...) without touching this package. - @classmethod - def from_url(cls, url: str) -> "RedisBroker": - return cls(redis.Redis.from_url(url, decode_responses=True)) + ``factory`` receives the full URL and returns a :class:`Broker`. + """ + _BACKENDS[scheme.lower()] = factory - def publish(self, topic: str, message: str) -> None: - self._client.lpush(topic, message) - def receive(self, topic: str, timeout: float = 1.0) -> str | None: - item = self._client.brpop([topic], timeout=timeout) - if item is None: - return None - value = item[1] - return value.decode() if isinstance(value, bytes) else value +def available_schemes() -> list[str]: + return sorted(_BACKENDS) + + +def _load(target: str) -> BrokerFactory: + module_name, _, attr = target.partition(":") + try: + module = importlib.import_module(module_name) + except ImportError as exc: + extra = _EXTRAS.get(module_name.rsplit(".", 1)[-1], "") + raise BrokerError( + f"the client library for this broker is not installed ({exc.name}); " + f"install the `messaging[{extra}]` extra (or the app's `{extra}` extra)" + ) from exc + cls = getattr(module, attr) + factory: BrokerFactory = cls.from_url + return factory def broker_from_url(url: str) -> Broker: - """Build a broker from a URL such as ``memory://`` or ``redis://host:6379/0``.""" - if url.startswith("memory://"): - return InMemoryBroker() - if url.startswith(("redis://", "rediss://")): - return RedisBroker.from_url(url) - raise ValueError(f"unsupported broker URL: {url!r}") + """Build the broker a URL names, e.g. ``broker_from_url(settings.broker_url)``.""" + scheme = urlsplit(url).scheme.lower() + target = _BACKENDS.get(scheme) + if target is None: + raise BrokerError( + f"unsupported broker URL {url!r}; known schemes: {', '.join(available_schemes())}" + ) + factory = _load(target) if isinstance(target, str) else target + return factory(url) diff --git a/packages/messaging/tests/conftest.py b/packages/messaging/tests/conftest.py new file mode 100644 index 0000000..2c79fb4 --- /dev/null +++ b/packages/messaging/tests/conftest.py @@ -0,0 +1,76 @@ +"""Fixtures that hand every contract test each available transport. + +memory, Redis (via fakeredis) and TCP (a real server on a random port) always run. +Real Redis and RabbitMQ servers join in when their URL is set, as CI's integration +job does: + + MESSAGING_TEST_REDIS_URL=redis://localhost:6379/0 + MESSAGING_TEST_AMQP_URL=amqp://guest:guest@localhost:5672/ +""" + +import os +import threading +import uuid +from collections.abc import Iterator + +import fakeredis +import pytest + +from messaging import Broker, InMemoryBroker, broker_from_url +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") + + +@pytest.fixture +def tcp_server() -> Iterator[TcpBrokerServer]: + server = TcpBrokerServer("127.0.0.1", 0) + thread = threading.Thread(target=server.serve_forever, args=(0.05,), daemon=True) + thread.start() + yield server + server.shutdown() + server.server_close() + + +@pytest.fixture( + params=[ + "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"), + ), + ] +) +def any_broker(request: pytest.FixtureRequest) -> Iterator[Broker]: + """A connected broker of each kind. Use :func:`topic` for an isolated topic name.""" + kind: str = request.param + broker: Broker + if kind == "memory": + broker = InMemoryBroker() + elif kind == "fakeredis": + broker = RedisBroker(fakeredis.FakeRedis(decode_responses=True)) + 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) + with broker: + yield broker + + +@pytest.fixture +def topic() -> str: + """A fresh topic per test, so runs against a shared real broker don't interfere.""" + return f"test.{uuid.uuid4().hex}" diff --git a/packages/messaging/tests/test_messaging.py b/packages/messaging/tests/test_messaging.py index 7224b22..a5e53aa 100644 --- a/packages/messaging/tests/test_messaging.py +++ b/packages/messaging/tests/test_messaging.py @@ -1,53 +1,84 @@ -import fakeredis +"""Behaviour every transport must share. Each test runs once per backend.""" + +import threading + import pytest from pydantic import BaseModel -from messaging import ( - InMemoryBroker, - RedisBroker, - broker_from_url, - publish_event, - receive_event, -) +from messaging import Broker, InMemoryBroker, publish_event, receive_event class Ping(BaseModel): n: int -def test_in_memory_broker_is_fifo() -> None: - broker = InMemoryBroker() - broker.publish("t", "a") - broker.publish("t", "b") - assert broker.receive("t") == "a" - assert broker.receive("t") == "b" - assert broker.receive("t") is None +def drain(broker: Broker, topic: str, count: int) -> list[str]: + out: list[str] = [] + for _ in range(count): + message = broker.receive(topic, timeout=2) + assert message is not None + out.append(message) + return out -def test_topics_are_independent() -> None: - broker = InMemoryBroker() - broker.publish("one", "x") - assert broker.receive("two") is None - assert broker.pending("one") == 1 +def test_fifo(any_broker: Broker, topic: str) -> None: + for message in ("a", "b", "c"): + any_broker.publish(topic, message) + assert drain(any_broker, topic, 3) == ["a", "b", "c"] + assert any_broker.receive(topic, timeout=0.1) is None + + +def test_empty_topic_times_out(any_broker: Broker, topic: str) -> None: + assert any_broker.receive(topic, timeout=0.1) is None + + +def test_topics_are_independent(any_broker: Broker, topic: str) -> None: + any_broker.publish(topic, "x") + assert any_broker.receive(f"{topic}.other", timeout=0.1) is None + assert any_broker.receive(topic, timeout=1) == "x" -def test_redis_broker_is_fifo() -> None: - broker = RedisBroker(fakeredis.FakeRedis(decode_responses=True)) - broker.publish("t", "a") - broker.publish("t", "b") - assert broker.receive("t", timeout=0.1) == "a" - assert broker.receive("t", timeout=0.1) == "b" +def test_non_ascii_and_large_messages(any_broker: Broker, topic: str) -> None: + big = "é✓" * 100_000 + any_broker.publish(topic, big) + assert any_broker.receive(topic, timeout=2) == big -def test_typed_events_round_trip() -> None: +def test_typed_events_round_trip(any_broker: Broker, topic: str) -> None: + publish_event(any_broker, topic, Ping(n=7)) + assert receive_event(any_broker, topic, Ping, timeout=2) == Ping(n=7) + assert receive_event(any_broker, topic, Ping, timeout=0.1) is None + + +def test_concurrent_publishers(any_broker: Broker, topic: str) -> None: + """FastAPI calls publish from several threads at once.""" + + def publish_many(prefix: str) -> None: + for i in range(20): + any_broker.publish(topic, f"{prefix}{i}") + + threads = [threading.Thread(target=publish_many, args=(p,)) for p in "abcd"] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + expected = sorted(f"{p}{i}" for p in "abcd" for i in range(20)) + assert sorted(drain(any_broker, topic, 80)) == expected + + +def test_close_is_idempotent(any_broker: Broker) -> None: + any_broker.close() + any_broker.close() + + +def test_in_memory_pending() -> None: broker = InMemoryBroker() - publish_event(broker, "pings", Ping(n=7)) - assert receive_event(broker, "pings", Ping) == Ping(n=7) - assert receive_event(broker, "pings", Ping) is None + broker.publish("one", "x") + assert broker.pending("one") == 1 + assert broker.pending("two") == 0 -def test_broker_from_url() -> None: - assert isinstance(broker_from_url("memory://"), InMemoryBroker) - assert isinstance(broker_from_url("redis://localhost:6379/0"), RedisBroker) - with pytest.raises(ValueError, match="unsupported"): - broker_from_url("kafka://nope") +@pytest.mark.parametrize("payload", ["", "line\nbreak"]) +def test_awkward_payloads(any_broker: Broker, topic: str, payload: str) -> None: + any_broker.publish(topic, payload) + assert any_broker.receive(topic, timeout=2) == payload diff --git a/packages/messaging/tests/test_rabbitmq.py b/packages/messaging/tests/test_rabbitmq.py new file mode 100644 index 0000000..87a2d31 --- /dev/null +++ b/packages/messaging/tests/test_rabbitmq.py @@ -0,0 +1,32 @@ +"""RabbitMQ-specific behaviour. Needs a real server (CI's integration job provides one).""" + +import os + +import pytest + +from messaging import broker_from_url +from messaging.backends.rabbitmq import RabbitMQBroker + +AMQP_URL = os.environ.get("MESSAGING_TEST_AMQP_URL") + +pytestmark = pytest.mark.skipif(not AMQP_URL, reason="MESSAGING_TEST_AMQP_URL not set") + + +def test_reconnects_after_the_connection_drops(topic: str) -> None: + assert AMQP_URL + with broker_from_url(AMQP_URL) as broker: + assert isinstance(broker, RabbitMQBroker) + broker.publish(topic, "one") + assert broker._connection is not None + broker._connection.close() # as if the broker restarted or heartbeats lapsed + broker.publish(topic, "two") + assert broker.receive(topic, timeout=2) == "one" + assert broker.receive(topic, timeout=2) == "two" + + +def test_messages_wait_in_a_durable_queue_for_a_later_consumer(topic: str) -> None: + assert AMQP_URL + with broker_from_url(AMQP_URL) as producer: + producer.publish(topic, "queued") + with broker_from_url(AMQP_URL) as consumer: + assert consumer.receive(topic, timeout=2) == "queued" diff --git a/packages/messaging/tests/test_registry.py b/packages/messaging/tests/test_registry.py new file mode 100644 index 0000000..2169033 --- /dev/null +++ b/packages/messaging/tests/test_registry.py @@ -0,0 +1,71 @@ +import pytest + +from messaging import ( + Broker, + BrokerError, + InMemoryBroker, + available_schemes, + broker_from_url, + register_backend, +) +from messaging.backends.rabbitmq import RabbitMQBroker +from messaging.backends.redis_broker import RedisBroker +from messaging.backends.tcp import TcpBroker +from messaging.broker import _BACKENDS + + +@pytest.mark.parametrize( + ("url", "kind"), + [ + ("memory://", InMemoryBroker), + ("redis://localhost:6379/0", RedisBroker), + ("rediss://localhost:6380/0", RedisBroker), + ("amqp://guest:guest@localhost:5672/", RabbitMQBroker), + ("AMQP://localhost", RabbitMQBroker), + ("tcp://localhost:7000", TcpBroker), + ("tcp://localhost", TcpBroker), + ], +) +def test_url_scheme_selects_backend(url: str, kind: type[Broker]) -> None: + # Building a broker never connects; the first publish/receive does. + with broker_from_url(url) as broker: + assert isinstance(broker, kind) + + +def test_unknown_scheme_lists_the_known_ones() -> None: + with pytest.raises(BrokerError, match=r"unsupported.*amqp.*tcp"): + broker_from_url("kafka://nope") + + +def test_tcp_url_needs_a_host() -> None: + with pytest.raises(BrokerError, match="needs a host"): + broker_from_url("tcp://") + + +def test_register_custom_backend(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setitem(_BACKENDS, "custom", _BACKENDS["memory"]) + created: list[str] = [] + + def factory(url: str) -> Broker: + created.append(url) + return InMemoryBroker() + + register_backend("Custom", factory) + assert "custom" in available_schemes() + assert isinstance(broker_from_url("custom://x"), InMemoryBroker) + assert created == ["custom://x"] + + +def test_missing_client_library_names_the_extra(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setitem(_BACKENDS, "ghost", "messaging.backends.not_installed:Nope") + with pytest.raises(BrokerError, match="not installed"): + broker_from_url("ghost://x") + + +def test_missing_rabbitmq_extra_hint(monkeypatch: pytest.MonkeyPatch) -> None: + import sys + + monkeypatch.delitem(sys.modules, "messaging.backends.rabbitmq", raising=False) + monkeypatch.setitem(sys.modules, "pika", None) # makes `import pika` fail + with pytest.raises(BrokerError, match=r"messaging\[rabbitmq\]"): + broker_from_url("amqp://localhost") diff --git a/packages/messaging/tests/test_tcp.py b/packages/messaging/tests/test_tcp.py new file mode 100644 index 0000000..ccd67b6 --- /dev/null +++ b/packages/messaging/tests/test_tcp.py @@ -0,0 +1,128 @@ +"""TCP-specific behaviour: the wire protocol, reconnects and not losing messages.""" + +import json +import socket +import threading + +import pytest + +from messaging import BrokerError +from messaging.backends.tcp import TcpBroker, TcpBrokerServer + + +def raw(server: TcpBrokerServer, *requests: object) -> list[dict[str, object]]: + with socket.create_connection(("127.0.0.1", server.port), timeout=5) as sock: + file = sock.makefile("rwb") + replies = [] + for request in requests: + line = request if isinstance(request, bytes) else json.dumps(request).encode() + file.write(line + b"\n") + file.flush() + replies.append(json.loads(file.readline())) + return replies + + +def test_protocol(tcp_server: TcpBrokerServer) -> None: + assert raw( + tcp_server, + {"op": "ping"}, + {"op": "publish", "topic": "t", "message": "m"}, + {"op": "receive", "topic": "t", "timeout": 0}, + {"op": "receive", "topic": "t", "timeout": 0}, + ) == [{"ok": True}, {"ok": True}, {"ok": True, "message": "m"}, {"ok": True, "message": None}] + + +@pytest.mark.parametrize( + "bad", + [ + b"not json", + {"op": "explode", "topic": "t"}, + {"op": "publish", "topic": "t"}, + {"op": "publish", "topic": "", "message": "m"}, + {"op": "publish", "topic": "t", "message": 1}, + [], + ], +) +def test_bad_requests_get_an_error_and_keep_the_connection( + tcp_server: TcpBrokerServer, bad: object +) -> None: + error, pong = raw(tcp_server, bad, {"op": "ping"}) + assert error["ok"] is False + assert pong == {"ok": True} + + +def test_server_errors_surface_as_broker_error(tcp_server: TcpBrokerServer) -> None: + with TcpBroker("127.0.0.1", tcp_server.port) as broker, pytest.raises(BrokerError): + broker._call({"op": "explode"}, wait=0) + + +def test_receive_blocks_until_a_message_arrives(tcp_server: TcpBrokerServer) -> None: + with ( + TcpBroker("127.0.0.1", tcp_server.port) as consumer, + TcpBroker("127.0.0.1", tcp_server.port) as producer, + ): + timer = threading.Timer(0.2, producer.publish, args=("t", "late")) + timer.start() + assert consumer.receive("t", timeout=5) == "late" + timer.join() + + +def test_each_message_goes_to_one_consumer(tcp_server: TcpBrokerServer) -> None: + port = tcp_server.port + with TcpBroker("127.0.0.1", port) as producer: + for i in range(50): + producer.publish("work", str(i)) + seen: list[str] = [] + lock = threading.Lock() + + def consume() -> None: + with TcpBroker("127.0.0.1", port) as consumer: + while (message := consumer.receive("work", timeout=0.2)) is not None: + with lock: + seen.append(message) + + workers = [threading.Thread(target=consume) for _ in range(4)] + for worker in workers: + worker.start() + for worker in workers: + worker.join() + assert sorted(seen, key=int) == [str(i) for i in range(50)] + + +def test_client_reconnects_after_the_server_restarts() -> None: + first = TcpBrokerServer("127.0.0.1", 0) + port = first.port + threading.Thread(target=first.serve_forever, args=(0.05,), daemon=True).start() + broker = TcpBroker("127.0.0.1", port) + broker.publish("t", "before") + first.shutdown() + first.server_close() + second = TcpBrokerServer("127.0.0.1", port) + threading.Thread(target=second.serve_forever, args=(0.05,), daemon=True).start() + try: + broker.publish("t", "after") + assert broker.receive("t", timeout=1) == "after" + finally: + broker.close() + second.shutdown() + second.server_close() + + +def test_message_is_requeued_if_the_consumer_vanishes(tcp_server: TcpBrokerServer) -> None: + topic, message = "t", "precious" + tcp_server.requeue(topic, message) + reply, taken = tcp_server.dispatch(json.dumps({"op": "receive", "topic": topic}).encode()) + assert reply == {"ok": True, "message": message} + assert taken == (topic, message) + # The handler gives `taken` back when writing the reply fails: + tcp_server.requeue(*taken) + assert tcp_server.pending(topic) == 1 + + +def test_connection_refused_raises() -> None: + server = TcpBrokerServer("127.0.0.1", 0) + port = server.port + server.server_close() + broker = TcpBroker("127.0.0.1", port, connect_timeout=1) + with pytest.raises(ConnectionRefusedError): + broker.publish("t", "m") diff --git a/pyproject.toml b/pyproject.toml index 9d7a2bb..08b9a22 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,6 +9,9 @@ dependencies = [] [dependency-groups] dev = [ "fakeredis>=2.26", + # Every broker client, so the whole workspace (and every backend) is testable locally. + "pika>=1.3", + "redis>=5.2", "mypy>=1.13", "pre-commit>=4.0", "pytest>=8.3", @@ -41,6 +44,7 @@ known-first-party = [ "catalog_api", "orders_api", "notifier_worker", + "tcp_broker", ] # ---------------------------------------------------------------- mypy @@ -58,10 +62,15 @@ mypy_path = [ "apps/catalog-api/src", "apps/orders-api/src", "apps/notifier-worker/src", + "apps/tcp-broker/src", ] explicit_package_bases = true files = ["packages", "apps", "scripts"] +[[tool.mypy.overrides]] +module = ["pika", "pika.*"] # pika ships no type hints +ignore_missing_imports = true + # ---------------------------------------------------------------- pytest [tool.pytest.ini_options] addopts = ["-ra", "--strict-markers", "--strict-config", "--import-mode=importlib"] diff --git a/scripts/ci/compose_smoke.sh b/scripts/ci/compose_smoke.sh new file mode 100755 index 0000000..1763cea --- /dev/null +++ b/scripts/ci/compose_smoke.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# End-to-end check of the compose stack with one broker: +# scripts/ci/compose_smoke.sh redis|rabbitmq|tcp +# Starts the stack with brokers/.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}" +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") + +cleanup() { + status=$? + if [ "$status" -ne 0 ]; then + "${compose[@]}" ps -a || true + "${compose[@]}" logs --no-color --tail 100 || true + fi + "${compose[@]}" down --volumes --remove-orphans >/dev/null 2>&1 || true + exit "$status" +} +trap cleanup EXIT + +"${compose[@]}" up --build --detach --wait + +email="smoke-${broker}-$RANDOM@example.com" +curl --fail --silent --show-error --retry 10 --retry-connrefused --retry-delay 1 \ + -X POST localhost:8002/orders -H 'content-type: application/json' \ + -d "{\"customer_email\":\"$email\",\"items\":[{\"sku\":\"MUG-001\",\"quantity\":2}]}" +echo + +for _ in $(seq 1 30); do + if "${compose[@]}" logs notifier-worker 2>&1 | grep -q "notify to=$email"; then + echo "OK: notifier-worker received the order over $broker" + exit 0 + fi + sleep 1 +done +echo "FAIL: notifier-worker never logged a notification for $email" >&2 +exit 1 diff --git a/uv.lock b/uv.lock index e538ec8..c70e768 100644 --- a/uv.lock +++ b/uv.lock @@ -17,6 +17,7 @@ members = [ "orders-api", "python-monorepo", "servicekit", + "tcp-broker", ] [[package]] @@ -492,14 +493,23 @@ version = "0.1.0" source = { editable = "packages/messaging" } dependencies = [ { name = "pydantic" }, +] + +[package.optional-dependencies] +rabbitmq = [ + { name = "pika" }, +] +redis = [ { name = "redis" }, ] [package.metadata] requires-dist = [ + { name = "pika", marker = "extra == 'rabbitmq'", specifier = ">=1.3" }, { name = "pydantic", specifier = ">=2.9" }, - { name = "redis", specifier = ">=5.2" }, + { name = "redis", marker = "extra == 'redis'", specifier = ">=5.2" }, ] +provides-extras = ["redis", "rabbitmq"] [[package]] name = "mypy" @@ -577,12 +587,23 @@ dependencies = [ { name = "servicekit" }, ] +[package.optional-dependencies] +rabbitmq = [ + { name = "messaging", extra = ["rabbitmq"] }, +] +redis = [ + { name = "messaging", extra = ["redis"] }, +] + [package.metadata] requires-dist = [ { name = "contracts", editable = "packages/contracts" }, { name = "messaging", editable = "packages/messaging" }, + { name = "messaging", extras = ["rabbitmq"], marker = "extra == 'rabbitmq'", editable = "packages/messaging" }, + { name = "messaging", extras = ["redis"], marker = "extra == 'redis'", editable = "packages/messaging" }, { name = "servicekit", editable = "packages/servicekit" }, ] +provides-extras = ["redis", "rabbitmq"] [[package]] name = "opentelemetry-api" @@ -607,13 +628,24 @@ dependencies = [ { name = "servicekit", extra = ["http"] }, ] +[package.optional-dependencies] +rabbitmq = [ + { name = "messaging", extra = ["rabbitmq"] }, +] +redis = [ + { name = "messaging", extra = ["redis"] }, +] + [package.metadata] requires-dist = [ { name = "contracts", editable = "packages/contracts" }, { name = "httpx", specifier = ">=0.28" }, { name = "messaging", editable = "packages/messaging" }, + { name = "messaging", extras = ["rabbitmq"], marker = "extra == 'rabbitmq'", editable = "packages/messaging" }, + { name = "messaging", extras = ["redis"], marker = "extra == 'redis'", editable = "packages/messaging" }, { name = "servicekit", extras = ["http"], editable = "packages/servicekit" }, ] +provides-extras = ["redis", "rabbitmq"] [[package]] name = "packaging" @@ -633,6 +665,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f1/d9/7fb5aa316bc299258e68c73ba3bddbc499654a07f151cba08f6153988714/pathspec-1.1.1-py3-none-any.whl", hash = "sha256:a00ce642f577bf7f473932318056212bc4f8bfdf53128c78bbd5af0b9b20b189", size = 57328, upload-time = "2026-04-27T01:46:07.06Z" }, ] +[[package]] +name = "pika" +version = "1.4.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7f/26/54e0b98a7f60b474cb0a6c05ecf048d4bc8c866e10ab1c82bc83865e7421/pika-1.4.4.tar.gz", hash = "sha256:8cfc8b33a5cb16e733bd60cffca9732c0d1d761ecd80a89f34ed7df2cd38d6d6", size = 154713, upload-time = "2026-08-06T21:33:39.836Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7c/f3/921170b78779ac3f8b405cb28fce88acca1562ac114072cbf0a115e19bb9/pika-1.4.4-py3-none-any.whl", hash = "sha256:48de960c97a93b55db06b8be4c53eb977c9c8a2754c57cdae9097abcbd70ce04", size = 165275, upload-time = "2026-08-06T21:33:38.449Z" }, +] + [[package]] name = "platformdirs" version = "4.14.5" @@ -853,9 +894,11 @@ source = { virtual = "." } dev = [ { name = "fakeredis" }, { name = "mypy" }, + { name = "pika" }, { name = "pre-commit" }, { name = "pytest" }, { name = "pytest-cov" }, + { name = "redis" }, { name = "ruff" }, ] @@ -865,9 +908,11 @@ dev = [ dev = [ { name = "fakeredis", specifier = ">=2.26" }, { name = "mypy", specifier = ">=1.13" }, + { name = "pika", specifier = ">=1.3" }, { name = "pre-commit", specifier = ">=4.0" }, { name = "pytest", specifier = ">=8.3" }, { name = "pytest-cov", specifier = ">=6.0" }, + { name = "redis", specifier = ">=5.2" }, { name = "ruff", specifier = ">=0.8" }, ] @@ -984,6 +1029,21 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/88/2e/947cfe02def9371c07cd5bf5b6b61c829e9aecb9904db02a66cfafbc1eec/starlette-1.10.0-py3-none-any.whl", hash = "sha256:478c0ab3b4ced6e82719849c118fa406f0278a3499c1a898cd15cd31bdc38ce4", size = 80571, upload-time = "2026-10-24T15:04:10.371Z" }, ] +[[package]] +name = "tcp-broker" +version = "0.1.0" +source = { editable = "apps/tcp-broker" } +dependencies = [ + { name = "messaging" }, + { name = "servicekit" }, +] + +[package.metadata] +requires-dist = [ + { name = "messaging", editable = "packages/messaging" }, + { name = "servicekit", editable = "packages/servicekit" }, +] + [[package]] name = "typing-extensions" version = "4.16.0"