python-saga-orchestrator 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- python_saga_orchestrator-0.1.0/LICENSE +21 -0
- python_saga_orchestrator-0.1.0/PKG-INFO +341 -0
- python_saga_orchestrator-0.1.0/README.md +307 -0
- python_saga_orchestrator-0.1.0/pyproject.toml +68 -0
- python_saga_orchestrator-0.1.0/python_saga_orchestrator.egg-info/PKG-INFO +341 -0
- python_saga_orchestrator-0.1.0/python_saga_orchestrator.egg-info/SOURCES.txt +28 -0
- python_saga_orchestrator-0.1.0/python_saga_orchestrator.egg-info/dependency_links.txt +1 -0
- python_saga_orchestrator-0.1.0/python_saga_orchestrator.egg-info/requires.txt +12 -0
- python_saga_orchestrator-0.1.0/python_saga_orchestrator.egg-info/top_level.txt +1 -0
- python_saga_orchestrator-0.1.0/saga_orchestrator/__init__.py +57 -0
- python_saga_orchestrator-0.1.0/saga_orchestrator/admin/__init__.py +7 -0
- python_saga_orchestrator-0.1.0/saga_orchestrator/admin/api.py +47 -0
- python_saga_orchestrator-0.1.0/saga_orchestrator/core/__init__.py +13 -0
- python_saga_orchestrator-0.1.0/saga_orchestrator/core/builder.py +106 -0
- python_saga_orchestrator-0.1.0/saga_orchestrator/core/engine.py +753 -0
- python_saga_orchestrator-0.1.0/saga_orchestrator/core/orchestrator.py +81 -0
- python_saga_orchestrator-0.1.0/saga_orchestrator/core/repository.py +166 -0
- python_saga_orchestrator-0.1.0/saga_orchestrator/domain/__init__.py +1 -0
- python_saga_orchestrator-0.1.0/saga_orchestrator/domain/exceptions/__init__.py +17 -0
- python_saga_orchestrator-0.1.0/saga_orchestrator/domain/exceptions/saga.py +22 -0
- python_saga_orchestrator-0.1.0/saga_orchestrator/domain/mixins/__init__.py +7 -0
- python_saga_orchestrator-0.1.0/saga_orchestrator/domain/mixins/saga_state.py +57 -0
- python_saga_orchestrator-0.1.0/saga_orchestrator/domain/models/__init__.py +21 -0
- python_saga_orchestrator-0.1.0/saga_orchestrator/domain/models/builder.py +12 -0
- python_saga_orchestrator-0.1.0/saga_orchestrator/domain/models/enums/__init__.py +7 -0
- python_saga_orchestrator-0.1.0/saga_orchestrator/domain/models/enums/saga_status.py +13 -0
- python_saga_orchestrator-0.1.0/saga_orchestrator/domain/models/retry.py +50 -0
- python_saga_orchestrator-0.1.0/saga_orchestrator/domain/models/saga_snapshot.py +36 -0
- python_saga_orchestrator-0.1.0/saga_orchestrator/domain/models/step.py +87 -0
- python_saga_orchestrator-0.1.0/setup.cfg +4 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: python-saga-orchestrator
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Lightweight embedded saga orchestrator for asyncio Python services
|
|
5
|
+
Author-email: Maxim Vasilyev <mayxis@inbox.ru>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/mdvasilyev/python-saga-orchestrator
|
|
8
|
+
Project-URL: Issues, https://github.com/mdvasilyev/python-saga-orchestrator/issues
|
|
9
|
+
Keywords: saga,orchestration,asyncio,sqlalchemy,distributed-transactions
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Framework :: AsyncIO
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Topic :: Database
|
|
17
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
18
|
+
Classifier: Topic :: System :: Distributed Computing
|
|
19
|
+
Requires-Python: >=3.12
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: asyncpg>=0.31.0
|
|
23
|
+
Requires-Dist: greenlet>=3.3.2
|
|
24
|
+
Requires-Dist: loguru>=0.7.3
|
|
25
|
+
Requires-Dist: pydantic>=2.12.5
|
|
26
|
+
Requires-Dist: sqlalchemy>=2.0.48
|
|
27
|
+
Provides-Extra: dev
|
|
28
|
+
Requires-Dist: build>=1.2.2; extra == "dev"
|
|
29
|
+
Requires-Dist: pytest>=8.3.4; extra == "dev"
|
|
30
|
+
Requires-Dist: pytest-asyncio>=1.3.0; extra == "dev"
|
|
31
|
+
Requires-Dist: ruff>=0.12.0; extra == "dev"
|
|
32
|
+
Requires-Dist: twine>=6.1.0; extra == "dev"
|
|
33
|
+
Dynamic: license-file
|
|
34
|
+
|
|
35
|
+
# python-saga-orchestrator
|
|
36
|
+
|
|
37
|
+
Lightweight embedded saga orchestration for `asyncio` Python services.
|
|
38
|
+
|
|
39
|
+
The library implements the Saga pattern for long-running business processes that:
|
|
40
|
+
- span multiple steps,
|
|
41
|
+
- call external systems,
|
|
42
|
+
- need retry and compensation,
|
|
43
|
+
- must survive worker crashes and process restarts.
|
|
44
|
+
|
|
45
|
+
Unlike external workflow platforms, this library runs inside your service and stores saga state in your application's database through SQLAlchemy.
|
|
46
|
+
|
|
47
|
+
## What it provides
|
|
48
|
+
|
|
49
|
+
- typed step definitions with `Pydantic` models
|
|
50
|
+
- saga construction with `SagaBuilder` and `StepRef`
|
|
51
|
+
- persisted saga state through `SagaStateMixin`
|
|
52
|
+
- runtime execution through `SagaOrchestrator` and `SagaEngine`
|
|
53
|
+
- retry, timeout, recovery, and compensation
|
|
54
|
+
- administrative operations through `SagaAdmin`
|
|
55
|
+
- PostgreSQL-first reliability using `SELECT ... FOR UPDATE`
|
|
56
|
+
|
|
57
|
+
## Installation
|
|
58
|
+
|
|
59
|
+
Requirements:
|
|
60
|
+
- Python 3.12+
|
|
61
|
+
- PostgreSQL for production-grade execution semantics
|
|
62
|
+
|
|
63
|
+
Install from source:
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
pip install .
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Or install development dependencies:
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
pip install .[dev]
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## Core concepts
|
|
76
|
+
|
|
77
|
+
### `BaseStep`
|
|
78
|
+
|
|
79
|
+
Each saga step is a class with:
|
|
80
|
+
- `execute(inp) -> out`
|
|
81
|
+
- optional `compensate(inp, out) -> None`
|
|
82
|
+
|
|
83
|
+
Steps are regular Python objects. In practice they are created once at application startup and reused.
|
|
84
|
+
|
|
85
|
+
### `SagaBuilder`
|
|
86
|
+
|
|
87
|
+
`SagaBuilder` creates an immutable `SagaDefinition`.
|
|
88
|
+
Each added step includes:
|
|
89
|
+
- the step object
|
|
90
|
+
- `input_map`
|
|
91
|
+
- optional timeout
|
|
92
|
+
- retry policy
|
|
93
|
+
- optional dependency on a previous step via `StepRef`
|
|
94
|
+
|
|
95
|
+
### `SagaStateMixin`
|
|
96
|
+
|
|
97
|
+
Your SQLAlchemy model inherits `SagaStateMixin` to store:
|
|
98
|
+
- current status
|
|
99
|
+
- current step index
|
|
100
|
+
- execution token
|
|
101
|
+
- context
|
|
102
|
+
- step history
|
|
103
|
+
- deadline
|
|
104
|
+
- retry counter
|
|
105
|
+
|
|
106
|
+
### `SagaOrchestrator`
|
|
107
|
+
|
|
108
|
+
`SagaOrchestrator` is the public runtime API used by application code:
|
|
109
|
+
- `register(...)`
|
|
110
|
+
- `start(...)`
|
|
111
|
+
- `notify(...)`
|
|
112
|
+
- `run_due(...)`
|
|
113
|
+
- `get_snapshot(...)`
|
|
114
|
+
|
|
115
|
+
### `SagaAdmin`
|
|
116
|
+
|
|
117
|
+
`SagaAdmin` exposes operational controls:
|
|
118
|
+
- `get_saga(...)`
|
|
119
|
+
- `retry_step(...)`
|
|
120
|
+
- `skip_step(...)`
|
|
121
|
+
- `compensate_step(...)`
|
|
122
|
+
- `abort(...)`
|
|
123
|
+
|
|
124
|
+
## Quick start
|
|
125
|
+
|
|
126
|
+
```python
|
|
127
|
+
from datetime import timedelta
|
|
128
|
+
|
|
129
|
+
from pydantic import BaseModel
|
|
130
|
+
from sqlalchemy.ext.asyncio import async_sessionmaker
|
|
131
|
+
from sqlalchemy.orm import DeclarativeBase
|
|
132
|
+
|
|
133
|
+
from saga_orchestrator import (
|
|
134
|
+
BaseStep,
|
|
135
|
+
ExponentialRetry,
|
|
136
|
+
SagaAdmin,
|
|
137
|
+
SagaBuilder,
|
|
138
|
+
SagaOrchestrator,
|
|
139
|
+
SagaStateMixin,
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class Base(DeclarativeBase):
|
|
144
|
+
pass
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class OrderSagaState(Base, SagaStateMixin):
|
|
148
|
+
__tablename__ = "order_saga_state"
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
class ReserveInput(BaseModel):
|
|
152
|
+
order_id: str
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class ReserveOutput(BaseModel):
|
|
156
|
+
reservation_id: str
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
class ChargeInput(BaseModel):
|
|
160
|
+
reservation_id: str
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class ChargeOutput(BaseModel):
|
|
164
|
+
payment_id: str
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
class ReserveInventoryStep(BaseStep[ReserveInput, ReserveOutput]):
|
|
168
|
+
async def execute(self, inp: ReserveInput) -> ReserveOutput:
|
|
169
|
+
return ReserveOutput(reservation_id=f"res-{inp.order_id}")
|
|
170
|
+
|
|
171
|
+
async def compensate(self, inp: ReserveInput, out: ReserveOutput) -> None:
|
|
172
|
+
return None
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
class ChargePaymentStep(BaseStep[ChargeInput, ChargeOutput]):
|
|
176
|
+
async def execute(self, inp: ChargeInput) -> ChargeOutput:
|
|
177
|
+
return ChargeOutput(payment_id=f"pay-{inp.reservation_id}")
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def build_order_saga():
|
|
181
|
+
builder = SagaBuilder()
|
|
182
|
+
|
|
183
|
+
reserve_ref = builder.add_step(
|
|
184
|
+
step=ReserveInventoryStep(),
|
|
185
|
+
input_map=lambda ctx: ReserveInput(order_id=ctx.initial_data["order_id"]),
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
builder.add_step(
|
|
189
|
+
step=ChargePaymentStep(),
|
|
190
|
+
depends_on=reserve_ref,
|
|
191
|
+
input_map=lambda out: ChargeInput(reservation_id=out.reservation_id),
|
|
192
|
+
retry_policy=ExponentialRetry(
|
|
193
|
+
max_attempts=3,
|
|
194
|
+
base_delay=timedelta(seconds=5),
|
|
195
|
+
),
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
return builder.build()
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def setup_saga(
|
|
202
|
+
session_maker: async_sessionmaker,
|
|
203
|
+
) -> tuple[SagaOrchestrator[OrderSagaState], SagaAdmin[OrderSagaState]]:
|
|
204
|
+
orchestrator = SagaOrchestrator[OrderSagaState](
|
|
205
|
+
model_class=OrderSagaState,
|
|
206
|
+
session_maker=session_maker,
|
|
207
|
+
)
|
|
208
|
+
orchestrator.register("create_order_v1", build_order_saga())
|
|
209
|
+
|
|
210
|
+
admin = SagaAdmin[OrderSagaState](engine=orchestrator.engine)
|
|
211
|
+
return orchestrator, admin
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
Start a saga:
|
|
215
|
+
|
|
216
|
+
```python
|
|
217
|
+
orchestrator, admin = setup_saga(session_maker)
|
|
218
|
+
|
|
219
|
+
saga_id = await orchestrator.start(
|
|
220
|
+
saga_name="create_order_v1",
|
|
221
|
+
initial_data={"order_id": "order-123"},
|
|
222
|
+
aggregation_id="order-123",
|
|
223
|
+
)
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
## Recovery model
|
|
227
|
+
|
|
228
|
+
The library persists enough state to recover work after failures:
|
|
229
|
+
|
|
230
|
+
- `RUNNING` sagas with expired execution leases can be reclaimed
|
|
231
|
+
- `SUSPENDED` sagas with expired retry deadlines can be resumed
|
|
232
|
+
- `COMPENSATING` sagas can continue rollback after a crash
|
|
233
|
+
|
|
234
|
+
The recovery entry point is:
|
|
235
|
+
|
|
236
|
+
```python
|
|
237
|
+
await orchestrator.run_due(limit=100)
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
In production this should be called by a background worker or scheduled job.
|
|
241
|
+
|
|
242
|
+
## Notifications and external events
|
|
243
|
+
|
|
244
|
+
Use `notify(...)` when a suspended saga should resume because of an external signal:
|
|
245
|
+
|
|
246
|
+
```python
|
|
247
|
+
accepted = await orchestrator.notify(
|
|
248
|
+
saga_id=saga_id,
|
|
249
|
+
token=current_token,
|
|
250
|
+
event={"approved": True},
|
|
251
|
+
)
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
The event payload is stored in saga context and can be used by root-step `input_map` functions through `InputContext`.
|
|
255
|
+
|
|
256
|
+
## Administrative operations
|
|
257
|
+
|
|
258
|
+
Get the full persisted state:
|
|
259
|
+
|
|
260
|
+
```python
|
|
261
|
+
snapshot = await admin.get_saga(saga_id)
|
|
262
|
+
print(snapshot.status)
|
|
263
|
+
print(snapshot.step_history)
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
Retry the current failed step:
|
|
267
|
+
|
|
268
|
+
```python
|
|
269
|
+
await admin.retry_step(saga_id)
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
Skip the current suspended step:
|
|
273
|
+
|
|
274
|
+
```python
|
|
275
|
+
await admin.skip_step(
|
|
276
|
+
saga_id,
|
|
277
|
+
mock_output={"payment_id": "manual-payment"},
|
|
278
|
+
)
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
Start compensation manually:
|
|
282
|
+
|
|
283
|
+
```python
|
|
284
|
+
await admin.compensate_step(saga_id)
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
Abort the saga:
|
|
288
|
+
|
|
289
|
+
```python
|
|
290
|
+
await admin.abort(saga_id)
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
## Persistence expectations
|
|
294
|
+
|
|
295
|
+
The library is PostgreSQL-first.
|
|
296
|
+
|
|
297
|
+
Important implementation details:
|
|
298
|
+
- state transitions are performed inside database transactions
|
|
299
|
+
- mutating reads use `SELECT ... FOR UPDATE`
|
|
300
|
+
- JSON state is stored in `context` and `step_history`
|
|
301
|
+
- `step_execution_token` is used to reject stale events and stale step completions
|
|
302
|
+
|
|
303
|
+
SQLite may be sufficient for local experiments, but PostgreSQL should be used for integration testing and production use.
|
|
304
|
+
|
|
305
|
+
## Example workflow
|
|
306
|
+
|
|
307
|
+
A runnable end-to-end example is available in:
|
|
308
|
+
|
|
309
|
+
- [`test.py`](./test.py)
|
|
310
|
+
|
|
311
|
+
It demonstrates:
|
|
312
|
+
- retry and recovery through `run_due()`
|
|
313
|
+
- compensation after failure
|
|
314
|
+
- admin-driven step skipping
|
|
315
|
+
|
|
316
|
+
## Running tests
|
|
317
|
+
|
|
318
|
+
Run unit tests:
|
|
319
|
+
|
|
320
|
+
```bash
|
|
321
|
+
pytest -q tests/unit
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
Run PostgreSQL integration tests:
|
|
325
|
+
|
|
326
|
+
```bash
|
|
327
|
+
export TEST_DATABASE_URL='postgresql+asyncpg://postgres:postgres@localhost:5432/saga_test_db'
|
|
328
|
+
pytest -q tests/integration
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
The integration fixture creates an isolated schema per test, so it does not require a dedicated empty database schema.
|
|
332
|
+
|
|
333
|
+
## Current limitations
|
|
334
|
+
|
|
335
|
+
- the implementation is optimized for sequential saga execution, not parallel DAG execution
|
|
336
|
+
- PostgreSQL is the intended reliability target
|
|
337
|
+
- tracing integration is not implemented yet
|
|
338
|
+
|
|
339
|
+
## License
|
|
340
|
+
|
|
341
|
+
MIT. See [`LICENSE`](./LICENSE).
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
# python-saga-orchestrator
|
|
2
|
+
|
|
3
|
+
Lightweight embedded saga orchestration for `asyncio` Python services.
|
|
4
|
+
|
|
5
|
+
The library implements the Saga pattern for long-running business processes that:
|
|
6
|
+
- span multiple steps,
|
|
7
|
+
- call external systems,
|
|
8
|
+
- need retry and compensation,
|
|
9
|
+
- must survive worker crashes and process restarts.
|
|
10
|
+
|
|
11
|
+
Unlike external workflow platforms, this library runs inside your service and stores saga state in your application's database through SQLAlchemy.
|
|
12
|
+
|
|
13
|
+
## What it provides
|
|
14
|
+
|
|
15
|
+
- typed step definitions with `Pydantic` models
|
|
16
|
+
- saga construction with `SagaBuilder` and `StepRef`
|
|
17
|
+
- persisted saga state through `SagaStateMixin`
|
|
18
|
+
- runtime execution through `SagaOrchestrator` and `SagaEngine`
|
|
19
|
+
- retry, timeout, recovery, and compensation
|
|
20
|
+
- administrative operations through `SagaAdmin`
|
|
21
|
+
- PostgreSQL-first reliability using `SELECT ... FOR UPDATE`
|
|
22
|
+
|
|
23
|
+
## Installation
|
|
24
|
+
|
|
25
|
+
Requirements:
|
|
26
|
+
- Python 3.12+
|
|
27
|
+
- PostgreSQL for production-grade execution semantics
|
|
28
|
+
|
|
29
|
+
Install from source:
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install .
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Or install development dependencies:
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install .[dev]
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Core concepts
|
|
42
|
+
|
|
43
|
+
### `BaseStep`
|
|
44
|
+
|
|
45
|
+
Each saga step is a class with:
|
|
46
|
+
- `execute(inp) -> out`
|
|
47
|
+
- optional `compensate(inp, out) -> None`
|
|
48
|
+
|
|
49
|
+
Steps are regular Python objects. In practice they are created once at application startup and reused.
|
|
50
|
+
|
|
51
|
+
### `SagaBuilder`
|
|
52
|
+
|
|
53
|
+
`SagaBuilder` creates an immutable `SagaDefinition`.
|
|
54
|
+
Each added step includes:
|
|
55
|
+
- the step object
|
|
56
|
+
- `input_map`
|
|
57
|
+
- optional timeout
|
|
58
|
+
- retry policy
|
|
59
|
+
- optional dependency on a previous step via `StepRef`
|
|
60
|
+
|
|
61
|
+
### `SagaStateMixin`
|
|
62
|
+
|
|
63
|
+
Your SQLAlchemy model inherits `SagaStateMixin` to store:
|
|
64
|
+
- current status
|
|
65
|
+
- current step index
|
|
66
|
+
- execution token
|
|
67
|
+
- context
|
|
68
|
+
- step history
|
|
69
|
+
- deadline
|
|
70
|
+
- retry counter
|
|
71
|
+
|
|
72
|
+
### `SagaOrchestrator`
|
|
73
|
+
|
|
74
|
+
`SagaOrchestrator` is the public runtime API used by application code:
|
|
75
|
+
- `register(...)`
|
|
76
|
+
- `start(...)`
|
|
77
|
+
- `notify(...)`
|
|
78
|
+
- `run_due(...)`
|
|
79
|
+
- `get_snapshot(...)`
|
|
80
|
+
|
|
81
|
+
### `SagaAdmin`
|
|
82
|
+
|
|
83
|
+
`SagaAdmin` exposes operational controls:
|
|
84
|
+
- `get_saga(...)`
|
|
85
|
+
- `retry_step(...)`
|
|
86
|
+
- `skip_step(...)`
|
|
87
|
+
- `compensate_step(...)`
|
|
88
|
+
- `abort(...)`
|
|
89
|
+
|
|
90
|
+
## Quick start
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
from datetime import timedelta
|
|
94
|
+
|
|
95
|
+
from pydantic import BaseModel
|
|
96
|
+
from sqlalchemy.ext.asyncio import async_sessionmaker
|
|
97
|
+
from sqlalchemy.orm import DeclarativeBase
|
|
98
|
+
|
|
99
|
+
from saga_orchestrator import (
|
|
100
|
+
BaseStep,
|
|
101
|
+
ExponentialRetry,
|
|
102
|
+
SagaAdmin,
|
|
103
|
+
SagaBuilder,
|
|
104
|
+
SagaOrchestrator,
|
|
105
|
+
SagaStateMixin,
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class Base(DeclarativeBase):
|
|
110
|
+
pass
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class OrderSagaState(Base, SagaStateMixin):
|
|
114
|
+
__tablename__ = "order_saga_state"
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class ReserveInput(BaseModel):
|
|
118
|
+
order_id: str
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class ReserveOutput(BaseModel):
|
|
122
|
+
reservation_id: str
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class ChargeInput(BaseModel):
|
|
126
|
+
reservation_id: str
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class ChargeOutput(BaseModel):
|
|
130
|
+
payment_id: str
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class ReserveInventoryStep(BaseStep[ReserveInput, ReserveOutput]):
|
|
134
|
+
async def execute(self, inp: ReserveInput) -> ReserveOutput:
|
|
135
|
+
return ReserveOutput(reservation_id=f"res-{inp.order_id}")
|
|
136
|
+
|
|
137
|
+
async def compensate(self, inp: ReserveInput, out: ReserveOutput) -> None:
|
|
138
|
+
return None
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class ChargePaymentStep(BaseStep[ChargeInput, ChargeOutput]):
|
|
142
|
+
async def execute(self, inp: ChargeInput) -> ChargeOutput:
|
|
143
|
+
return ChargeOutput(payment_id=f"pay-{inp.reservation_id}")
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def build_order_saga():
|
|
147
|
+
builder = SagaBuilder()
|
|
148
|
+
|
|
149
|
+
reserve_ref = builder.add_step(
|
|
150
|
+
step=ReserveInventoryStep(),
|
|
151
|
+
input_map=lambda ctx: ReserveInput(order_id=ctx.initial_data["order_id"]),
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
builder.add_step(
|
|
155
|
+
step=ChargePaymentStep(),
|
|
156
|
+
depends_on=reserve_ref,
|
|
157
|
+
input_map=lambda out: ChargeInput(reservation_id=out.reservation_id),
|
|
158
|
+
retry_policy=ExponentialRetry(
|
|
159
|
+
max_attempts=3,
|
|
160
|
+
base_delay=timedelta(seconds=5),
|
|
161
|
+
),
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
return builder.build()
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def setup_saga(
|
|
168
|
+
session_maker: async_sessionmaker,
|
|
169
|
+
) -> tuple[SagaOrchestrator[OrderSagaState], SagaAdmin[OrderSagaState]]:
|
|
170
|
+
orchestrator = SagaOrchestrator[OrderSagaState](
|
|
171
|
+
model_class=OrderSagaState,
|
|
172
|
+
session_maker=session_maker,
|
|
173
|
+
)
|
|
174
|
+
orchestrator.register("create_order_v1", build_order_saga())
|
|
175
|
+
|
|
176
|
+
admin = SagaAdmin[OrderSagaState](engine=orchestrator.engine)
|
|
177
|
+
return orchestrator, admin
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
Start a saga:
|
|
181
|
+
|
|
182
|
+
```python
|
|
183
|
+
orchestrator, admin = setup_saga(session_maker)
|
|
184
|
+
|
|
185
|
+
saga_id = await orchestrator.start(
|
|
186
|
+
saga_name="create_order_v1",
|
|
187
|
+
initial_data={"order_id": "order-123"},
|
|
188
|
+
aggregation_id="order-123",
|
|
189
|
+
)
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
## Recovery model
|
|
193
|
+
|
|
194
|
+
The library persists enough state to recover work after failures:
|
|
195
|
+
|
|
196
|
+
- `RUNNING` sagas with expired execution leases can be reclaimed
|
|
197
|
+
- `SUSPENDED` sagas with expired retry deadlines can be resumed
|
|
198
|
+
- `COMPENSATING` sagas can continue rollback after a crash
|
|
199
|
+
|
|
200
|
+
The recovery entry point is:
|
|
201
|
+
|
|
202
|
+
```python
|
|
203
|
+
await orchestrator.run_due(limit=100)
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
In production this should be called by a background worker or scheduled job.
|
|
207
|
+
|
|
208
|
+
## Notifications and external events
|
|
209
|
+
|
|
210
|
+
Use `notify(...)` when a suspended saga should resume because of an external signal:
|
|
211
|
+
|
|
212
|
+
```python
|
|
213
|
+
accepted = await orchestrator.notify(
|
|
214
|
+
saga_id=saga_id,
|
|
215
|
+
token=current_token,
|
|
216
|
+
event={"approved": True},
|
|
217
|
+
)
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
The event payload is stored in saga context and can be used by root-step `input_map` functions through `InputContext`.
|
|
221
|
+
|
|
222
|
+
## Administrative operations
|
|
223
|
+
|
|
224
|
+
Get the full persisted state:
|
|
225
|
+
|
|
226
|
+
```python
|
|
227
|
+
snapshot = await admin.get_saga(saga_id)
|
|
228
|
+
print(snapshot.status)
|
|
229
|
+
print(snapshot.step_history)
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
Retry the current failed step:
|
|
233
|
+
|
|
234
|
+
```python
|
|
235
|
+
await admin.retry_step(saga_id)
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
Skip the current suspended step:
|
|
239
|
+
|
|
240
|
+
```python
|
|
241
|
+
await admin.skip_step(
|
|
242
|
+
saga_id,
|
|
243
|
+
mock_output={"payment_id": "manual-payment"},
|
|
244
|
+
)
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
Start compensation manually:
|
|
248
|
+
|
|
249
|
+
```python
|
|
250
|
+
await admin.compensate_step(saga_id)
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
Abort the saga:
|
|
254
|
+
|
|
255
|
+
```python
|
|
256
|
+
await admin.abort(saga_id)
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
## Persistence expectations
|
|
260
|
+
|
|
261
|
+
The library is PostgreSQL-first.
|
|
262
|
+
|
|
263
|
+
Important implementation details:
|
|
264
|
+
- state transitions are performed inside database transactions
|
|
265
|
+
- mutating reads use `SELECT ... FOR UPDATE`
|
|
266
|
+
- JSON state is stored in `context` and `step_history`
|
|
267
|
+
- `step_execution_token` is used to reject stale events and stale step completions
|
|
268
|
+
|
|
269
|
+
SQLite may be sufficient for local experiments, but PostgreSQL should be used for integration testing and production use.
|
|
270
|
+
|
|
271
|
+
## Example workflow
|
|
272
|
+
|
|
273
|
+
A runnable end-to-end example is available in:
|
|
274
|
+
|
|
275
|
+
- [`test.py`](./test.py)
|
|
276
|
+
|
|
277
|
+
It demonstrates:
|
|
278
|
+
- retry and recovery through `run_due()`
|
|
279
|
+
- compensation after failure
|
|
280
|
+
- admin-driven step skipping
|
|
281
|
+
|
|
282
|
+
## Running tests
|
|
283
|
+
|
|
284
|
+
Run unit tests:
|
|
285
|
+
|
|
286
|
+
```bash
|
|
287
|
+
pytest -q tests/unit
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
Run PostgreSQL integration tests:
|
|
291
|
+
|
|
292
|
+
```bash
|
|
293
|
+
export TEST_DATABASE_URL='postgresql+asyncpg://postgres:postgres@localhost:5432/saga_test_db'
|
|
294
|
+
pytest -q tests/integration
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
The integration fixture creates an isolated schema per test, so it does not require a dedicated empty database schema.
|
|
298
|
+
|
|
299
|
+
## Current limitations
|
|
300
|
+
|
|
301
|
+
- the implementation is optimized for sequential saga execution, not parallel DAG execution
|
|
302
|
+
- PostgreSQL is the intended reliability target
|
|
303
|
+
- tracing integration is not implemented yet
|
|
304
|
+
|
|
305
|
+
## License
|
|
306
|
+
|
|
307
|
+
MIT. See [`LICENSE`](./LICENSE).
|