|
| 1 | +# Saga Mediator |
| 2 | + |
| 3 | +<div class="grid cards" markdown> |
| 4 | + |
| 5 | +- :material-home: **Back to Bootstrap Overview** |
| 6 | + |
| 7 | + Return to the Bootstrap overview page with all configuration options. |
| 8 | + |
| 9 | + [:octicons-arrow-left-24: Back to Overview](index.md) |
| 10 | + |
| 11 | +- :material-sitemap: **Saga Pattern** |
| 12 | + |
| 13 | + Flow, storage, recovery, and compensation. |
| 14 | + |
| 15 | + [:octicons-arrow-right-24: Read More](../saga/index.md) |
| 16 | + |
| 17 | +</div> |
| 18 | + |
| 19 | +## Overview |
| 20 | + |
| 21 | +The `SagaMediator` runs orchestrated sagas: it resolves the saga by context type, creates a transaction, and streams step results. It is bootstrapped via `cqrs.saga.bootstrap.bootstrap()` with a saga map, DI container, optional saga storage, and optional event mapping for domain events emitted by steps. |
| 22 | + |
| 23 | +### Basic Configuration |
| 24 | + |
| 25 | +```python |
| 26 | +import di |
| 27 | +import cqrs |
| 28 | +from cqrs.saga import bootstrap |
| 29 | +from cqrs.saga.storage.memory import MemorySagaStorage |
| 30 | + |
| 31 | +def saga_mapper(mapper: cqrs.SagaMap) -> None: |
| 32 | + mapper.bind(OrderContext, OrderSaga) |
| 33 | + |
| 34 | +storage = MemorySagaStorage() |
| 35 | + |
| 36 | +mediator = bootstrap.bootstrap( |
| 37 | + di_container=di.Container(), |
| 38 | + sagas_mapper=saga_mapper, |
| 39 | + saga_storage=storage, |
| 40 | +) |
| 41 | +``` |
| 42 | + |
| 43 | +### With Domain Events |
| 44 | + |
| 45 | +Steps can emit domain events; the mediator uses an event emitter and event map (same as request bootstrap). Register handlers via `domain_events_mapper`: |
| 46 | + |
| 47 | +```python |
| 48 | +def events_mapper(mapper: cqrs.EventMap) -> None: |
| 49 | + mapper.bind(InventoryReservedEvent, InventoryReservedEventHandler) |
| 50 | + |
| 51 | +mediator = bootstrap.bootstrap( |
| 52 | + di_container=di.Container(), |
| 53 | + sagas_mapper=saga_mapper, |
| 54 | + domain_events_mapper=events_mapper, |
| 55 | + saga_storage=storage, |
| 56 | +) |
| 57 | +``` |
| 58 | + |
| 59 | +### With Message Broker |
| 60 | + |
| 61 | +By default the event emitter uses `DevnullMessageBroker`. To publish events to Kafka or RabbitMQ, pass `message_broker`: |
| 62 | + |
| 63 | +```python |
| 64 | +from cqrs.message_brokers import kafka |
| 65 | +from cqrs.adapters.kafka import KafkaProducerAdapter |
| 66 | + |
| 67 | +kafka_producer = KafkaProducerAdapter( |
| 68 | + bootstrap_servers=["localhost:9092"], |
| 69 | + client_id="my-app", |
| 70 | +) |
| 71 | + |
| 72 | +mediator = bootstrap.bootstrap( |
| 73 | + di_container=di.Container(), |
| 74 | + sagas_mapper=saga_mapper, |
| 75 | + domain_events_mapper=events_mapper, |
| 76 | + saga_storage=storage, |
| 77 | + message_broker=kafka.KafkaMessageBroker( |
| 78 | + producer=kafka_producer, |
| 79 | + aiokafka_log_level="ERROR", |
| 80 | + ), |
| 81 | +) |
| 82 | +``` |
| 83 | + |
| 84 | +### With Middlewares and On Startup |
| 85 | + |
| 86 | +```python |
| 87 | +from cqrs.middlewares import base |
| 88 | + |
| 89 | +class SagaLoggingMiddleware(base.Middleware): |
| 90 | + async def __call__(self, request: cqrs.Request, handle): |
| 91 | + print(f"Before saga step: {type(request).__name__}") |
| 92 | + result = await handle(request) |
| 93 | + print(f"After saga step: {type(request).__name__}") |
| 94 | + return result |
| 95 | + |
| 96 | +def init_storage(): |
| 97 | + # e.g. create tables for SqlAlchemySagaStorage |
| 98 | + pass |
| 99 | + |
| 100 | +mediator = bootstrap.bootstrap( |
| 101 | + di_container=di.Container(), |
| 102 | + sagas_mapper=saga_mapper, |
| 103 | + saga_storage=storage, |
| 104 | + middlewares=[SagaLoggingMiddleware()], |
| 105 | + on_startup=[init_storage], |
| 106 | +) |
| 107 | +``` |
| 108 | + |
| 109 | +### Executing a Saga |
| 110 | + |
| 111 | +Use `mediator.stream(context, saga_id=...)` to run the saga. It returns an async iterator; consume it with `async for`: |
| 112 | + |
| 113 | +```python |
| 114 | +import uuid |
| 115 | + |
| 116 | +context = OrderContext(order_id="123", items=["item_1"], total_amount=100.0) |
| 117 | +saga_id = uuid.uuid4() |
| 118 | + |
| 119 | +async for step_result in mediator.stream(context, saga_id=saga_id): |
| 120 | + print(f"Step completed: {step_result.step_type.__name__}") |
| 121 | +``` |
| 122 | + |
| 123 | +For recovery, use the same `saga_id` and call `recover_saga()` (see [Saga Recovery](../saga/recovery.md)). |
| 124 | + |
| 125 | +### Complete Example |
| 126 | + |
| 127 | +```python |
| 128 | +import dataclasses |
| 129 | +import uuid |
| 130 | +import di |
| 131 | +import cqrs |
| 132 | +from cqrs.saga import bootstrap |
| 133 | +from cqrs.saga.saga import Saga |
| 134 | +from cqrs.saga.step import SagaStepHandler, SagaStepResult |
| 135 | +from cqrs.saga.storage.memory import MemorySagaStorage |
| 136 | +from cqrs.saga.models import SagaContext |
| 137 | +from cqrs.response import Response |
| 138 | + |
| 139 | +@dataclasses.dataclass |
| 140 | +class OrderContext(SagaContext): |
| 141 | + order_id: str |
| 142 | + items: list[str] |
| 143 | + total_amount: float |
| 144 | + inventory_reservation_id: str | None = None |
| 145 | + payment_id: str | None = None |
| 146 | + |
| 147 | +class ReserveInventoryStep(SagaStepHandler[OrderContext, Response]): |
| 148 | + def __init__(self, inventory_service): |
| 149 | + self._inventory_service = inventory_service |
| 150 | + |
| 151 | + async def act(self, context: OrderContext) -> SagaStepResult: |
| 152 | + reservation_id = await self._inventory_service.reserve_items( |
| 153 | + context.order_id, context.items |
| 154 | + ) |
| 155 | + context.inventory_reservation_id = reservation_id |
| 156 | + return self._generate_step_result(Response()) |
| 157 | + |
| 158 | + async def compensate(self, context: OrderContext) -> None: |
| 159 | + if context.inventory_reservation_id: |
| 160 | + await self._inventory_service.release_items( |
| 161 | + context.inventory_reservation_id |
| 162 | + ) |
| 163 | + |
| 164 | +class OrderSaga(Saga[OrderContext]): |
| 165 | + steps = [ReserveInventoryStep] |
| 166 | + |
| 167 | +# Register services in container |
| 168 | +di_container = di.Container() |
| 169 | +# di_container.bind(...) |
| 170 | + |
| 171 | +def saga_mapper(mapper: cqrs.SagaMap) -> None: |
| 172 | + mapper.bind(OrderContext, OrderSaga) |
| 173 | + |
| 174 | +storage = MemorySagaStorage() |
| 175 | +mediator = bootstrap.bootstrap( |
| 176 | + di_container=di_container, |
| 177 | + sagas_mapper=saga_mapper, |
| 178 | + saga_storage=storage, |
| 179 | +) |
| 180 | + |
| 181 | +context = OrderContext(order_id="123", items=["item_1"], total_amount=100.0) |
| 182 | +saga_id = uuid.uuid4() |
| 183 | + |
| 184 | +async for step_result in mediator.stream(context, saga_id=saga_id): |
| 185 | + print(f"Step: {step_result.step_type.__name__}") |
| 186 | +``` |
| 187 | + |
| 188 | +## Bootstrap Parameters |
| 189 | + |
| 190 | +| Parameter | Description | |
| 191 | +|-----------|-------------| |
| 192 | +| `di_container` | DI container (`di.Container` or CQRS `Container`) for resolving saga step handlers | |
| 193 | +| `sagas_mapper` | Callable that receives `cqrs.SagaMap` and registers context type → saga class (e.g. `mapper.bind(OrderContext, OrderSaga)`) | |
| 194 | +| `saga_storage` | Optional `ISagaStorage` implementation. If `None`, defaults to in-memory behaviour when storage is needed. For production, use e.g. `SqlAlchemySagaStorage` and register it in the container | |
| 195 | +| `domain_events_mapper` | Optional callable to register event handlers (for events emitted by steps) | |
| 196 | +| `message_broker` | Optional message broker for event publishing; defaults to `DevnullMessageBroker` | |
| 197 | +| `middlewares` | Optional list of middlewares for request processing | |
| 198 | +| `on_startup` | Optional list of callables invoked once when bootstrap runs | |
| 199 | +| `max_concurrent_event_handlers` | Max concurrent event handlers (default: 1) | |
| 200 | +| `concurrent_event_handle_enable` | Whether to process events in parallel (default: True) | |
0 commit comments