|
| 1 | +# ADR-002 — CQRS in the Application Layer |
| 2 | + |
| 3 | +| Field | Value | |
| 4 | +|--------------|---------------------| |
| 5 | +| **Date** | 2026-04-15 | |
| 6 | +| **Status** | Accepted | |
| 7 | +| **Deciders** | Project maintainers | |
| 8 | + |
| 9 | +--- |
| 10 | + |
| 11 | +## Context |
| 12 | + |
| 13 | +As the Sudoku application grew, a single `IGameApplicationService` interface was accumulating both state-mutating operations (create game, make move, abandon game) and read operations (get game, get player games, validate game). This conflation caused several problems: |
| 14 | + |
| 15 | +- **Concurrency and consistency**: Write paths require domain invariant enforcement and event raising; read paths benefit from lighter-weight execution paths that do not touch the domain model. |
| 16 | +- **Testability**: A monolithic service interface forces all handler tests to configure a large dependency surface even when testing a single operation. |
| 17 | +- **Extensibility**: Adding a new query or command to a shared service contract requires touching a single growing interface, increasing merge friction. |
| 18 | +- **Auditability**: Without separation, it is unclear which operations mutate state and which are safe to cache or replay. |
| 19 | + |
| 20 | +A pattern was needed that would enforce the separation of intent between reads and writes at the application boundary. |
| 21 | + |
| 22 | +--- |
| 23 | + |
| 24 | +## Decision |
| 25 | + |
| 26 | +The Application layer (`Sudoku.Application`) adopts **CQRS (Command Query Responsibility Segregation)** implemented via **MediatR** as the in-process mediator. |
| 27 | + |
| 28 | +### Core Abstractions |
| 29 | + |
| 30 | +| Abstraction | Contract | Return Type | |
| 31 | +|---|---|---| |
| 32 | +| `ICommand` | Extends `IRequest<Result>` | `Result` (success/failure) | |
| 33 | +| `ICommandHandler<TCommand>` | Extends `IRequestHandler<TCommand, Result>` | `Result` | |
| 34 | +| `IQuery<TResponse>` | Extends `IRequest<Result<TResponse>>` | `Result<TResponse>` | |
| 35 | +| `IQueryHandler<TQuery, TResponse>` | Extends `IRequestHandler<TQuery, Result<TResponse>>` | `Result<TResponse>` | |
| 36 | + |
| 37 | +All commands and queries are dispatched through MediatR's `IMediator` interface. Handlers are registered automatically via MediatR's assembly scanning at startup. |
| 38 | + |
| 39 | +### Registered Commands (14) |
| 40 | + |
| 41 | +`AbandonGameCommand`, `AddPossibleValueCommand`, `ClearPossibleValuesCommand`, `CompleteGameCommand`, `CreateGameCommand`, `DeleteGameCommand`, `DeletePlayerGamesCommand`, `MakeMoveCommand`, `PauseGameCommand`, `RemovePossibleValueCommand`, `ResetGameCommand`, `ResumeGameCommand`, `StartGameCommand`, `UndoLastMoveCommand` |
| 42 | + |
| 43 | +### Registered Queries (4) |
| 44 | + |
| 45 | +`GetGameQuery`, `GetPlayerGamesQuery`, `GetPlayerGamesByStatusQuery`, `ValidateGameQuery` |
| 46 | + |
| 47 | +### Interaction Flow |
| 48 | + |
| 49 | +```mermaid |
| 50 | +sequenceDiagram |
| 51 | + participant API as Sudoku.Api |
| 52 | + participant Mediator as MediatR IMediator |
| 53 | + participant Handler as CommandHandler / QueryHandler |
| 54 | + participant Domain as Sudoku.Domain |
| 55 | + participant Repo as IGameRepository |
| 56 | +
|
| 57 | + API->>Mediator: Send(command / query) |
| 58 | + Mediator->>Handler: Handle(command / query) |
| 59 | + Handler->>Domain: Call aggregate method (commands only) |
| 60 | + Domain-->>Handler: Raise domain events / return state |
| 61 | + Handler->>Repo: SaveAsync / GetByIdAsync |
| 62 | + Repo-->>Handler: Result |
| 63 | + Handler-->>Mediator: Result / Result<TResponse> |
| 64 | + Mediator-->>API: Result / Result<TResponse> |
| 65 | +``` |
| 66 | + |
| 67 | +### Rules |
| 68 | + |
| 69 | +1. **Commands never return domain objects.** They return `Result` (success/failure with optional error detail). If the caller needs updated state, it issues a subsequent query. |
| 70 | +2. **Queries never mutate state.** A query handler must not call any repository `SaveAsync`, `DeleteAsync`, or domain method that raises events. |
| 71 | +3. **Handlers are the only consumers of repository interfaces and domain aggregates.** Controllers call `IMediator.Send()`; they do not touch `IGameRepository` directly. |
| 72 | +4. **MediatR pipeline behaviors** (e.g., validation, logging) may be registered globally and apply to all commands and queries without modifying individual handlers. |
| 73 | + |
| 74 | +--- |
| 75 | + |
| 76 | +## Consequences |
| 77 | + |
| 78 | +### Positive |
| 79 | + |
| 80 | +- **Separation of concerns**: Write and read paths are independently testable and independently evolvable. |
| 81 | +- **Handler isolation**: Each handler has a narrow dependency surface. Tests configure only the dependencies relevant to that operation. |
| 82 | +- **Pipeline extensibility**: Cross-cutting concerns (validation, logging, timing) are added via MediatR pipeline behaviors without modifying any handler. |
| 83 | +- **Explicit intent**: The presence of a command communicates mutation intent; the presence of a query communicates read intent — both at compile time. |
| 84 | +- **Scalability path**: The pattern leaves the door open to separate read and write models (e.g., a denormalized read projection backed by a separate Cosmos DB container) without requiring structural refactoring. |
| 85 | + |
| 86 | +### Tradeoffs |
| 87 | + |
| 88 | +- **MediatR coupling**: All application orchestration is coupled to MediatR as an in-process mediator. Replacing MediatR would require changing all handler registrations and call sites in the API layer. |
| 89 | +- **Indirection**: A simple operation (e.g., `GetGame`) passes through `IMediator → GetGameQueryHandler → IGameRepository` rather than a direct service call. This is an intentional tradeoff for consistency and testability. |
| 90 | +- **No out-of-process messaging**: The current CQRS implementation is in-process only. Distributing commands or queries to a message bus (e.g., Azure Service Bus) would require introducing a separate messaging infrastructure layer. |
| 91 | + |
| 92 | +### Rules Enforced by This Decision |
| 93 | + |
| 94 | +1. **All new application operations must be expressed as a command or query**, not as a method added to `IGameApplicationService` or `IPlayerApplicationService`. |
| 95 | +2. **Never inject `IGameRepository` into a controller.** Repository access belongs exclusively in handlers. |
| 96 | +3. **Command handlers raise domain events; query handlers do not.** |
| 97 | +4. **Never return domain entities from a handler.** Commands return `Result`; queries return `Result<TDto>`. |
| 98 | + |
| 99 | +--- |
| 100 | + |
| 101 | +## Related ADRs |
| 102 | + |
| 103 | +- [ADR-001 — Adoption of Clean Architecture](ADR-001-clean-architecture.md) |
| 104 | +- [ADR-003 — Specification Pattern for Repository Queries](ADR-003-specification-pattern.md) *(forthcoming)* |
| 105 | +- [ADR-004 — Azure Cosmos DB as the Primary Game Persistence Backend](ADR-004-cosmosdb.md) *(forthcoming)* |
0 commit comments