From 7afe502fd19566c3c03dd98220a8843722499dca Mon Sep 17 00:00:00 2001 From: Erik Shafer Date: Sat, 5 Sep 2026 19:10:18 -0500 Subject: [PATCH 1/3] Slice 004 spec and OpenSpec trail: NotifyBaker over RabbitMQ Erik's call, 2026-09-05: the baker notification crosses a real RabbitMQ broker on BOTH twins, so the talk can show what one message costs a layered codebase against a slice. Same broker both sides; only the idiom changes. No new endpoint, no contract change. - docs/slices/004-notify-baker-over-rabbitmq.md: the slice spec (contract unchanged from 003, required before-twin structure, after-twin shape, fixture-only suite changes, out of scope). - openspec change proposed, applied, and archived in one pass; design.md records the settled decisions (queue per twin, publish after commit with no outbox, consumer in WebApi re-dispatching through MediatR, ExistsForOrderAsync idempotency, UseDurableOutbox on the publish rule, one RabbitMQ container per twin collection). - openspec/specs/orders: the exactly-one-baker-task requirement now says the notification is delivered through a RabbitMQ queue in both twins before the task is written. Scenario list unchanged. - openspec/config.yaml: four slices; dotnet test starts PostgreSQL and RabbitMQ through Testcontainers. --- docs/slices/004-notify-baker-over-rabbitmq.md | 45 ++++++++++++ .../.openspec.yaml | 2 + .../design.md | 73 +++++++++++++++++++ .../proposal.md | 40 ++++++++++ .../specs/orders/spec.md | 12 +++ .../tasks.md | 38 ++++++++++ openspec/config.yaml | 16 ++-- openspec/specs/orders/spec.md | 2 +- 8 files changed, 221 insertions(+), 7 deletions(-) create mode 100644 docs/slices/004-notify-baker-over-rabbitmq.md create mode 100644 openspec/changes/archive/2026-09-05-slice-004-notify-baker-over-rabbitmq/.openspec.yaml create mode 100644 openspec/changes/archive/2026-09-05-slice-004-notify-baker-over-rabbitmq/design.md create mode 100644 openspec/changes/archive/2026-09-05-slice-004-notify-baker-over-rabbitmq/proposal.md create mode 100644 openspec/changes/archive/2026-09-05-slice-004-notify-baker-over-rabbitmq/specs/orders/spec.md create mode 100644 openspec/changes/archive/2026-09-05-slice-004-notify-baker-over-rabbitmq/tasks.md diff --git a/docs/slices/004-notify-baker-over-rabbitmq.md b/docs/slices/004-notify-baker-over-rabbitmq.md new file mode 100644 index 0000000..f6f7587 --- /dev/null +++ b/docs/slices/004-notify-baker-over-rabbitmq.md @@ -0,0 +1,45 @@ +# Slice 004 — NotifyBaker over RabbitMQ + +**Why this slice is in the talk:** slice 003 made "tell the baker" a cascaded message in the after twin and an inline row write in the before twin. This slice puts that one side effect on a real broker in BOTH twins, so the talk can show what a message costs a layered codebase (a port, an adapter, a hosted consumer, a re-dispatch, wiring in every ring) against what it costs a slice (configuration in `Program.cs`; the feature files do not change). Same broker both sides; only the idiom changes. Decided 2026-09-05. + +## Contract (unchanged from slice 003) + +`POST /orders`, `GET /orders/{id}`, `GET /baker/tasks` are byte-for-byte the slice 003 contract. No new endpoint. The observable side effect is unchanged: placing an order produces exactly one baker task for that order, visible on `GET /baker/tasks?orderId={id}` within the suite's polling window. What changes is the path the notification takes: it now crosses a RabbitMQ queue in both twins before the task is written. + +## Before twin — REQUIRED structure + +Earnest Clean Architecture, no padding, no collapsing. Expected elements: + +- `Application/Common/Interfaces/IMessagePublisher.cs`: the port. `Task PublishAsync(TMessage message, CancellationToken cancellationToken)`. +- `Application/Orders/Messages/NotifyBakerMessage.cs`: `record NotifyBakerMessage(Guid OrderId, string Summary)`. +- `Application/Baker/Commands/CreateBakerTask/CreateBakerTaskCommand.cs` and `CreateBakerTaskCommandHandler.cs`: the consumer's re-dispatch target. The handler checks `IBakerTaskRepository.ExistsForOrderAsync` before adding (the broker delivers at least once; the suite asserts exactly one), stages the task, and commits through `IUnitOfWork`. +- `Infrastructure/Messaging/RabbitMqOptions.cs` (connection URI, queue name), `Infrastructure/Messaging/RabbitMqConnection.cs` (one `IConnection` per host, created lazily, disposed with the host), `Infrastructure/Messaging/RabbitMqMessagePublisher.cs : IMessagePublisher` (channel per publish, declares the queue durable, System.Text.Json camelCase body, persistent delivery mode, default exchange, routing key = queue name). +- `WebApi/Messaging/NotifyBakerConsumer.cs : BackgroundService`: own channel, declares the same queue with identical arguments, `AsyncEventingBasicConsumer`, manual ack. On a message: deserialize `NotifyBakerMessage`, create a DI scope, `ISender.Send(new CreateBakerTaskCommand(...))`, ack. On an exception: log and nack without requeue, with one comment saying a real system would dead-letter here. +- `PlaceOrderCommandHandler` edits: `IBakerTaskRepository` out, `IMessagePublisher` in (the constructor stays at seven dependencies; one of them is now a bus). After `SaveChangesAsync`, publish `NotifyBakerMessage`. Replace the "Imagine this line is SendGrid" comment with one that owns the gap in plain words, em-dash-free, for example: `// Published after the commit. If this line throws, the order exists and the baker never hears. No outbox, because most real ones do not have one.` +- `IBakerTaskRepository` and `BakerTaskRepository` edits: add `ExistsForOrderAsync(Guid orderId, CancellationToken)`. +- `Infrastructure/DependencyInjection.cs`: bind options from the `RabbitMq` section plus `ConnectionStrings:RabbitMq`, register the connection as a singleton and the publisher, and `Infrastructure.csproj` gains `RabbitMQ.Client`. +- `WebApi/Program.cs`: `AddHostedService()`. `appsettings.json`: `ConnectionStrings:RabbitMq` (`amqp://localhost`) and `RabbitMq:QueueName` (`layercake-before-baker-tasks`). +- No validator for `CreateBakerTaskCommand` unless the pipeline demands one (it does not; the shape was fixed by deserialization). Record the choice in the build log either way. + +## After twin — expected shape + +`Program.cs` only: + +- `opts.UseRabbitMq(...)` moves OUT of the `CritterWatch:Enabled` block and runs unconditionally, keeping `.AutoProvision()`. The CritterWatch `AddCritterWatchMonitoring` call stays inside the block. +- `opts.PublishMessage().ToRabbitQueue("layercake-after-baker-tasks").UseDurableOutbox();` so the envelope is still written in the same Marten transaction as the order (the claim on the 3.15 slide) and sent after commit. +- `opts.ListenToRabbitQueue("layercake-after-baker-tasks");` so `NotifyBakerHandler` receives it in-process. +- Revisit the `UseDurableLocalQueues()` comment (it describes `NotifyBaker` as a local message, which stops being true). Keep the line if any local message could still exist, otherwise remove it; keep the comment honest and em-dash-free. Add `ConnectionStrings:rabbitmq` to `appsettings.json` for discoverability (the code already reads that key with an `amqp://localhost` fallback). +- `PlaceOrder.cs`, `NotifyBaker.cs`, and every other file in the project: untouched. + +## Shared contract scenarios + +Unchanged: the eleven order scenarios from slice 003, including `placing_order_produces_exactly_one_baker_task`, which is now the proof that a message crossed the broker on each twin (with no broker, neither consumer runs and the scenario fails). Fixture changes only: + +- `Testcontainers.RabbitMq` added. A `RabbitMqContainerFixture` (`rabbitmq:4`, same major as docker-compose) per twin collection, added as a second `ICollectionFixture<>` on `BeforeTwinCollection` and `AfterTwinCollection`, mirroring the Postgres pattern. +- Both host fixtures pass the container's connection string via `UseSetting("ConnectionStrings:RabbitMq", ...)` (configuration keys are case-insensitive, so the after twin's lowercase read matches). +- `AfterHostFixture` REMOVES `services.DisableAllExternalWolverineTransports()`; `RunWolverineInSoloMode()` stays. Update the comment. +- Poll constants stay 250 ms / 5 s unless the real broker proves slower on a cold run; if so, raise the timeout constant only and record why. + +## Out of scope + +Outbox in the before twin. Retry, dead-lettering, or poison handling beyond log-and-nack. Any second message. Any change to routes, JSON shapes, status codes, seeds, the frontend page, the CritterWatch console, or `docs/slices/001-003`. diff --git a/openspec/changes/archive/2026-09-05-slice-004-notify-baker-over-rabbitmq/.openspec.yaml b/openspec/changes/archive/2026-09-05-slice-004-notify-baker-over-rabbitmq/.openspec.yaml new file mode 100644 index 0000000..34f54d2 --- /dev/null +++ b/openspec/changes/archive/2026-09-05-slice-004-notify-baker-over-rabbitmq/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-09-05 diff --git a/openspec/changes/archive/2026-09-05-slice-004-notify-baker-over-rabbitmq/design.md b/openspec/changes/archive/2026-09-05-slice-004-notify-baker-over-rabbitmq/design.md new file mode 100644 index 0000000..8a33a07 --- /dev/null +++ b/openspec/changes/archive/2026-09-05-slice-004-notify-baker-over-rabbitmq/design.md @@ -0,0 +1,73 @@ +# Design: slice-004-notify-baker-over-rabbitmq + +## Context + +Slice 003 is archived and green. The after twin's `PlaceOrderEndpoint.Post` returns `(PlacedOrder, NotifyBaker)`; Wolverine routes `NotifyBaker` to a durable local queue and `NotifyBakerHandler` stores the `BakerTask`. The before twin's `PlaceOrderCommandHandler` writes the `BakerTask` inline through `IBakerTaskRepository` and commits once through `IUnitOfWork`. docker-compose already runs RabbitMQ 4 for CritterWatch, and the after twin already references `WolverineFx.RabbitMQ` (gated behind `CritterWatch:Enabled`). The contract suite runs both hosts concurrently in one process, each on its own Testcontainers PostgreSQL. Behavior and structure are settled in `docs/slices/004-notify-baker-over-rabbitmq.md`; see proposal.md for motivation. This document records the decisions Erik took on 2026-09-05 with the trade-offs in view, so no later session re-litigates them, and settles the mechanics the slice spec leaves to the build. + +## Goals / Non-Goals + +**Goals:** + +- Fix the broker topology so two hosts in one test process against real brokers can never consume each other's messages. +- Fix the before twin's publish timing and consumer placement so the layered cost is honest (no padding, no shortcut) and the dual-write gap is visible on purpose. +- Fix the after twin's routing so the outbox claim stays literally true after the message leaves the process. +- Fix the test fixture pattern so `dotnet test` still needs only Docker. + +**Non-Goals:** + +- Anything re-litigating the settled contract, the before twin's required structure, or the after twin's `Program.cs`-only shape (slice spec owns those). +- Outbox, retry, dead-lettering, poison handling, second messages, second deployables (proposal non-goals). + +## Decisions + +### Same broker on both sides, one queue per twin + +RabbitMQ on both twins, the broker compose already runs. This is the Postgres move again: the engine never changes between twins, only the idiom for reaching it. Queue names `layercake-before-baker-tasks` and `layercake-after-baker-tasks`, default exchange, routing key equals queue name, durable queues. Two queues because the two hosts run concurrently in one test process against real brokers; a shared name would let one twin's consumer drain the other twin's notification and fail the exactly-one assertion on the wrong side. Alternative considered: one queue with a per-twin header filter; rejected as invisible topology that a slide cannot show. + +### Before twin: raw `RabbitMQ.Client`, no framework + +Hand-written publisher and consumer, not MassTransit, Rebus, or NServiceBus. That is exactly what the port-and-adapter split leaves a team writing when no framework is doing it, and the point of the slide is the cost of that writing. `RabbitMQ.Client` 7.x is async-first; the code uses `CreateConnectionAsync`, `CreateChannelAsync`, `BasicPublishAsync`, `BasicAckAsync`, `BasicNackAsync`, and `AsyncEventingBasicConsumer` with no sync-over-async. Alternative considered: MassTransit, which would hide the port, the adapter, and the hosted service behind one registration and make the before twin's cost look smaller than a raw-client team pays; rejected because the exhibit is the hand-written seam. + +### Before twin: publish after commit, no outbox + +`PlaceOrderCommandHandler` saves through `IUnitOfWork`, then calls `IMessagePublisher.PublishAsync`. If the publish throws, the order exists and the baker never hears. The gap is real, owned on a slide in one sentence, and carried in the code by one em-dash-free comment. No outbox, no retry loop, no dead-letter exchange: most real layered codebases do not have one, and adding one here would be padding the before twin to look worse or better than it is. Alternative considered: publish before commit; rejected because that inverts the gap (a baker task for an order that never committed) and is the less common real-world shape. + +### Before twin: consumer is a `BackgroundService` in WebApi, re-dispatching through MediatR + +A consumer is a delivery mechanism like a controller, so it belongs in the outer ring, and it stays thin the same way a controller does: deserialize, open a DI scope, `ISender.Send(new CreateBakerTaskCommand(...))`, ack. The publisher (adapter) lives in Infrastructure behind `IMessagePublisher` in Application. On an exception the consumer logs and nacks without requeue, with one comment saying a real system would dead-letter here. Alternative considered: the consumer in Infrastructure; rejected because Infrastructure has no reason to know MediatR is the dispatch mechanism, and a hosted service is host wiring. + +### Before twin: idempotency via `ExistsForOrderAsync` + +The broker delivers at least once and the suite asserts exactly one, so `CreateBakerTaskCommandHandler` checks `IBakerTaskRepository.ExistsForOrderAsync` before staging the task. The before twin keeps its conventional `Id` + `OrderId` entity (slice 003 design), so an identity upsert is not available the way it is on the after twin; a read-before-write is the earnest EF-idiom answer, and its race window is acceptable for a demo that redelivers only on consumer failure. Alternative considered: a unique index on `OrderId` plus catching the violation; rejected as a new migration and an exception-as-flow path the talk does not need. + +### Before twin: message name keeps the `Message` suffix + +`NotifyBakerMessage(Guid OrderId, string Summary)` carries the same information as the after twin's `NotifyBaker`. The `Message` suffix is the before twin's idiom and stays; CLAUDE.md's no-role-suffix rule applies to the after twin only. + +### Before twin: connection and channel lifecycle + +One `IConnection` per host, created lazily on first use, disposed with the host (singleton `RabbitMqConnection` in Infrastructure). Publisher opens a channel per publish and disposes it. The consumer owns one long-lived channel for the life of the hosted service. Both sides declare the queue with identical arguments (durable, non-exclusive, non-auto-delete, no arguments) so whichever starts first wins and the other side's declare is a no-op; RabbitMQ refuses an inequivalent redeclaration with a channel error, which is why the arguments are spelled out once in the options and used twice. A message published before the consumer subscribes waits in the queue; that is the normal case in the Alba fixture, where the first `POST` can beat the hosted service's subscription. + +### After twin: `UseDurableOutbox` on the RabbitMQ publish rule, listen in-process + +`opts.PublishMessage().ToRabbitQueue("layercake-after-baker-tasks").UseDurableOutbox()` keeps the envelope in the same Marten transaction as the order (the claim on the outbox slide) and sends after commit; `opts.ListenToRabbitQueue("layercake-after-baker-tasks")` delivers it back to `NotifyBakerHandler` in the same process. `UseRabbitMq(...).AutoProvision()` moves out of the `CritterWatch:Enabled` block and runs unconditionally; `AddCritterWatchMonitoring` stays gated. `UseDurableLocalQueues()` is revisited at build time: kept only if any local message can still exist, otherwise removed, and either way the comment stops describing `NotifyBaker` as local. Verification: `dotnet run -- describe` must report the sending endpoint in Durable mode. + +### Suite: one RabbitMQ container per twin collection + +`Testcontainers.RabbitMq` at its latest stable, image `rabbitmq:4` (same major as compose). A `RabbitMqContainerFixture` per twin collection as a second `ICollectionFixture<>`, mirroring the 2026-09-02 Postgres pattern, so `dotnet test` still needs only Docker and the two twins never share a broker either. Both host fixtures pass the container's connection string as `ConnectionStrings:RabbitMq`; configuration keys are case-insensitive, so the after twin's lowercase read matches. `AfterHostFixture` drops `DisableAllExternalWolverineTransports()` (it would swap the RabbitMQ sender for a null sender and make the proof vacuous) and keeps `RunWolverineInSoloMode()`. Alternative considered: one shared container for both collections with the two queue names keeping them apart; rejected because per-collection containers are the established pattern and the second container is cheap. + +### Package additions, never bumps + +`RabbitMQ.Client` pinned at 7.2.2, which is the exact version `WolverineFx.RabbitMQ` 6.30.0 already depends on, so the solution carries one copy. `Testcontainers.RabbitMq` pinned at 4.14.0, matching `Testcontainers.PostgreSql`. Both recorded with a dated comment in `Directory.Packages.props`; no existing pin moves. + +## Risks / Trade-offs + +- [Container startup adds seconds to the timed live `dotnet test` moment] → Record wall-clock before and after; the RabbitMQ containers start in parallel with Postgres per collection. Poll constants stay 250 ms / 5 s unless a cold run proves slower, in which case only the timeout rises and the build log says why. +- [The before twin's first `POST` can beat the consumer's subscription] → Durable queue, persistent delivery, message waits; both sides declare, so the queue exists before the first publish regardless of start order. +- [Inequivalent queue redeclaration fails the channel] → Arguments defined once in `RabbitMqOptions`, used by publisher and consumer; on the after twin Wolverine owns both sides of its queue. +- [`DisableAllExternalWolverineTransports` removed, so the after host now needs a reachable broker in every test class] → That is the point: with no broker the scenario fails, and the negative check in verification proves it can. +- [Dual-write gap in the before twin] → Owned, not mitigated. One comment in code, one sentence on a slide. + +## Open Questions + +None. The negative check (stop the broker or comment out the listener, confirm the scenario fails, revert) runs once during verification and is recorded in the build log. diff --git a/openspec/changes/archive/2026-09-05-slice-004-notify-baker-over-rabbitmq/proposal.md b/openspec/changes/archive/2026-09-05-slice-004-notify-baker-over-rabbitmq/proposal.md new file mode 100644 index 0000000..57eb8e7 --- /dev/null +++ b/openspec/changes/archive/2026-09-05-slice-004-notify-baker-over-rabbitmq/proposal.md @@ -0,0 +1,40 @@ +# Proposal: slice-004-notify-baker-over-rabbitmq + +## Why + +Slice 003 left "tell the baker" as a cascaded outbox message on the after twin and an inline row write on the before twin, and the talk asks the room to imagine that inline line is a call to an external system. This slice stops asking: the baker notification crosses a real RabbitMQ broker on BOTH twins, so the talk can show what one message costs a layered codebase against what it costs a slice. Full rationale, settled decisions, and structure: [docs/slices/004-notify-baker-over-rabbitmq.md](../../../docs/slices/004-notify-baker-over-rabbitmq.md). Decided by Erik 2026-09-05; the slate's three-slice lock stands for the talk's Act 3 features, and 004 is an extension of PlaceOrder's side effect. + +## What Changes + +- Before twin: a messaging port in Application (`IMessagePublisher`), a `NotifyBakerMessage`, a `CreateBakerTask` command + handler as the consumer's re-dispatch target, a raw `RabbitMQ.Client` publisher (adapter) plus connection and options in Infrastructure, a `BackgroundService` consumer in WebApi, and `PlaceOrderCommandHandler` swapping the inline baker-task write for a publish AFTER the commit (no outbox; the dual-write gap is owned in one comment). +- After twin: `Program.cs` only. RabbitMQ transport wired unconditionally, `NotifyBaker` published to a RabbitMQ queue with the durable outbox, the same queue listened to in-process. `PlaceOrder.cs` and `NotifyBaker.cs` untouched. +- Shared contract suite: fixture changes only. One RabbitMQ container per twin collection through `Testcontainers.RabbitMq`, connection string passed to both hosts, the after fixture stops stubbing external transports. Scenarios and assertions unchanged. +- Two package ADDITIONS at Erik's explicit call, never bumps: `RabbitMQ.Client` (before twin) and `Testcontainers.RabbitMq` (suite). Existing pins untouched. +- Bookkeeping: slice 004 section in `docs/file-inventory.md` with the whole-twin recount, dated `docs/build-log.md` entry, README / CLAUDE.md / `openspec/config.yaml` / `docker-compose.yml` wording updated so nothing still claims the suite is broker-free. + +## Capabilities + +### New Capabilities + +None. + +### Modified Capabilities + +- `orders`: the "Placing an order produces exactly one baker task" requirement now states that the notification is delivered through a RabbitMQ queue in both twins before the task is written. Scenario list unchanged; HTTP surface unchanged. + +## Impact + +- `src/before/`: all four projects touched (Application port + message + command, Infrastructure adapter + DI + csproj, WebApi hosted consumer + Program + appsettings, Domain unchanged). `PlaceOrderCommandHandler` loses `IBakerTaskRepository`, gains `IMessagePublisher`. +- `src/after/LayerCake.Slices/Program.cs` and `appsettings.json` only. +- `tests/LayerCake.ContractTests/TwinHosts.cs` and its csproj; `Directory.Packages.props` gains two entries. +- `dotnet test` now starts PostgreSQL AND RabbitMQ per twin through Testcontainers; Docker remains the only prerequisite. The live `dotnet test` moment in the talk is timed, so the before/after wall-clock is recorded. +- Docs: README, CLAUDE.md, `openspec/config.yaml`, `docker-compose.yml` comment, file inventory, build log. + +## Non-goals + +- No outbox, retry loop, or dead-letter exchange in the before twin: save through the unit of work, then publish. The gap is a slide, not a fix. +- No poison handling beyond log-and-nack in the before twin's consumer. +- No second message on either twin; no MassTransit, Rebus, or NServiceBus. +- No change to routes, JSON shapes, status codes, seeds, the frontend page, the CritterWatch console, or `docs/slices/001-003`. +- No edit to `PlaceOrder.cs` or `NotifyBaker.cs` on the after twin, even for tidiness; that would be a talk-content decision for Erik. +- No second deployable per twin; each twin's consumer runs inside its own host process (charter non-negotiable 3). diff --git a/openspec/changes/archive/2026-09-05-slice-004-notify-baker-over-rabbitmq/specs/orders/spec.md b/openspec/changes/archive/2026-09-05-slice-004-notify-baker-over-rabbitmq/specs/orders/spec.md new file mode 100644 index 0000000..3e7b40e --- /dev/null +++ b/openspec/changes/archive/2026-09-05-slice-004-notify-baker-over-rabbitmq/specs/orders/spec.md @@ -0,0 +1,12 @@ +# Delta: orders (slice-004-notify-baker-over-rabbitmq) + +## MODIFIED Requirements + +### Requirement: Placing an order produces exactly one baker task + +Placing an order SHALL produce exactly one baker task for that order, observable via `GET /baker/tasks` returning exactly `200` with a camelCase array `[ { orderId, summary, createdAt } ]`, filterable with an optional `?orderId={id}` query parameter. The notification that creates the task SHALL be delivered through a RabbitMQ queue in both twins before the task is written; the task appears asynchronously after the `201`, so observers SHALL poll with a short timeout. Once present, the count for that order SHALL be exactly one (never zero after settling, never duplicated), including when the broker redelivers the notification. With no broker reachable, no task SHALL appear on either twin. The HTTP contract does not reveal which broker, queue, or client library either twin uses. + +#### Scenario: placing_order_produces_exactly_one_baker_task + +- **WHEN** a client places an order successfully and polls `GET /baker/tasks?orderId={id}` with a short timeout +- **THEN** exactly one task for that order appears, with its `orderId` matching the placed order and a non-empty `summary` and `createdAt` diff --git a/openspec/changes/archive/2026-09-05-slice-004-notify-baker-over-rabbitmq/tasks.md b/openspec/changes/archive/2026-09-05-slice-004-notify-baker-over-rabbitmq/tasks.md new file mode 100644 index 0000000..c4760f3 --- /dev/null +++ b/openspec/changes/archive/2026-09-05-slice-004-notify-baker-over-rabbitmq/tasks.md @@ -0,0 +1,38 @@ +# Tasks: slice-004-notify-baker-over-rabbitmq + +Contract, structure, and scenarios: `docs/slices/004-notify-baker-over-rabbitmq.md`. Decisions: `design.md` (queue-per-twin topology, publish-after-commit with no outbox, consumer in WebApi re-dispatching through MediatR, `ExistsForOrderAsync` idempotency, connection and channel lifecycle, `UseDurableOutbox` on the after twin's publish rule, one RabbitMQ container per twin collection, identical queue-declare arguments). + +## 1. Package pins + +- [x] 1.1 Add `RabbitMQ.Client` 7.2.2 and `Testcontainers.RabbitMq` 4.14.0 to `Directory.Packages.props` with a dated "addition, not a bump" comment in the Testcontainers.PostgreSql style; verify `git diff` touches no existing pin and `dotnet restore` succeeds + +## 2. Before twin (earnest Clean Architecture) + +- [x] 2.1 Add `Application/Common/Interfaces/IMessagePublisher.cs` (the port) and `Application/Orders/Messages/NotifyBakerMessage.cs`; verify the Application project builds with no new package references +- [x] 2.2 Add `ExistsForOrderAsync(Guid orderId, CancellationToken)` to `IBakerTaskRepository` and `BakerTaskRepository`; verify the Infrastructure project builds +- [x] 2.3 Add `Application/Baker/Commands/CreateBakerTask/CreateBakerTaskCommand.cs` and `CreateBakerTaskCommandHandler.cs` (exists-check, stage, commit through `IUnitOfWork`); no validator (record the choice in the build log); verify by reading that the handler never saves twice and skips the add when a task exists +- [x] 2.4 Add `Infrastructure/Messaging/RabbitMqOptions.cs`, `RabbitMqConnection.cs` (lazy singleton `IConnection`, disposed with the host), and `RabbitMqMessagePublisher.cs : IMessagePublisher` (channel per publish, durable queue declare, camelCase System.Text.Json body, persistent delivery, default exchange, routing key = queue name); add `RabbitMQ.Client` to `Infrastructure.csproj`; register options, connection, and publisher in `Infrastructure/DependencyInjection.cs`; verify the Infrastructure project builds with 0 warnings +- [x] 2.5 Edit `PlaceOrderCommandHandler`: `IBakerTaskRepository` out, `IMessagePublisher` in, publish `NotifyBakerMessage` after `SaveChangesAsync` with the em-dash-free comment that owns the gap; verify the constructor still lists seven dependencies and the baker-task write is gone from the handler +- [x] 2.6 Add `WebApi/Messaging/NotifyBakerConsumer.cs : BackgroundService` (own channel, identical queue declare, `AsyncEventingBasicConsumer`, manual ack, DI scope + `ISender.Send(new CreateBakerTaskCommand(...))`, log-and-nack-without-requeue on exception with the one dead-letter comment); register with `AddHostedService` in `Program.cs`; add `ConnectionStrings:RabbitMq` and `RabbitMq:QueueName` to `appsettings.json`; verify the WebApi project builds with 0 warnings and every comment in the consumer and the handler is em-dash-free + +## 3. After twin (Wolverine + Marten slices) + +- [x] 3.1 Edit `Program.cs` only: `UseRabbitMq(...).AutoProvision()` unconditional, `PublishMessage().ToRabbitQueue("layercake-after-baker-tasks").UseDurableOutbox()`, `ListenToRabbitQueue("layercake-after-baker-tasks")`, `AddCritterWatchMonitoring` still gated, `UseDurableLocalQueues()` kept or removed with an honest em-dash-free comment; add `ConnectionStrings:rabbitmq` to `appsettings.json`; verify `git status` shows no other `.cs` file in `src/after` changed +- [x] 3.2 Run `dotnet run --project src/after/LayerCake.Slices -- describe` with the compose stack up and verify the `layercake-after-baker-tasks` sending endpoint reports Durable mode; paste the relevant lines into the build log + +## 4. Shared contract suite (fixtures only) + +- [x] 4.1 Add `Testcontainers.RabbitMq` to the suite's csproj; add `RabbitMqContainerFixture` (`rabbitmq:4`) and register it as a second `ICollectionFixture<>` on both twin collections; verify the suite project builds +- [x] 4.2 Pass the container's connection string to both host fixtures via `UseSetting("ConnectionStrings:RabbitMq", ...)`; remove `DisableAllExternalWolverineTransports()` from `AfterHostFixture`, keep `RunWolverineInSoloMode()`, update the comment; verify no scenario file changed + +## 5. Verification + +- [x] 5.1 Run `dotnet test` twice with Docker running and verify 54/54 on both hosts plus 15/15 unit facts, 0 build warnings, both times; record the wall-clock seconds against the 13 s baseline measured before this slice +- [x] 5.2 With the compose stack up, run both twins live, place one order on each through `src/frontend/index.html`, and verify in the RabbitMQ management UI that both `layercake-*-baker-tasks` queues exist with one consumer and zero backlog, that the baker's board shows the task on each twin, and that the CritterWatch queues are untouched +- [x] 5.3 Negative check, once, then revert: stop the broker mid-run or comment out the after twin's `ListenToRabbitQueue` line and verify `placing_order_produces_exactly_one_baker_task` fails on that twin; confirm `git diff` is clean of the experiment afterwards + +## 6. Bookkeeping and docs + +- [x] 6.1 Append a "Slice 004" section to `docs/file-inventory.md` (before twin `.cs` created and edited, after twin `.cs` created and edited, non-`.cs` wiring edits listed separately) and the whole-twin recount by the inventory's rule; verify the numbers by re-running the count command +- [x] 6.2 Append a dated `docs/build-log.md` entry: decisions as applied, surprises, the `describe` output, the suite timings, the negative-check outcome, the no-validator choice +- [x] 6.3 Update README (tour, run-it, monitor wording), CLAUDE.md (commands, tech-stack Messaging row, OpenSpec section and slate, CritterWatch RESOLVED line), `openspec/config.yaml` context, and the `docker-compose.yml` RabbitMQ comment; verify no file still claims the suite or `dotnet test` is broker-free diff --git a/openspec/config.yaml b/openspec/config.yaml index 3d66d19..0ad9d8e 100644 --- a/openspec/config.yaml +++ b/openspec/config.yaml @@ -14,10 +14,13 @@ context: | "after". "dotnet test" green twice is the talk's most credible artifact. CLAUDE.md is the build charter; read it before anything else. The slice - slate is LOCKED at three slices, built per-slice end to end in this order: - publish-browse-cakes, validate-coupon, place-order. Behavior is fully - settled in docs/slices/001-003 (contract clauses, required before-twin - structure, after-twin shape, scenario lists, seeds). Derive every change + slate is LOCKED at three features, built per-slice end to end in this order: + publish-browse-cakes, validate-coupon, place-order, plus slice 004 + (notify-baker-over-rabbitmq, amended by Erik 2026-09-05), which extends + place-order's side effect onto a real RabbitMQ broker in both twins without + adding an endpoint. Behavior is fully settled in docs/slices/001-004 + (contract clauses, required before-twin structure, after-twin shape, + scenario lists, seeds). Derive every change artifact from those specs; do not re-litigate settled decisions, and route surviving ambiguity to the author rather than assuming. @@ -26,7 +29,8 @@ context: | are one capability with two implementations, never two capabilities. Workflow: one change per slice, named slice-001-publish-browse-cakes, - slice-002-validate-coupon, slice-003-place-order. OpenSpec is adopted thin + slice-002-validate-coupon, slice-003-place-order, + slice-004-notify-baker-over-rabbitmq. OpenSpec is adopted thin here: task checklists and an archive trail, not re-planning. # Per-artifact rules. @@ -42,7 +46,7 @@ rules: tasks: - Order tasks per the charter's build discipline; before twin, after twin, shared contract scenarios, seeds, then verification. - Every slice ends with the same two bookkeeping tasks; append the before twin's honest file list to docs/file-inventory.md, and record mid-build decisions in docs/build-log.md. - - Definition of done for the slice is the shared suite green on BOTH hosts (`dotnet test` with Docker running; the suite starts its own PostgreSQL through Testcontainers). + - Definition of done for the slice is the shared suite green on BOTH hosts (`dotnet test` with Docker running; the suite starts its own PostgreSQL and RabbitMQ through Testcontainers). # Per-operation guidance. operations: diff --git a/openspec/specs/orders/spec.md b/openspec/specs/orders/spec.md index 2cdda36..988cb20 100644 --- a/openspec/specs/orders/spec.md +++ b/openspec/specs/orders/spec.md @@ -74,7 +74,7 @@ Both twins SHALL expose `GET /orders/{id}` returning exactly `200` with the same ### Requirement: Placing an order produces exactly one baker task -Placing an order SHALL produce exactly one baker task for that order, observable via `GET /baker/tasks` returning exactly `200` with a camelCase array `[ { orderId, summary, createdAt } ]`, filterable with an optional `?orderId={id}` query parameter. The task MAY appear asynchronously after the `201`, so observers SHALL poll with a short timeout; once present, the count for that order SHALL be exactly one (never zero after settling, never duplicated). The contract does not reveal which twin produces the task synchronously. +Placing an order SHALL produce exactly one baker task for that order, observable via `GET /baker/tasks` returning exactly `200` with a camelCase array `[ { orderId, summary, createdAt } ]`, filterable with an optional `?orderId={id}` query parameter. The notification that creates the task SHALL be delivered through a RabbitMQ queue in both twins before the task is written; the task appears asynchronously after the `201`, so observers SHALL poll with a short timeout. Once present, the count for that order SHALL be exactly one (never zero after settling, never duplicated), including when the broker redelivers the notification. With no broker reachable, no task SHALL appear on either twin. The HTTP contract does not reveal which broker, queue, or client library either twin uses. #### Scenario: placing_order_produces_exactly_one_baker_task From c0f78e7f804fdd7b62e821e41d5a84b05f447e40 Mon Sep 17 00:00:00 2001 From: Erik Shafer Date: Sat, 5 Sep 2026 19:10:18 -0500 Subject: [PATCH 2/3] Slice 004: the baker notification crosses RabbitMQ on both twins Before twin (raw RabbitMQ.Client 7.2.2, no framework, no outbox): - IMessagePublisher port in Application; NotifyBakerMessage; a CreateBakerTask command + handler as the consumer's re-dispatch target, idempotent through IBakerTaskRepository.ExistsForOrderAsync. - RabbitMqOptions, RabbitMqConnection (one lazy connection per host, disposed with it), RabbitMqMessagePublisher (channel per publish, durable queue, camelCase JSON, persistent delivery, default exchange). Options bound by hand: the section binder lives in a package this project does not reference and the freeze allows no third addition. - NotifyBakerConsumer BackgroundService in WebApi: own channel, same queue declare, manual ack, DI scope, ISender.Send, log-and-nack on failure. - PlaceOrderCommandHandler: IBakerTaskRepository out, IMessagePublisher in; publish after SaveChangesAsync. The dual-write gap is owned in one comment. After twin, Program.cs only: UseRabbitMq unconditional, PublishMessage().ToRabbitQueue(...).UseDurableOutbox(), ListenToRabbitQueue(...). UseDurableLocalQueues removed; no local message remains. PlaceOrder.cs and NotifyBaker.cs untouched. Contract suite, fixtures only: Testcontainers.RabbitMq 4.14.0, one rabbitmq:4 container per twin collection, connection string into both hosts, DisableAllExternalWolverineTransports dropped from the after fixture. No scenario changed. Package ADDITIONS at Erik's call, never bumps: RabbitMQ.Client 7.2.2 (the version WolverineFx.RabbitMQ 6.30.0 already depends on) and Testcontainers.RabbitMq 4.14.0. Existing pins untouched. Build 0 warnings. Contract suite 54/54, unit tests 15/15, three runs. dotnet test --no-build: 13 s before, 19 s cold / 14 s warm after. Negative check: with the after twin's listener commented out, the exactly-one-baker-task scenario fails on that twin and still passes on the other; reverted. --- Directory.Packages.props | 12 +++ docker-compose.yml | 5 +- .../LayerCake.Slices/LayerCake.Slices.csproj | 4 +- src/after/LayerCake.Slices/Program.cs | 32 ++++--- src/after/LayerCake.Slices/appsettings.json | 3 +- .../CreateBakerTask/CreateBakerTaskCommand.cs | 9 ++ .../CreateBakerTaskCommandHandler.cs | 36 +++++++ .../Common/Interfaces/IBakerTaskRepository.cs | 7 +- .../Common/Interfaces/IMessagePublisher.cs | 11 +++ .../Common/Interfaces/IUnitOfWork.cs | 6 +- .../PlaceOrder/PlaceOrderCommandHandler.cs | 20 ++-- .../Orders/Messages/NotifyBakerMessage.cs | 8 ++ .../DependencyInjection.cs | 16 ++++ .../LayerCake.Infrastructure.csproj | 3 + .../Messaging/RabbitMqConnection.cs | 82 ++++++++++++++++ .../Messaging/RabbitMqMessagePublisher.cs | 49 ++++++++++ .../Messaging/RabbitMqOptions.cs | 14 +++ .../Repositories/BakerTaskRepository.cs | 7 ++ .../Messaging/NotifyBakerConsumer.cs | 93 +++++++++++++++++++ src/before/LayerCake.WebApi/Program.cs | 4 + src/before/LayerCake.WebApi/appsettings.json | 6 +- .../LayerCake.ContractTests.csproj | 1 + tests/LayerCake.ContractTests/TwinHosts.cs | 54 ++++++++--- 23 files changed, 437 insertions(+), 45 deletions(-) create mode 100644 src/before/LayerCake.Application/Baker/Commands/CreateBakerTask/CreateBakerTaskCommand.cs create mode 100644 src/before/LayerCake.Application/Baker/Commands/CreateBakerTask/CreateBakerTaskCommandHandler.cs create mode 100644 src/before/LayerCake.Application/Common/Interfaces/IMessagePublisher.cs create mode 100644 src/before/LayerCake.Application/Orders/Messages/NotifyBakerMessage.cs create mode 100644 src/before/LayerCake.Infrastructure/Messaging/RabbitMqConnection.cs create mode 100644 src/before/LayerCake.Infrastructure/Messaging/RabbitMqMessagePublisher.cs create mode 100644 src/before/LayerCake.Infrastructure/Messaging/RabbitMqOptions.cs create mode 100644 src/before/LayerCake.WebApi/Messaging/NotifyBakerConsumer.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index 2db0e0b..06b3ac6 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -45,6 +45,13 @@ + + @@ -61,5 +68,10 @@ suite starts its own PostgreSQL per twin so "dotnet test" needs Docker running and nothing else. Same pin as mmo-reconnect. --> + + diff --git a/docker-compose.yml b/docker-compose.yml index b5e8c30..6d3fbef 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -20,8 +20,9 @@ services: timeout: 5s retries: 5 - # Telemetry channel between the after twin and the CritterWatch console. - # Only the live demo needs it; the contract tests never touch RabbitMQ. + # The baker notification crosses this broker on BOTH twins (slice 004), and + # it is also the telemetry channel to the CritterWatch console. The contract + # tests start their own broker through Testcontainers and never touch this one. rabbitmq: image: rabbitmq:4-management container_name: layercake-rabbitmq diff --git a/src/after/LayerCake.Slices/LayerCake.Slices.csproj b/src/after/LayerCake.Slices/LayerCake.Slices.csproj index 7173653..e2cc8be 100644 --- a/src/after/LayerCake.Slices/LayerCake.Slices.csproj +++ b/src/after/LayerCake.Slices/LayerCake.Slices.csproj @@ -16,8 +16,10 @@ + never need the console running. --> + diff --git a/src/after/LayerCake.Slices/Program.cs b/src/after/LayerCake.Slices/Program.cs index 2ffd874..c5fc91d 100644 --- a/src/after/LayerCake.Slices/Program.cs +++ b/src/after/LayerCake.Slices/Program.cs @@ -1,6 +1,7 @@ using JasperFx; using LayerCake.Slices; using LayerCake.Slices.Cakes; +using LayerCake.Slices.Orders; using Marten; using Marten.Schema; using Weasel.Core; @@ -47,23 +48,30 @@ opts.Policies.AutoApplyTransactions(); opts.ServiceName = "LayerCake"; - // Local queues are in-memory by default. Durable makes the cascaded - // NotifyBaker an actual outbox message: written to the Wolverine envelope - // table in the SAME Marten transaction as the order, replayed after a - // crash, delivered at least once. Without this line "no order without a - // baker task" only holds while the process stays up. - opts.Policies.UseDurableLocalQueues(); + // The broker is part of the app now, not just the telemetry channel. + // AutoProvision declares the queue on startup; the contract suite points + // this at its own Testcontainers broker through the same setting. + opts.UseRabbitMq(new Uri(builder.Configuration.GetConnectionString("rabbitmq") ?? "amqp://localhost")) + .AutoProvision(); + + // The cascaded NotifyBaker goes to RabbitMQ. UseDurableOutbox keeps it an + // outbox message: the envelope is written to the Wolverine table in the + // SAME Marten transaction as the order and sent to the broker after the + // commit, replayed after a crash, delivered at least once. Without this + // line "no order without a baker task" only holds while the process stays up. + opts.PublishMessage() + .ToRabbitQueue("layercake-after-baker-tasks") + .UseDurableOutbox(); + + // The same host consumes the queue, so NotifyBakerHandler runs in-process + // after the message has crossed the broker. + opts.ListenToRabbitQueue("layercake-after-baker-tasks"); // CritterWatch monitoring is opt-in via launchSettings (the live-demo run). // The contract tests boot this host through Alba without the flag, so - // `dotnet test` never needs RabbitMQ or the console running. + // `dotnet test` never needs the console running. if (builder.Configuration.GetValue("CritterWatch:Enabled")) { - // Telemetry channel only; no conventional routing, so no accidental - // message surface appears on the broker. - opts.UseRabbitMq(new Uri(builder.Configuration.GetConnectionString("rabbitmq") ?? "amqp://localhost")) - .AutoProvision(); - // Telemetry out to the console's well-known intake queue; control // commands back on this service's private queue. opts.AddCritterWatchMonitoring( diff --git a/src/after/LayerCake.Slices/appsettings.json b/src/after/LayerCake.Slices/appsettings.json index 1d0fb4e..481e775 100644 --- a/src/after/LayerCake.Slices/appsettings.json +++ b/src/after/LayerCake.Slices/appsettings.json @@ -1,6 +1,7 @@ { "ConnectionStrings": { - "Postgres": "Host=localhost;Port=5432;Database=layercake;Username=postgres;Password=postgres" + "Postgres": "Host=localhost;Port=5432;Database=layercake;Username=postgres;Password=postgres", + "rabbitmq": "amqp://localhost" }, "Logging": { "LogLevel": { diff --git a/src/before/LayerCake.Application/Baker/Commands/CreateBakerTask/CreateBakerTaskCommand.cs b/src/before/LayerCake.Application/Baker/Commands/CreateBakerTask/CreateBakerTaskCommand.cs new file mode 100644 index 0000000..8a1ac1e --- /dev/null +++ b/src/before/LayerCake.Application/Baker/Commands/CreateBakerTask/CreateBakerTaskCommand.cs @@ -0,0 +1,9 @@ +using MediatR; + +namespace LayerCake.Application.Baker.Commands.CreateBakerTask; + +/// +/// Creates the baker's to-do entry for an order. Dispatched by the RabbitMQ +/// consumer in WebApi once a NotifyBakerMessage arrives. +/// +public sealed record CreateBakerTaskCommand(Guid OrderId, string Summary) : IRequest; diff --git a/src/before/LayerCake.Application/Baker/Commands/CreateBakerTask/CreateBakerTaskCommandHandler.cs b/src/before/LayerCake.Application/Baker/Commands/CreateBakerTask/CreateBakerTaskCommandHandler.cs new file mode 100644 index 0000000..ccc2df9 --- /dev/null +++ b/src/before/LayerCake.Application/Baker/Commands/CreateBakerTask/CreateBakerTaskCommandHandler.cs @@ -0,0 +1,36 @@ +using LayerCake.Application.Common.Interfaces; +using LayerCake.Domain.Entities; +using MediatR; + +namespace LayerCake.Application.Baker.Commands.CreateBakerTask; + +public sealed class CreateBakerTaskCommandHandler : IRequestHandler +{ + private readonly IBakerTaskRepository _bakerTaskRepository; + private readonly IUnitOfWork _unitOfWork; + + public CreateBakerTaskCommandHandler(IBakerTaskRepository bakerTaskRepository, IUnitOfWork unitOfWork) + { + _bakerTaskRepository = bakerTaskRepository; + _unitOfWork = unitOfWork; + } + + public async Task Handle(CreateBakerTaskCommand request, CancellationToken cancellationToken) + { + // The broker delivers at least once; the contract promises exactly one + // task per order. A redelivered message must find its work already done. + if (await _bakerTaskRepository.ExistsForOrderAsync(request.OrderId, cancellationToken)) + { + return; + } + + _bakerTaskRepository.Add(new BakerTask + { + Id = Guid.NewGuid(), + OrderId = request.OrderId, + Summary = request.Summary + }); + + await _unitOfWork.SaveChangesAsync(cancellationToken); + } +} diff --git a/src/before/LayerCake.Application/Common/Interfaces/IBakerTaskRepository.cs b/src/before/LayerCake.Application/Common/Interfaces/IBakerTaskRepository.cs index d6ae4c5..3e4799e 100644 --- a/src/before/LayerCake.Application/Common/Interfaces/IBakerTaskRepository.cs +++ b/src/before/LayerCake.Application/Common/Interfaces/IBakerTaskRepository.cs @@ -3,13 +3,14 @@ namespace LayerCake.Application.Common.Interfaces; /// -/// Abstraction over baker-task persistence. Add stages only (no save) so a -/// task always commits in the same transaction as the order that caused it; -/// the handler saves once through . +/// Abstraction over baker-task persistence. Add stages only (no save); the +/// handler that stages a task commits it through . /// public interface IBakerTaskRepository { Task> GetAllAsync(Guid? orderId, CancellationToken cancellationToken); + Task ExistsForOrderAsync(Guid orderId, CancellationToken cancellationToken); + void Add(BakerTask bakerTask); } diff --git a/src/before/LayerCake.Application/Common/Interfaces/IMessagePublisher.cs b/src/before/LayerCake.Application/Common/Interfaces/IMessagePublisher.cs new file mode 100644 index 0000000..2fa74b8 --- /dev/null +++ b/src/before/LayerCake.Application/Common/Interfaces/IMessagePublisher.cs @@ -0,0 +1,11 @@ +namespace LayerCake.Application.Common.Interfaces; + +/// +/// The port for putting a message on the wire. The Application layer knows +/// that a message leaves the process; which broker, which queue, and which +/// client library are Infrastructure's business. +/// +public interface IMessagePublisher +{ + Task PublishAsync(TMessage message, CancellationToken cancellationToken); +} diff --git a/src/before/LayerCake.Application/Common/Interfaces/IUnitOfWork.cs b/src/before/LayerCake.Application/Common/Interfaces/IUnitOfWork.cs index ed3baaf..ca3c7bd 100644 --- a/src/before/LayerCake.Application/Common/Interfaces/IUnitOfWork.cs +++ b/src/before/LayerCake.Application/Common/Interfaces/IUnitOfWork.cs @@ -1,9 +1,9 @@ namespace LayerCake.Application.Common.Interfaces; /// -/// The transaction boundary. PlaceOrder writes an order AND a baker task -/// atomically, so those repositories only stage changes and the handler -/// commits them here in one save. +/// The transaction boundary. Repositories only stage changes; the handler +/// that owns the use case commits them here in one save. PlaceOrder commits +/// the order and then publishes; CreateBakerTask commits the task. /// public interface IUnitOfWork { diff --git a/src/before/LayerCake.Application/Orders/Commands/PlaceOrder/PlaceOrderCommandHandler.cs b/src/before/LayerCake.Application/Orders/Commands/PlaceOrder/PlaceOrderCommandHandler.cs index 9ce337f..f3e78f9 100644 --- a/src/before/LayerCake.Application/Orders/Commands/PlaceOrder/PlaceOrderCommandHandler.cs +++ b/src/before/LayerCake.Application/Orders/Commands/PlaceOrder/PlaceOrderCommandHandler.cs @@ -2,6 +2,7 @@ using LayerCake.Application.Common.Exceptions; using LayerCake.Application.Common.Interfaces; using LayerCake.Application.Coupons; +using LayerCake.Application.Orders.Messages; using LayerCake.Domain.Entities; using LayerCake.Domain.Enums; using MediatR; @@ -14,7 +15,7 @@ public sealed class PlaceOrderCommandHandler : IRequestHandler Handle(PlaceOrderCommand request, CancellationToken _orderRepository.Add(order); - // Notify the baker inline, mid-transaction. Imagine this line is SendGrid. - _bakerTaskRepository.Add(new BakerTask - { - Id = Guid.NewGuid(), - OrderId = order.Id, - Summary = string.Join(", ", orderLines.Select(l => $"{l.Quantity}x {l.Name}")) - }); - await _unitOfWork.SaveChangesAsync(cancellationToken); + // Published after the commit. If this line throws, the order exists and + // the baker never hears. No outbox, because most real ones do not have one. + var summary = string.Join(", ", orderLines.Select(l => $"{l.Quantity}x {l.Name}")); + await _messagePublisher.PublishAsync(new NotifyBakerMessage(order.Id, summary), cancellationToken); + return _mapper.Map(order); } } diff --git a/src/before/LayerCake.Application/Orders/Messages/NotifyBakerMessage.cs b/src/before/LayerCake.Application/Orders/Messages/NotifyBakerMessage.cs new file mode 100644 index 0000000..4031231 --- /dev/null +++ b/src/before/LayerCake.Application/Orders/Messages/NotifyBakerMessage.cs @@ -0,0 +1,8 @@ +namespace LayerCake.Application.Orders.Messages; + +/// +/// The wire message that tells the bakers an order needs making. Published +/// by PlaceOrder after its commit and consumed by the WebApi hosted service, +/// which re-dispatches it as a CreateBakerTaskCommand. +/// +public sealed record NotifyBakerMessage(Guid OrderId, string Summary); diff --git a/src/before/LayerCake.Infrastructure/DependencyInjection.cs b/src/before/LayerCake.Infrastructure/DependencyInjection.cs index b286f4f..b65c8e9 100644 --- a/src/before/LayerCake.Infrastructure/DependencyInjection.cs +++ b/src/before/LayerCake.Infrastructure/DependencyInjection.cs @@ -1,4 +1,5 @@ using LayerCake.Application.Common.Interfaces; +using LayerCake.Infrastructure.Messaging; using LayerCake.Infrastructure.Persistence; using LayerCake.Infrastructure.Repositories; using LayerCake.Infrastructure.Services; @@ -30,6 +31,21 @@ public static IServiceCollection AddInfrastructure( services.AddSingleton(); + // Slice 004: the broker adapter behind IMessagePublisher. The queue + // name comes from the RabbitMq section; the URI from ConnectionStrings + // so it sits beside Postgres in appsettings and in the test fixture. + // Bound by hand: the section binder lives in a package this project + // does not reference, and the freeze allows no third addition. + services.Configure(options => + { + options.ConnectionUri = configuration.GetConnectionString("RabbitMq") ?? options.ConnectionUri; + options.QueueName = configuration[$"{RabbitMqOptions.SectionName}:QueueName"] ?? options.QueueName; + }); + + // One connection per host; the container disposes it with the host. + services.AddSingleton(); + services.AddSingleton(); + return services; } } diff --git a/src/before/LayerCake.Infrastructure/LayerCake.Infrastructure.csproj b/src/before/LayerCake.Infrastructure/LayerCake.Infrastructure.csproj index 81a8486..baf02dd 100644 --- a/src/before/LayerCake.Infrastructure/LayerCake.Infrastructure.csproj +++ b/src/before/LayerCake.Infrastructure/LayerCake.Infrastructure.csproj @@ -7,6 +7,9 @@ + + diff --git a/src/before/LayerCake.Infrastructure/Messaging/RabbitMqConnection.cs b/src/before/LayerCake.Infrastructure/Messaging/RabbitMqConnection.cs new file mode 100644 index 0000000..ba2f5ae --- /dev/null +++ b/src/before/LayerCake.Infrastructure/Messaging/RabbitMqConnection.cs @@ -0,0 +1,82 @@ +using Microsoft.Extensions.Options; +using RabbitMQ.Client; + +namespace LayerCake.Infrastructure.Messaging; + +/// +/// One broker connection per host process, opened on first use and closed +/// when the host disposes it. Channels are cheap and short-lived; the +/// connection is the expensive thing, so the publisher and the consumer +/// share this one. +/// +public sealed class RabbitMqConnection : IAsyncDisposable +{ + private readonly RabbitMqOptions _options; + private readonly SemaphoreSlim _gate = new(1, 1); + private IConnection? _connection; + + public RabbitMqConnection(IOptions options) + { + _options = options.Value; + } + + public string QueueName => _options.QueueName; + + public async Task GetConnectionAsync(CancellationToken cancellationToken) + { + if (_connection is { IsOpen: true }) + { + return _connection; + } + + await _gate.WaitAsync(cancellationToken); + try + { + if (_connection is { IsOpen: true }) + { + return _connection; + } + + if (_connection is not null) + { + await _connection.DisposeAsync(); + } + + var factory = new ConnectionFactory { Uri = new Uri(_options.ConnectionUri) }; + _connection = await factory.CreateConnectionAsync(cancellationToken); + + return _connection; + } + finally + { + _gate.Release(); + } + } + + /// + /// Declares the baker-task queue. Both the publisher and the consumer call + /// this, so whichever starts first creates the queue and the other side's + /// declare is a no-op. The arguments live here once because RabbitMQ + /// refuses a redeclaration with different arguments. + /// + public Task DeclareQueueAsync(IChannel channel, CancellationToken cancellationToken) + { + return channel.QueueDeclareAsync( + queue: _options.QueueName, + durable: true, + exclusive: false, + autoDelete: false, + arguments: null, + cancellationToken: cancellationToken); + } + + public async ValueTask DisposeAsync() + { + if (_connection is not null) + { + await _connection.DisposeAsync(); + } + + _gate.Dispose(); + } +} diff --git a/src/before/LayerCake.Infrastructure/Messaging/RabbitMqMessagePublisher.cs b/src/before/LayerCake.Infrastructure/Messaging/RabbitMqMessagePublisher.cs new file mode 100644 index 0000000..5d4da2b --- /dev/null +++ b/src/before/LayerCake.Infrastructure/Messaging/RabbitMqMessagePublisher.cs @@ -0,0 +1,49 @@ +using System.Text.Json; +using LayerCake.Application.Common.Interfaces; +using RabbitMQ.Client; + +namespace LayerCake.Infrastructure.Messaging; + +/// +/// The adapter behind IMessagePublisher: serializes the message as camelCase +/// JSON and publishes it to the baker-task queue through the default +/// exchange, routing key equal to the queue name, persistent delivery so +/// the message survives a broker restart alongside the durable queue. +/// +public sealed class RabbitMqMessagePublisher : IMessagePublisher +{ + private static readonly JsonSerializerOptions SerializerOptions = new(JsonSerializerDefaults.Web); + + private readonly RabbitMqConnection _connection; + + public RabbitMqMessagePublisher(RabbitMqConnection connection) + { + _connection = connection; + } + + public async Task PublishAsync(TMessage message, CancellationToken cancellationToken) + { + var connection = await _connection.GetConnectionAsync(cancellationToken); + + // A channel per publish: channels are not thread-safe, and the handler + // that calls this runs per request. + await using var channel = await connection.CreateChannelAsync(cancellationToken: cancellationToken); + + await _connection.DeclareQueueAsync(channel, cancellationToken); + + var body = JsonSerializer.SerializeToUtf8Bytes(message, SerializerOptions); + var properties = new BasicProperties + { + ContentType = "application/json", + Persistent = true + }; + + await channel.BasicPublishAsync( + exchange: string.Empty, + routingKey: _connection.QueueName, + mandatory: false, + basicProperties: properties, + body: body, + cancellationToken: cancellationToken); + } +} diff --git a/src/before/LayerCake.Infrastructure/Messaging/RabbitMqOptions.cs b/src/before/LayerCake.Infrastructure/Messaging/RabbitMqOptions.cs new file mode 100644 index 0000000..07000f9 --- /dev/null +++ b/src/before/LayerCake.Infrastructure/Messaging/RabbitMqOptions.cs @@ -0,0 +1,14 @@ +namespace LayerCake.Infrastructure.Messaging; + +/// +/// Broker settings for the baker notification. The connection URI comes from +/// ConnectionStrings:RabbitMq and the rest from the RabbitMq section. +/// +public sealed class RabbitMqOptions +{ + public const string SectionName = "RabbitMq"; + + public string ConnectionUri { get; set; } = "amqp://localhost"; + + public string QueueName { get; set; } = "layercake-before-baker-tasks"; +} diff --git a/src/before/LayerCake.Infrastructure/Repositories/BakerTaskRepository.cs b/src/before/LayerCake.Infrastructure/Repositories/BakerTaskRepository.cs index 79a0877..2358796 100644 --- a/src/before/LayerCake.Infrastructure/Repositories/BakerTaskRepository.cs +++ b/src/before/LayerCake.Infrastructure/Repositories/BakerTaskRepository.cs @@ -33,6 +33,13 @@ public async Task> GetAllAsync(Guid? orderId, Cancellat .ToListAsync(cancellationToken); } + public async Task ExistsForOrderAsync(Guid orderId, CancellationToken cancellationToken) + { + return await _dbContext.BakerTasks + .AsNoTracking() + .AnyAsync(t => t.OrderId == orderId, cancellationToken); + } + public void Add(BakerTask bakerTask) { _dbContext.BakerTasks.Add(bakerTask); diff --git a/src/before/LayerCake.WebApi/Messaging/NotifyBakerConsumer.cs b/src/before/LayerCake.WebApi/Messaging/NotifyBakerConsumer.cs new file mode 100644 index 0000000..2566dc2 --- /dev/null +++ b/src/before/LayerCake.WebApi/Messaging/NotifyBakerConsumer.cs @@ -0,0 +1,93 @@ +using System.Text.Json; +using LayerCake.Application.Baker.Commands.CreateBakerTask; +using LayerCake.Application.Orders.Messages; +using LayerCake.Infrastructure.Messaging; +using MediatR; +using RabbitMQ.Client; +using RabbitMQ.Client.Events; + +namespace LayerCake.WebApi.Messaging; + +/// +/// Pulls NotifyBakerMessage off the baker-task queue and re-dispatches it as a +/// CreateBakerTaskCommand. A consumer is a delivery mechanism like a +/// controller, so it lives in the outer ring and stays thin the same way: +/// deserialize, open a scope, send a command, acknowledge. +/// +public sealed class NotifyBakerConsumer : BackgroundService +{ + private static readonly JsonSerializerOptions SerializerOptions = new(JsonSerializerDefaults.Web); + + private readonly RabbitMqConnection _connection; + private readonly IServiceScopeFactory _scopeFactory; + private readonly ILogger _logger; + private IChannel? _channel; + + public NotifyBakerConsumer( + RabbitMqConnection connection, + IServiceScopeFactory scopeFactory, + ILogger logger) + { + _connection = connection; + _scopeFactory = scopeFactory; + _logger = logger; + } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + var connection = await _connection.GetConnectionAsync(stoppingToken); + + // One long-lived channel for the life of the host. The same declare as + // the publisher, so start order between the two does not matter and a + // message published before this subscription waits in the queue. + _channel = await connection.CreateChannelAsync(cancellationToken: stoppingToken); + await _connection.DeclareQueueAsync(_channel, stoppingToken); + + // One unacknowledged message at a time keeps the handler's work serial. + await _channel.BasicQosAsync(prefetchSize: 0, prefetchCount: 1, global: false, stoppingToken); + + var consumer = new AsyncEventingBasicConsumer(_channel); + consumer.ReceivedAsync += (_, args) => HandleAsync(args, stoppingToken); + + await _channel.BasicConsumeAsync( + queue: _connection.QueueName, + autoAck: false, + consumer: consumer, + cancellationToken: stoppingToken); + } + + private async Task HandleAsync(BasicDeliverEventArgs args, CancellationToken cancellationToken) + { + try + { + var message = JsonSerializer.Deserialize(args.Body.Span, SerializerOptions) + ?? throw new JsonException("Empty NotifyBakerMessage body."); + + // Handlers and repositories are scoped; a broker callback has no + // request scope of its own, so the consumer opens one per message. + using var scope = _scopeFactory.CreateScope(); + var sender = scope.ServiceProvider.GetRequiredService(); + + await sender.Send(new CreateBakerTaskCommand(message.OrderId, message.Summary), cancellationToken); + + await _channel!.BasicAckAsync(args.DeliveryTag, multiple: false, cancellationToken); + } + catch (Exception exception) + { + _logger.LogError(exception, "Failed to handle NotifyBakerMessage; dropping delivery {DeliveryTag}.", args.DeliveryTag); + + // Nack without requeue: a real system would dead-letter here. + await _channel!.BasicNackAsync(args.DeliveryTag, multiple: false, requeue: false, cancellationToken); + } + } + + public override async Task StopAsync(CancellationToken cancellationToken) + { + await base.StopAsync(cancellationToken); + + if (_channel is not null) + { + await _channel.DisposeAsync(); + } + } +} diff --git a/src/before/LayerCake.WebApi/Program.cs b/src/before/LayerCake.WebApi/Program.cs index 6a39a54..61073bc 100644 --- a/src/before/LayerCake.WebApi/Program.cs +++ b/src/before/LayerCake.WebApi/Program.cs @@ -2,6 +2,7 @@ using LayerCake.Infrastructure; using LayerCake.Infrastructure.Persistence; using LayerCake.WebApi.Filters; +using LayerCake.WebApi.Messaging; using Microsoft.EntityFrameworkCore; var builder = WebApplication.CreateBuilder(args); @@ -14,6 +15,9 @@ builder.Services.AddInfrastructure(builder.Configuration); builder.Services.AddCors(); +// The RabbitMQ consumer for the baker notification runs inside this host. +builder.Services.AddHostedService(); + var app = builder.Build(); if (app.Environment.IsDevelopment()) diff --git a/src/before/LayerCake.WebApi/appsettings.json b/src/before/LayerCake.WebApi/appsettings.json index 1d0fb4e..04dda9b 100644 --- a/src/before/LayerCake.WebApi/appsettings.json +++ b/src/before/LayerCake.WebApi/appsettings.json @@ -1,6 +1,10 @@ { "ConnectionStrings": { - "Postgres": "Host=localhost;Port=5432;Database=layercake;Username=postgres;Password=postgres" + "Postgres": "Host=localhost;Port=5432;Database=layercake;Username=postgres;Password=postgres", + "RabbitMq": "amqp://localhost" + }, + "RabbitMq": { + "QueueName": "layercake-before-baker-tasks" }, "Logging": { "LogLevel": { diff --git a/tests/LayerCake.ContractTests/LayerCake.ContractTests.csproj b/tests/LayerCake.ContractTests/LayerCake.ContractTests.csproj index 563ddd8..bafe971 100644 --- a/tests/LayerCake.ContractTests/LayerCake.ContractTests.csproj +++ b/tests/LayerCake.ContractTests/LayerCake.ContractTests.csproj @@ -16,6 +16,7 @@ + diff --git a/tests/LayerCake.ContractTests/TwinHosts.cs b/tests/LayerCake.ContractTests/TwinHosts.cs index 5b89476..e756903 100644 --- a/tests/LayerCake.ContractTests/TwinHosts.cs +++ b/tests/LayerCake.ContractTests/TwinHosts.cs @@ -6,6 +6,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Testcontainers.PostgreSql; +using Testcontainers.RabbitMq; using Wolverine; using Xunit; @@ -35,38 +36,64 @@ public async Task DisposeAsync() } } +/// +/// One throwaway RabbitMQ container per twin collection, the same way as +/// PostgreSQL: since slice 004 the baker notification crosses a real broker +/// on both twins, so the suite starts one and "dotnet test" still needs +/// Docker and nothing else. Same major as docker-compose.yml. +/// +public sealed class RabbitMqContainerFixture : IAsyncLifetime +{ + private readonly RabbitMqContainer _rabbitMq = new RabbitMqBuilder("rabbitmq:4").Build(); + + public string ConnectionString => _rabbitMq.GetConnectionString(); + + public async Task InitializeAsync() + { + await _rabbitMq.StartAsync(); + } + + public async Task DisposeAsync() + { + await _rabbitMq.DisposeAsync(); + } +} + /// /// Scenario classes for the same twin share an xUnit collection so they run /// sequentially: each class fixture resets that twin's schema and re-seeds, /// and parallel hosts would race on startup migrations and seed data. /// The two collections still run in parallel with each other, each on its -/// own container, so the twins never touch each other's database. +/// own database and broker containers, so the twins never touch each +/// other's data or consume each other's messages. /// [CollectionDefinition(Name)] -public sealed class BeforeTwinCollection : ICollectionFixture +public sealed class BeforeTwinCollection : ICollectionFixture, ICollectionFixture { public const string Name = "before twin"; } [CollectionDefinition(Name)] -public sealed class AfterTwinCollection : ICollectionFixture +public sealed class AfterTwinCollection : ICollectionFixture, ICollectionFixture { public const string Name = "after twin"; } /// /// Boots the before twin (Clean Architecture, EF Core + MediatR) for a test -/// class against the collection's container, applies the EF Core migrations, +/// class against the collection's containers, applies the EF Core migrations, /// then resets the "before" schema and re-seeds so every scenario class /// starts from the same three-cake catalog. /// public sealed class BeforeHostFixture : IAsyncLifetime { private readonly PostgresContainerFixture _postgres; + private readonly RabbitMqContainerFixture _rabbitMq; - public BeforeHostFixture(PostgresContainerFixture postgres) + public BeforeHostFixture(PostgresContainerFixture postgres, RabbitMqContainerFixture rabbitMq) { _postgres = postgres; + _rabbitMq = rabbitMq; } public IAlbaHost Host { get; private set; } = null!; @@ -76,6 +103,7 @@ public async Task InitializeAsync() Host = await AlbaHost.For(x => { x.UseSetting("ConnectionStrings:Postgres", _postgres.ConnectionString); + x.UseSetting("ConnectionStrings:RabbitMq", _rabbitMq.ConnectionString); }); using var scope = Host.Services.CreateScope(); @@ -102,16 +130,18 @@ public async Task DisposeAsync() /// /// Boots the after twin (vertical slices, Wolverine + Marten) for a test -/// class against the collection's container, builds the "after" schema, +/// class against the collection's containers, builds the "after" schema, /// then wipes its documents and re-seeds. /// public sealed class AfterHostFixture : IAsyncLifetime { private readonly PostgresContainerFixture _postgres; + private readonly RabbitMqContainerFixture _rabbitMq; - public AfterHostFixture(PostgresContainerFixture postgres) + public AfterHostFixture(PostgresContainerFixture postgres, RabbitMqContainerFixture rabbitMq) { _postgres = postgres; + _rabbitMq = rabbitMq; } public IAlbaHost Host { get; private set; } = null!; @@ -121,15 +151,17 @@ public async Task InitializeAsync() Host = await AlbaHost.For(x => { x.UseSetting("ConnectionStrings:Postgres", _postgres.ConnectionString); + // Configuration keys are case-insensitive, so this also satisfies + // the after twin's lowercase "rabbitmq" read. + x.UseSetting("ConnectionStrings:RabbitMq", _rabbitMq.ConnectionString); x.ConfigureServices(services => { // Solo mode: no node registration or leader election, so each // sequential test host boots fast and leaves no stale node rows. - // Stubbing external transports is belt-and-braces (RabbitMQ is - // already gated behind CritterWatch:Enabled, never set here) and - // is safe because the after twin only uses local routing. - services.DisableAllExternalWolverineTransports(); + // External transports are deliberately NOT stubbed: since slice + // 004 NotifyBaker crosses the collection's real broker, and a + // null sender would make the exactly-one-task scenario vacuous. services.RunWolverineInSoloMode(); }); }); From b46a22b234e19f8acac7be2b039aec5c9da239d1 Mon Sep 17 00:00:00 2001 From: Erik Shafer Date: Sat, 5 Sep 2026 19:10:18 -0500 Subject: [PATCH 3/3] Slice 004 bookkeeping: inventory, build log, README, CLAUDE.md - docs/file-inventory.md: slice 004 section. Before twin 8 .cs created / 6 edited (3 non-.cs wiring edits outside the count); after twin 0 created / 1 edited (2 non-.cs). Whole-twin recount: before 2,061 raw / 1,705 non-blank (was 1,733 / 1,432), after 703 / 581 (was 695 / 574). - docs/build-log.md: dated entry with the decisions as applied, the options-binder surprise, the describe output, suite timings, the live broker check, and the negative check. - README and CLAUDE.md: both twins use RabbitMQ for the baker notification; the suite starts its own broker; Messaging row in the tech-stack tables; slate lists slice 004 as an extension of PlaceOrder. --- CLAUDE.md | 18 +++++++++++------- README.md | 26 +++++++++++++++----------- docs/build-log.md | 1 + docs/file-inventory.md | 40 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 67 insertions(+), 18 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 8ebb935..985e45f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -14,11 +14,11 @@ This file is the routing layer for AI sessions: the non-negotiables, the build o ``` dotnet build # one solution, both twins + the CritterWatch console -dotnet test # the money shot: identical scenarios, green twice (Docker running is the only prerequisite); also runs the after-twin-only pure-function unit tests in tests/LayerCake.Slices.Tests -docker compose up -d # PostgreSQL 17 + RabbitMQ, for running the twins LIVE only (RabbitMQ only feeds CritterWatch) +dotnet test # the money shot: identical scenarios, green twice (Docker running is the only prerequisite; Testcontainers starts PostgreSQL AND RabbitMQ per twin); also runs the after-twin-only pure-function unit tests in tests/LayerCake.Slices.Tests +docker compose up -d # PostgreSQL 17 + RabbitMQ, for running the twins LIVE only (both twins put the baker notification on the broker; CritterWatch rides it too) ``` -`dotnet test` starts its own PostgreSQL 17 per twin via Testcontainers (`tests/LayerCake.ContractTests/TwinHosts.cs`); it never touches the compose database, RabbitMQ, or the console. +`dotnet test` starts its own PostgreSQL 17 and RabbitMQ 4 per twin via Testcontainers (`tests/LayerCake.ContractTests/TwinHosts.cs`); it never touches the compose database, the compose broker, or the console. Frontend demo page: run both twins, then open `src/frontend/index.html` straight from disk (no build step, no server). @@ -36,6 +36,7 @@ Ports (live demo only; Alba self-hosts in tests): before twin `42010`, after twi | Persistence | EF Core 10 + Npgsql, schema `before` | Marten documents, schema `after` | | Validation | FluentValidation via MediatR pipeline behavior | Wolverine `Validate()` / ProblemDetails guards | | Mapping | AutoMapper 14.0.0 (final OSS release, deliberate) | none (that is the point) | +| Messaging | `RabbitMQ.Client` publisher behind an Application port, `BackgroundService` consumer in WebApi re-dispatching through MediatR, publish after commit, no outbox | Wolverine RabbitMQ transport: `PublishMessage().ToRabbitQueue(...).UseDurableOutbox()` + `ListenToRabbitQueue`, all in `Program.cs` | | Database | PostgreSQL 17 (docker-compose live; Testcontainers under test) | same database, different schema | | Tests | shared Alba + xUnit + Shouldly contract suite | the same suite, same scenarios | @@ -87,7 +88,7 @@ The before twin follows conventional Clean Architecture idioms instead where the Build-week work runs through OpenSpec (`openspec/`, spec-driven schema, CLI 1.10.0). Adopted thin: task checklists, on-rails sessions, and an archive trail — never re-planning. -- **One change per slice**, matching the build order: `slice-001-publish-browse-cakes`, `slice-002-validate-coupon`, `slice-003-place-order`. Each change spans before twin + after twin + shared contract scenarios end to end. +- **One change per slice**, matching the build order: `slice-001-publish-browse-cakes`, `slice-002-validate-coupon`, `slice-003-place-order`, and (added 2026-09-05) `slice-004-notify-baker-over-rabbitmq`. Each change spans before twin + after twin + shared contract scenarios end to end. - Start a slice with `/opsx:propose`, implement with `/opsx:apply`, and `/opsx:archive` only when the shared suite is green on both hosts and the bookkeeping (file inventory, build log) is done. - **Change artifacts derive from `docs/slices/`.** The settled slice specs are the source of truth: proposals link to them instead of restating them, delta-spec requirements and scenario names mirror them, and nothing settled gets re-litigated in a proposal. Ambiguity that survives the slice spec goes to the author, not into an assumption. - **`openspec/specs/` accretes the built truth**: capabilities `cakes`, `coupons`, and `orders` materialize as slices archive. `docs/slices/` remains the design record; if the two diverge, the archived spec reflects what shipped and the divergence gets reconciled immediately. @@ -102,14 +103,15 @@ Build **per-slice, end to end** (before + after + contract scenarios), in this o | 1 | **PublishCake** (+ BrowseCakes read beat) | Act 1 hook: trivial write through a dozen layered files | `POST /cakes`, `GET /cakes`, `GET /cakes/{id}` | | 2 | **ValidateCoupon** | Railway Oriented Programming | `GET /coupons/{code}` always-200 envelope (statuses: invalid, notYetActive, expired, valid); coupons enter via seed data only | | 3 | **PlaceOrder** | A-Frame, side effects via outbox | `POST /orders` (optional `couponCode`), `GET /orders/{id}`, baker to-do read | +| 4 | **NotifyBaker over RabbitMQ** (extends 3; slate amended by Erik 2026-09-05) | What one message costs a layered codebase vs. a slice | No new endpoint. The baker notification crosses a RabbitMQ queue on BOTH twins (`layercake-before-baker-tasks`, `layercake-after-baker-tasks`); the exactly-one-baker-task scenario is the proof | -Slice designs are lifted-and-simplified from CritterMart (`PublishProduct`, `ValidateCoupon`, `PlaceOrder`), state-stored here instead of event-sourced. Coupon statuses come from date mechanics only: exists → active window → valid. "Exhausted" is out of scope (no redemption caps). The baker notification must be synchronously observable (bakers' to-do table with a read endpoint, not log tailing). +The three-slice lock stands for the talk's Act 3 features; slice 004 is an extension of PlaceOrder's side effect, not a fourth feature. Slice designs are lifted-and-simplified from CritterMart (`PublishProduct`, `ValidateCoupon`, `PlaceOrder`), state-stored here instead of event-sourced. Coupon statuses come from date mechanics only: exists → active window → valid. "Exhausted" is out of scope (no redemption caps). The baker notification must be synchronously observable (bakers' to-do table with a read endpoint, not log tailing). **Pre-agreed fallbacks:** coupon collapses to validate-only if PlaceOrder crowds the schedule; single-feature deep dive is the emergency compression. The static single-page frontend exists in `src/frontend/` (built 2026-08-25, spec `docs/frontend.md`); it is a demo surface only, not part of the proof, and the deck must never depend on it. ## Where detail lives -- **In this repo (agent-facing, canonical for BUILD):** `docs/slices/001-003` (per-slice specs: contract, required structure, scenarios, seeds), `docs/frontend.md` (the static demo page's design record), `docs/file-inventory.md` (the honest per-slice file counts; a slide depends on it), `docs/build-log.md` (decisions made mid-build), `openspec/` (change workflow per slice; `openspec/specs/` is canonical for what is BUILT so far). +- **In this repo (agent-facing, canonical for BUILD):** `docs/slices/001-004` (per-slice specs: contract, required structure, scenarios, seeds), `docs/frontend.md` (the static demo page's design record), `docs/file-inventory.md` (the honest per-slice file counts; a slide depends on it), `docs/build-log.md` (decisions made mid-build), `openspec/` (change workflow per slice; `openspec/specs/` is canonical for what is BUILT so far). - **Talk planning (canonical for the TALK, not mirrored here on purpose — narrative and slide beats stay out of the public repo):** the `presentations` repo, `how-i-gave-up-clean-architecture/` (plan.md with all locked decisions, slice-slate-gate.md, api-contract.md, jasperfx-research.md). Mirrored in the author's "Presentations & Talks" Claude project. - **Slice design sources:** CritterMart (`C:\Code\crittermart`), the quarry, not the vehicle. - **Generic Critter Stack mechanics:** the JasperFx ai-skills library (user-level, license required) and Context7 (`/jasperfx/wolverine`, `/jasperfx/marten`). This repo documents only what diverges. @@ -120,8 +122,10 @@ Slice designs are lifted-and-simplified from CritterMart (`PublishProduct`, `Val RESOLVED 2026-08-23 (details in `docs/slices/` and `docs/build-log.md`): error-shape parity (status + content type + reason discoverable, one shared assertion helper); two-schemas-one-database; PublishCake keeps the 409 duplicate-name guard; coupon validation is an always-200 envelope; `GET /cakes/{id}` stays. -RESOLVED 2026-08-25, upgrade pass (details in `docs/build-log.md`): JasperFx pins bumped to Wolverine 6.30.0 / Marten 9.29.0 before the freeze; CritterWatch 1.0.1 ADDED at Erik's explicit call — console host in `src/monitor/`, RabbitMQ in docker-compose, monitoring opt-in so the test suite stays broker-free. +RESOLVED 2026-08-25, upgrade pass (details in `docs/build-log.md`): JasperFx pins bumped to Wolverine 6.30.0 / Marten 9.29.0 before the freeze; CritterWatch 1.0.1 ADDED at Erik's explicit call — console host in `src/monitor/`, RabbitMQ in docker-compose, monitoring opt-in so the test suite never needs the console (since slice 004 the suite does start its own broker, for the baker notification, not for CritterWatch). RESOLVED 2026-09-02 (details in `docs/build-log.md`): the contract suite runs on **Testcontainers** (`Testcontainers.PostgreSql` 4.14.0 ADDED at Erik's call, an addition rather than a bump): one `postgres:17` container per twin collection, so `dotnet test` needs only Docker. docker-compose remains for the live demo (twins on their ports, the frontend page, CritterWatch). +RESOLVED 2026-09-05, slice 004 (details in `docs/slices/004-notify-baker-over-rabbitmq.md` and `docs/build-log.md`): the baker notification crosses RabbitMQ on BOTH twins. Before twin: raw `RabbitMQ.Client` 7.2.2 (ADDED at Erik's call), port in Application, publisher in Infrastructure, `BackgroundService` consumer in WebApi, publish after commit, NO outbox (the gap is owned on a slide). After twin: `Program.cs` only, `UseDurableOutbox` on the publish rule. Suite: `Testcontainers.RabbitMq` 4.14.0 (ADDED), one `rabbitmq:4` container per twin collection; the after fixture no longer stubs external transports. + RESOLVED 2026-08-23, slice 001 build (details in `docs/build-log.md`): EF Core **migrations**, not `EnsureCreated`, for the before twin (applied at startup in Development); Marten stored-JSON casing is **explicit camelCase** via `opts.UseSystemTextJsonForSerialization(casing: Casing.CamelCase)` (verified in `after.mt_doc_cake`). diff --git a/README.md b/README.md index 1b4a251..8eea789 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ dotnet build dotnet test ``` -`dotnet test` is the whole point of the repo. The suite starts a throwaway PostgreSQL 17 container per twin, migrates and seeds it, runs every scenario against the Clean Architecture host, runs the identical scenarios against the vertical-slice host, and tears both down. No compose step, no leftover state, no broker. The same command runs in CI on every push. +`dotnet test` is the whole point of the repo. The suite starts a throwaway PostgreSQL 17 container per twin, migrates and seeds it, runs every scenario against the Clean Architecture host, runs the identical scenarios against the vertical-slice host, and tears both down. Since the baker notification crosses RabbitMQ on both twins, the suite starts a throwaway RabbitMQ 4 container per twin the same way. No compose step, no leftover state. The same command runs in CI on every push. Want to poke at the APIs in a browser instead? See [Running it live](#running-it-live). @@ -67,6 +67,8 @@ A bakery publishes cakes, shoppers browse them, check a coupon, and place an ord | 2 | **Validate a coupon** | Railway-oriented flow. A coupon is `invalid`, `notYetActive`, `expired`, or `valid`, always as a 200 envelope. The evaluation is one shared function that the next feature reuses, which is the in-repo answer to "how do slices share logic?" | | 3 | **Place an order** | The A-Frame shape (load, decide purely, persist) and a reliable side effect: placing an order creates exactly one baker task. The after twin sends that through Marten's transactional outbox, so no order without a task and no task without an order. | +A fourth step extends feature 3 rather than adding a feature: the baker notification crosses a real RabbitMQ queue in both twins. The before twin writes a port, an adapter, a hosted consumer, and a re-dispatch to do it, and publishes after its commit with no outbox. The after twin changes `Program.cs` and nothing else. Same broker on both sides; only the idiom changes. It is recorded as slice 004 in `docs/slices/`. + Design notes for each feature, including the contract clauses, the required structure of each twin, and the scenario list, live in `docs/slices/`. ## The HTTP contract @@ -175,21 +177,21 @@ A second, smaller project, `tests/LayerCake.Slices.Tests`, exists for the after The scenarios assert what the contract says, not what is convenient: exact status codes rather than "any 2xx", the `Location` header on creates, the raw body never containing `percentOff` unless the coupon is valid, the discount math to the cent, and that placing an order produces exactly one baker task. For that last one the suite polls the baker endpoint with a short timeout and does not know or care which twin does the work asynchronously. -Each twin gets its own PostgreSQL 17 container from Testcontainers, has its schema applied (EF Core migrations on one side, Marten on the other), and is reset and reseeded per scenario class. The two twins run in parallel, and every scenario starts from the same three cakes and three coupons. +Each twin gets its own PostgreSQL 17 and RabbitMQ 4 containers from Testcontainers, has its schema applied (EF Core migrations on one side, Marten on the other), and is reset and reseeded per scenario class. The two twins run in parallel, and every scenario starts from the same three cakes and three coupons. ## Running it live The suite needs nothing but Docker, but to click around you want the twins running against a persistent database. ```bash -docker compose up -d # PostgreSQL 17 (+ RabbitMQ, only for the optional monitor) +docker compose up -d # PostgreSQL 17 + RabbitMQ 4 (both twins use the broker) dotnet run --project src/before/LayerCake.WebApi # http://localhost:42010 dotnet run --project src/after/LayerCake.Slices # http://localhost:42020 ``` Both twins apply their schema and seed data on startup in Development. Swagger UI is at `/swagger` on each. Both write to the one `layercake` database: EF Core into the `before` schema, Marten into the `after` schema. `docker compose down -v` wipes everything. -The after twin's default launch profile turns on CritterWatch telemetry and therefore expects RabbitMQ to be up (compose starts it). To run the after twin with only PostgreSQL, set `CritterWatch__Enabled=false` or pass `--no-launch-profile`. +Both twins expect RabbitMQ to be up (compose starts it): placing an order publishes the baker notification to a queue, and each twin consumes its own queue inside its own process. The after twin's default launch profile additionally turns on CritterWatch telemetry; set `CritterWatch__Enabled=false` or pass `--no-launch-profile` to run it without the console's queues. The broker's management UI is at http://localhost:15672 (guest/guest) if you want to watch the two `layercake-*-baker-tasks` queues. ### The demo page @@ -205,7 +207,7 @@ dotnet run --project src/monitor/LayerCake.CritterWatch dotnet run --project src/after/LayerCake.Slices ``` -Then exercise the after twin (the demo page is the easy way) and open the console. It keeps its own event store in a dedicated `critterwatch` PostgreSQL database; the compose file creates that database on a fresh volume, and an existing volume needs a one-off `CREATE DATABASE critterwatch;`. RabbitMQ is the telemetry channel between the twin and the console, which is why compose brings up a broker. In Development the console runs without a license key; outside Development it reads `JasperFx:LicenseKey` from user secrets (id `layercake-critterwatch`). `dotnet test` never touches any of this. +Then exercise the after twin (the demo page is the easy way) and open the console. It keeps its own event store in a dedicated `critterwatch` PostgreSQL database; the compose file creates that database on a fresh volume, and an existing volume needs a one-off `CREATE DATABASE critterwatch;`. RabbitMQ carries the telemetry between the twin and the console, on top of the baker notification it already carries for both twins. In Development the console runs without a license key; outside Development it reads `JasperFx:LicenseKey` from user secrets (id `layercake-critterwatch`). `dotnet test` never touches the console or the compose broker; it starts its own. ## Repo tour @@ -213,15 +215,15 @@ Then exercise the after twin (the demo page is the easy way) and open the consol src/ before/ the Clean Architecture twin LayerCake.Domain/ entities, enums, base classes - LayerCake.Application/ commands, queries, handlers, validators, DTOs, mapping profiles, interfaces - LayerCake.Infrastructure/ DbContext, EF configurations, migrations, repositories, services - LayerCake.WebApi/ controllers, exception filter, Program.cs (port 42010) + LayerCake.Application/ commands, queries, handlers, validators, DTOs, mapping profiles, interfaces (including the messaging port) + LayerCake.Infrastructure/ DbContext, EF configurations, migrations, repositories, services, the RabbitMQ publisher + LayerCake.WebApi/ controllers, exception filter, the RabbitMQ consumer, Program.cs (port 42010) after/ LayerCake.Slices/ the vertical-slice twin (port 42020) Cakes/ Cake.cs (the Marten document) plus one file per feature: PublishCake.cs, BrowseCakes.cs, GetCake.cs Coupons/ Coupon.cs, CouponValidation.cs (THE shared rule), ValidateCoupon.cs Orders/ Order.cs, BakerTask.cs, PlaceOrder.cs, NotifyBaker.cs, GetOrder.cs, GetBakerTasks.cs - Ping.cs, SeedData.cs, Program.cs + Ping.cs, SeedData.cs, Program.cs (Program.cs holds the whole RabbitMQ wiring) frontend/index.html the static demo page monitor/LayerCake.CritterWatch/ the optional monitoring console (port 42030) tests/ @@ -233,7 +235,7 @@ docs/ frontend.md the demo page's design record openspec/ the change workflow used during the build; specs/ is what actually shipped Directory.Packages.props every package version, pinned, with the reason for each pin -docker-compose.yml PostgreSQL 17 + RabbitMQ for running the twins live +docker-compose.yml PostgreSQL 17 + RabbitMQ 4 for running the twins live ``` ## Tech stack @@ -246,7 +248,9 @@ docker-compose.yml PostgreSQL 17 + RabbitMQ for running the tw | Persistence | EF Core 10 + Npgsql, schema `before` | [Marten](https://martendb.io/) 9 documents, schema `after` | | Validation | FluentValidation via a MediatR pipeline behavior | Wolverine `Validate` methods returning `ProblemDetails` | | Mapping | AutoMapper 14.0.0 | none | +| Messaging | `RabbitMQ.Client` publisher behind a port, `BackgroundService` consumer, no outbox | Wolverine's RabbitMQ transport with the durable outbox, configured in `Program.cs` | | Database | PostgreSQL 17 | PostgreSQL 17 | +| Broker | RabbitMQ 4 | RabbitMQ 4 | | Tests | the shared Alba + xUnit + Shouldly suite | the same suite | MediatR and AutoMapper are deliberately pinned at their final open-source releases, which is exactly where a lot of real layered codebases sit today. All versions were frozen before the talk's dry runs; the rationale for each pin is a comment in `Directory.Packages.props`. @@ -257,7 +261,7 @@ It is a laboratory built for a talk, not a starter template and not a production - Authentication and authorization. - Event sourcing. Both twins are state-stored; Marten is used purely as a document store here. If the after twin makes you curious, that refactor is one step away: see [CritterMart](https://github.com/erikshafer/crittermart), which these features were lifted and simplified from. -- Microservices, messaging between services, or anything beyond one deployable per twin. +- Microservices, messaging between services, or anything beyond one deployable per twin. The one RabbitMQ message here leaves and re-enters the same process on each side. - A frontend framework or SPA. The demo page is a single static file and the talk never depends on it. It is also not a claim that Clean Architecture is never the right call, or that the Critter Stack is the only way to write slices. It is one honest before-and-after you can clone, run, and argue with. diff --git a/docs/build-log.md b/docs/build-log.md index 7b90d9f..f4bb821 100644 --- a/docs/build-log.md +++ b/docs/build-log.md @@ -62,3 +62,4 @@ Running record of decisions made during build sessions: anything a later session - **2026-09-05** Audit Tier B, second pass (B3 + B4 from `docs/critter-stack-audit.md`). The flat `Features/` folder is gone: slices now live beside their documents in the bounded-context folders the style skill prefers (`Cakes/` holds `Cake.cs` + `PublishCake.cs`, `BrowseCakes.cs`, `GetCake.cs`; `Coupons/` holds `Coupon.cs` + `CouponValidation.cs`, `ValidateCoupon.cs`; `Orders/` holds `Order.cs`, `BakerTask.cs` + `PlaceOrder.cs`, `NotifyBaker.cs`, `GetOrder.cs`, `GetBakerTasks.cs`), `Ping.cs` sits at the project root with `SeedData.cs` and `Program.cs`, and `NotifyBakerHandler.cs` is renamed `NotifyBaker.cs` after the message it carries (style rule 1). Namespaces follow the folders (`LayerCake.Slices.Cakes` / `.Coupons` / `.Orders`; the `LayerCake.Slices.Features` and `.Features.Coupons` namespaces no longer exist), which made eleven `using` lines redundant and removed them. All moves via `git mv`, so history follows the files. No behaviour change; routes, contract, and file count unchanged. Paths updated in README (tour tree and the PublishCake pointer), `docs/file-inventory.md`, and the three slice specs; `openspec/changes/archive/` left as the historical record it is. Unit-test usings updated. Suite 54/54 + 15/15, 0 warnings. Line counts: after twin 695 raw / 574 non-blank (was 706 / 585; the eleven dropped usings), before twin unchanged. - **2026-09-05** Audit Tier B, third pass (B2). The two HTTP response records were named like events (`CakePublished`, `OrderPlaced`) while being neither events nor messages; the repo has no events at all (state-stored by design) and exactly one message, the command `NotifyBaker`. Renamed to noun phrases, `PublishedCake` and `PlacedOrder`, so `(PlacedOrder, NotifyBaker)` reads as response-plus-command at a glance and past tense stays reserved for events. The JasperFx sample style (`TodoCreationResponse`) was considered and declined: **Erik's standing rule, now in CLAUDE.md, is no role-word suffixes on type names (`Response`, `Request`, `Event`, `Message`, and the like) when avoidable; without the layers, the labels are not needed.** Rename only: routes, JSON shape, and contract untouched (the contract suite deserializes into its own records and never names these types). README code excerpt updated. A suffix scan of the whole solution found the after twin otherwise clean except `BakerTaskItem` in `GetBakerTasks.cs` (flagged, not changed); the before twin's `Command`/`Query`/`Dto`/`Request` suffixes are the Clean Architecture exhibit and stay by non-negotiable 1; the contract suite's private `CakeItem`/`OrderEnvelope`/`CouponEnvelope`/`BakerTaskItem` records are test-local deserialization shapes. Suite 54/54 + 15/15, 0 warnings. Line counts unchanged (after twin 695 raw / 574 non-blank). - **2026-09-05** Critter Stack audit closed (`docs/critter-stack-audit.md`). Across PRs #8 to #11: durable local queues (the outbox claim made true), solo-mode after-twin fixture, pure `NotifyBaker` handler returning `Store`, `tests/LayerCake.Slices.Tests` (15 pure-function facts), CritterWatch version coupling checked and the 6.29.1/6.30.0 mix kept with reasoning on the console csproj, slices moved from `Features/` into `Cakes/`/`Coupons/`/`Orders/`, `NotifyBaker.cs` rename, `PublishedCake`/`PlacedOrder` naming plus the no-role-word-suffix rule in CLAUDE.md. Accepted without change, reasons in the audit doc's closing status: inline clock (deliberate asymmetry exhibit), two round trips in `PlaceOrder.LoadAsync` (slide readability), explicit seeding over `IInitialData` (one line), unconditional `RuntimeCompilation` reference (Development-only repo), and the baker-task polling loop (the skill's own escape hatch for a shared suite). `BakerTaskItem` flagged for its `Item` suffix, left alone. Doc-only change; no code, counts unchanged (after twin 695 raw / 574 non-blank, before twin 1,733 / 1,432). +- **2026-09-05** Slice 004, NotifyBaker over RabbitMQ (`docs/slices/004-notify-baker-over-rabbitmq.md`, change `slice-004-notify-baker-over-rabbitmq`). Erik's call, same day: the baker notification crosses a real RabbitMQ broker on BOTH twins, so the talk can show what one message costs a layered codebase against a slice. Decisions as applied: same broker both sides, one durable queue per twin (`layercake-before-baker-tasks`, `layercake-after-baker-tasks`, default exchange, routing key = queue name) so the two hosts in one test process never consume each other's messages; before twin on raw `RabbitMQ.Client` 7.2.2 (async-first API throughout, no sync-over-async), publisher adapter in Infrastructure behind `IMessagePublisher` in Application, consumer as a `BackgroundService` in WebApi re-dispatching through MediatR (`CreateBakerTaskCommand`), publish AFTER `SaveChangesAsync` with NO outbox and the gap owned in one comment, idempotency via `IBakerTaskRepository.ExistsForOrderAsync`, log-and-nack-without-requeue on failure; after twin `Program.cs` only (`UseRabbitMq(...).AutoProvision()` unconditional, `PublishMessage().ToRabbitQueue(...).UseDurableOutbox()`, `ListenToRabbitQueue(...)`, `AddCritterWatchMonitoring` still gated), `PlaceOrder.cs` and `NotifyBaker.cs` untouched. `UseDurableLocalQueues()` REMOVED: with `NotifyBaker` on the broker there is no local message left for it to describe, and its comment claimed otherwise. Package ADDITIONS, never bumps: `RabbitMQ.Client` 7.2.2 (the exact version `WolverineFx.RabbitMQ` 6.30.0 already depends on, so one copy in the solution) and `Testcontainers.RabbitMq` 4.14.0 (same pin as PostgreSql). No validator for `CreateBakerTaskCommand`: the shape is fixed by deserialization and the pipeline does not demand one. `IUnitOfWork`'s summary edited because it claimed PlaceOrder writes the order and the task atomically, which stopped being true. Surprises: (1) `Infrastructure` has no `Microsoft.Extensions.Options.ConfigurationExtensions`, so `services.Configure(IConfigurationSection)` does not compile; rather than a third package addition the two options values are bound by hand through `Configure(Action)`, with a comment saying why. (2) `dotnet run -- describe` on the after twin lists only the local senders in its Senders table (Wolverine builds RabbitMQ senders on first use); the Message Routing table shows `LayerCake.Slices.Orders.NotifyBaker -> rabbitmq://queue/layercake-after-baker-tasks`, and the Listeners table shows `rabbitmq://queue/layercake-after-baker-tasks | layercake-after-baker-tasks | Durable | 32`. Wolverine keeps one endpoint object per queue URI, so `UseDurableOutbox()` on the publish rule makes the same endpoint durable on the listening side too (a durable inbox for free). (3) The before twin's consumer subscribes from a hosted service, so in the Alba fixture the first `POST` can beat the subscription; both sides declare the durable queue, the persistent message waits, the scenario passes on the first run. Suite: 54/54 + 15/15, 0 warnings, run three times. Wall-clock for `dotnet test --no-build`: 13 s before this slice; 19 s on the first run after (cold container start, image already cached) and 14 s on the second. Poll constants unchanged at 250 ms / 5 s. Live check with the compose stack: one order placed on each twin (through the same HTTP calls the demo page makes; the page itself was not driven because the browser tooling needed Erik to pick a Chrome instance), exactly one baker task appeared on each within a second, and the broker's management API showed both `layercake-*-baker-tasks` queues with 1 consumer, 0 backlog, 1 published, 1 acked; `critterwatch`, `layercake-control`, and the Wolverine dead-letter queue untouched. Negative check: with `ListenToRabbitQueue` commented out on the after twin, `AfterTwinOrders.placing_order_produces_exactly_one_baker_task` failed ("No baker task appeared for order ... within 5s; last body: []") while the before twin's run of the same scenario still passed; line restored, rebuilt, working tree clean of the experiment. Counts: before twin 8 `.cs` created / 6 edited (+3 non-`.cs` wiring), 2,061 raw / 1,705 non-blank (was 1,733 / 1,432); after twin 0 created / 1 edited (+1 non-`.cs`), 703 / 581 (was 695 / 574). diff --git a/docs/file-inventory.md b/docs/file-inventory.md index 7d83bcf..5c8935b 100644 --- a/docs/file-inventory.md +++ b/docs/file-inventory.md @@ -167,3 +167,43 @@ Whole-twin line counts re-run 2026-09-05 (same method): before twin 1,733 (uncha Whole-twin line counts re-run 2026-09-05 after Audit Tier B first pass (same method): after twin 706 raw / 585 non-blank (unchanged; the `NotifyBakerHandler` rewrite to a pure `Store` return is net zero), before twin 1,733 / 1,432 (unchanged). New project `tests/LayerCake.Slices.Tests` (4 files) is a test project and belongs to neither twin's count. Whole-twin line counts re-run 2026-09-05 after Audit Tier B second pass (same method): after twin 695 raw / 574 non-blank (was 706 / 585). The -11 is exactly the `using` lines made redundant when the slices moved from `Features/` into `Cakes/`, `Coupons/`, `Orders/` and took those namespaces. The per-slice paths above were rewritten to the new locations in the same change; file count per slice is unchanged. Before twin 1,733 / 1,432 (unchanged). + +## 004 NotifyBaker over RabbitMQ (recorded 2026-09-05) + +Same conventions as 001. Non-`.cs` wiring edits (`.csproj`, `appsettings.json`, `Directory.Packages.props`) are listed separately and stay OUTSIDE the count, so the count remains comparable with slices 001 to 003. This slice adds no endpoint and changes no contract; the numbers are what it costs each twin to put one existing side effect on a real broker. + +Before twin (8 files created): +- src/before/LayerCake.Application/Common/Interfaces/IMessagePublisher.cs +- src/before/LayerCake.Application/Orders/Messages/NotifyBakerMessage.cs +- src/before/LayerCake.Application/Baker/Commands/CreateBakerTask/CreateBakerTaskCommand.cs +- src/before/LayerCake.Application/Baker/Commands/CreateBakerTask/CreateBakerTaskCommandHandler.cs +- src/before/LayerCake.Infrastructure/Messaging/RabbitMqOptions.cs +- src/before/LayerCake.Infrastructure/Messaging/RabbitMqConnection.cs +- src/before/LayerCake.Infrastructure/Messaging/RabbitMqMessagePublisher.cs +- src/before/LayerCake.WebApi/Messaging/NotifyBakerConsumer.cs + +Before twin, earlier-slice `.cs` files edited (6): +- src/before/LayerCake.Application/Orders/Commands/PlaceOrder/PlaceOrderCommandHandler.cs (`IBakerTaskRepository` out, `IMessagePublisher` in; publish after the commit) +- src/before/LayerCake.Application/Common/Interfaces/IBakerTaskRepository.cs (`ExistsForOrderAsync`) +- src/before/LayerCake.Application/Common/Interfaces/IUnitOfWork.cs (summary no longer claims the order and the task share a transaction) +- src/before/LayerCake.Infrastructure/Repositories/BakerTaskRepository.cs (`ExistsForOrderAsync` implementation) +- src/before/LayerCake.Infrastructure/DependencyInjection.cs (options, connection singleton, publisher registration) +- src/before/LayerCake.WebApi/Program.cs (`AddHostedService`) + +Before twin, non-`.cs` wiring edits (outside the count, 3): +- src/before/LayerCake.Infrastructure/LayerCake.Infrastructure.csproj (`RabbitMQ.Client` reference) +- src/before/LayerCake.WebApi/appsettings.json (`ConnectionStrings:RabbitMq`, `RabbitMq:QueueName`) +- Directory.Packages.props (`RabbitMQ.Client` 7.2.2 pin; shared file) + +After twin (0 files created). + +After twin, `.cs` files edited (1): +- src/after/LayerCake.Slices/Program.cs (`UseRabbitMq` unconditional, `PublishMessage().ToRabbitQueue(...).UseDurableOutbox()`, `ListenToRabbitQueue`; `UseDurableLocalQueues` and its comment removed) + +After twin, non-`.cs` wiring edits (outside the count, 2): +- src/after/LayerCake.Slices/appsettings.json (`ConnectionStrings:rabbitmq`, for discoverability; the code already had the fallback) +- src/after/LayerCake.Slices/LayerCake.Slices.csproj (comment only: it claimed the contract tests never need RabbitMQ) + +Shared contract suite (outside both counts): TwinHosts.cs edited (`RabbitMqContainerFixture`, second collection fixture on both twins, broker connection string into both hosts, `DisableAllExternalWolverineTransports` removed from the after fixture); the suite csproj gains `Testcontainers.RabbitMq`; Directory.Packages.props gains the `Testcontainers.RabbitMq` 4.14.0 pin. No scenario file changed. + +Whole-twin line counts re-run 2026-09-05 after slice 004 (same method): before twin 2,061 raw / 1,705 non-blank (was 1,733 / 1,432; +328 / +273, the eight new files plus the six edits above). After twin 703 raw / 581 non-blank (was 695 / 574; +8 / +7: the RabbitMQ block in `Program.cs` replaced `UseDurableLocalQueues()` and its comment).