python-saga-orchestrator 0.1.0__py3-none-any.whl
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.dist-info/METADATA +341 -0
- python_saga_orchestrator-0.1.0.dist-info/RECORD +25 -0
- python_saga_orchestrator-0.1.0.dist-info/WHEEL +5 -0
- python_saga_orchestrator-0.1.0.dist-info/licenses/LICENSE +21 -0
- python_saga_orchestrator-0.1.0.dist-info/top_level.txt +1 -0
- saga_orchestrator/__init__.py +57 -0
- saga_orchestrator/admin/__init__.py +7 -0
- saga_orchestrator/admin/api.py +47 -0
- saga_orchestrator/core/__init__.py +13 -0
- saga_orchestrator/core/builder.py +106 -0
- saga_orchestrator/core/engine.py +753 -0
- saga_orchestrator/core/orchestrator.py +81 -0
- saga_orchestrator/core/repository.py +166 -0
- saga_orchestrator/domain/__init__.py +1 -0
- saga_orchestrator/domain/exceptions/__init__.py +17 -0
- saga_orchestrator/domain/exceptions/saga.py +22 -0
- saga_orchestrator/domain/mixins/__init__.py +7 -0
- saga_orchestrator/domain/mixins/saga_state.py +57 -0
- saga_orchestrator/domain/models/__init__.py +21 -0
- saga_orchestrator/domain/models/builder.py +12 -0
- saga_orchestrator/domain/models/enums/__init__.py +7 -0
- saga_orchestrator/domain/models/enums/saga_status.py +13 -0
- saga_orchestrator/domain/models/retry.py +50 -0
- saga_orchestrator/domain/models/saga_snapshot.py +36 -0
- saga_orchestrator/domain/models/step.py +87 -0
|
@@ -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,25 @@
|
|
|
1
|
+
python_saga_orchestrator-0.1.0.dist-info/licenses/LICENSE,sha256=ESYyLizI0WWtxMeS7rGVcX3ivMezm-HOd5WdeOh-9oU,1056
|
|
2
|
+
saga_orchestrator/__init__.py,sha256=MCVa52nGc4FZn7RcZ3zaJ5nIFmc1WfHJjb2jnb7piXI,1227
|
|
3
|
+
saga_orchestrator/admin/__init__.py,sha256=TKwKTM7IieI4nlMAbJ0O0OI0KPKfwbclVffNjRtIyAg,80
|
|
4
|
+
saga_orchestrator/admin/api.py,sha256=zrgNXTBql-1LNz-5JHF64J0vH9xAm6Zv_37KAuC6DO4,1548
|
|
5
|
+
saga_orchestrator/core/__init__.py,sha256=EsUqhbO_CgCYZz0yBnf6OUXH3N-_uxMod4A7yGzvbMY,264
|
|
6
|
+
saga_orchestrator/core/builder.py,sha256=6cEydT1P4TRyIdlie8LTslkeGBwGVeT60cNHqFQk_CQ,3877
|
|
7
|
+
saga_orchestrator/core/engine.py,sha256=JM0jROTVzumjiv01QklapjwSA3ATMpbO00j10sNYzR8,30565
|
|
8
|
+
saga_orchestrator/core/orchestrator.py,sha256=vHzrQvWQ-UwBReveeZ2Ju3H8Gqr2m5nV08XDEQQ96xQ,2729
|
|
9
|
+
saga_orchestrator/core/repository.py,sha256=5a8zZ721dvxI17aqU1hzUTE7tekP_m-6415N9koFGgU,5452
|
|
10
|
+
saga_orchestrator/domain/__init__.py,sha256=ECVisQXiPSwx974Dbei_Ze_6SWqPVaQrTZPj_qESpYA,21
|
|
11
|
+
saga_orchestrator/domain/exceptions/__init__.py,sha256=smKhoR_G-PLtqvDkxgzCzDE7zfoztpUoFc0x4prdX4U,334
|
|
12
|
+
saga_orchestrator/domain/exceptions/saga.py,sha256=GeqxHJkHxobM8e8sVq69skP75_Sklo6mqFS9gFvTx4Y,567
|
|
13
|
+
saga_orchestrator/domain/mixins/__init__.py,sha256=enWzXVKf7BP-sHCuqaOL0zPcmW2CSbKeNUblzECQTx0,105
|
|
14
|
+
saga_orchestrator/domain/mixins/saga_state.py,sha256=AhsA2eRZtAHx16xLNVZp0SXrHIiS--S2U2NAyV6VsrM,1941
|
|
15
|
+
saga_orchestrator/domain/models/__init__.py,sha256=7GGAP7GiC86L1JxyLgyiM7Op3UGLYuKAVbid4HsAerw,525
|
|
16
|
+
saga_orchestrator/domain/models/builder.py,sha256=vUzTTlI-wojTQJh6L2s-r6RyuHuixKYciwM2RieyRqg,262
|
|
17
|
+
saga_orchestrator/domain/models/retry.py,sha256=UM2ZrSGKDZRiPMj0qOGp36xiTr78CVKsceXFFxtiOug,1362
|
|
18
|
+
saga_orchestrator/domain/models/saga_snapshot.py,sha256=4tmgwY1ezAG4Mh6vEVMGAx7f4NbIL71rWIK7dMZjifg,794
|
|
19
|
+
saga_orchestrator/domain/models/step.py,sha256=dRHbvegKGiqRcBY6TpqTnmsTzQArewvZrpedfcGuswU,2752
|
|
20
|
+
saga_orchestrator/domain/models/enums/__init__.py,sha256=tdTz69vzPJDX06TJA03gm2Zk0M96rXGEbY21IPQzJOM,103
|
|
21
|
+
saga_orchestrator/domain/models/enums/saga_status.py,sha256=aSp6mdzaZALxxp1p-NgPD2b8bg2dhEf016iDdjp_Vzw,292
|
|
22
|
+
python_saga_orchestrator-0.1.0.dist-info/METADATA,sha256=1imgMFBbeb1zlxu3CWiOgCK_suEOOGSGHcUQMcsfcHQ,8449
|
|
23
|
+
python_saga_orchestrator-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
24
|
+
python_saga_orchestrator-0.1.0.dist-info/top_level.txt,sha256=XBp_2J8dacJGCoVxIDaUYhSEuOusCN3BD_uhEjBEEBA,18
|
|
25
|
+
python_saga_orchestrator-0.1.0.dist-info/RECORD,,
|
|
@@ -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 @@
|
|
|
1
|
+
saga_orchestrator
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Public package API for the saga orchestrator library."""
|
|
2
|
+
|
|
3
|
+
from .admin import SagaAdmin
|
|
4
|
+
from .core import SagaBuilder, SagaEngine, SagaOrchestrator, SagaRepository
|
|
5
|
+
from .domain.exceptions import (
|
|
6
|
+
ActiveSagaAlreadyExistsError,
|
|
7
|
+
SagaDefinitionError,
|
|
8
|
+
SagaNotFoundError,
|
|
9
|
+
SagaStateError,
|
|
10
|
+
TypeValidationError,
|
|
11
|
+
)
|
|
12
|
+
from .domain.mixins import SagaStateMixin
|
|
13
|
+
from .domain.models import (
|
|
14
|
+
BaseStep,
|
|
15
|
+
ExponentialRetry,
|
|
16
|
+
FixedRetry,
|
|
17
|
+
InputContext,
|
|
18
|
+
NoRetry,
|
|
19
|
+
RetryPolicy,
|
|
20
|
+
SagaAdminSnapshot,
|
|
21
|
+
SagaDefinition,
|
|
22
|
+
SagaSnapshot,
|
|
23
|
+
StepDefinition,
|
|
24
|
+
StepInputMap,
|
|
25
|
+
StepRef,
|
|
26
|
+
)
|
|
27
|
+
from .domain.models.enums import SagaStatus
|
|
28
|
+
|
|
29
|
+
__version__ = "0.1.0"
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"ActiveSagaAlreadyExistsError",
|
|
33
|
+
"BaseStep",
|
|
34
|
+
"ExponentialRetry",
|
|
35
|
+
"FixedRetry",
|
|
36
|
+
"InputContext",
|
|
37
|
+
"NoRetry",
|
|
38
|
+
"RetryPolicy",
|
|
39
|
+
"SagaAdmin",
|
|
40
|
+
"SagaAdminSnapshot",
|
|
41
|
+
"SagaBuilder",
|
|
42
|
+
"SagaDefinition",
|
|
43
|
+
"SagaDefinitionError",
|
|
44
|
+
"SagaEngine",
|
|
45
|
+
"SagaNotFoundError",
|
|
46
|
+
"SagaOrchestrator",
|
|
47
|
+
"SagaRepository",
|
|
48
|
+
"SagaSnapshot",
|
|
49
|
+
"SagaStateError",
|
|
50
|
+
"SagaStateMixin",
|
|
51
|
+
"SagaStatus",
|
|
52
|
+
"StepDefinition",
|
|
53
|
+
"StepInputMap",
|
|
54
|
+
"StepRef",
|
|
55
|
+
"TypeValidationError",
|
|
56
|
+
"__version__",
|
|
57
|
+
]
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, Generic, TypeVar
|
|
4
|
+
from uuid import UUID
|
|
5
|
+
|
|
6
|
+
from pydantic import BaseModel
|
|
7
|
+
|
|
8
|
+
from ..core.engine import SagaEngine
|
|
9
|
+
from ..domain.mixins import SagaStateMixin
|
|
10
|
+
from ..domain.models import SagaAdminSnapshot
|
|
11
|
+
|
|
12
|
+
ModelT = TypeVar("ModelT", bound=SagaStateMixin)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class SagaAdmin(Generic[ModelT]):
|
|
16
|
+
"""Provide administrative operations for persisted saga instances."""
|
|
17
|
+
|
|
18
|
+
def __init__(
|
|
19
|
+
self,
|
|
20
|
+
engine: SagaEngine[ModelT],
|
|
21
|
+
) -> None:
|
|
22
|
+
"""Initialize the admin API facade."""
|
|
23
|
+
self._engine = engine
|
|
24
|
+
|
|
25
|
+
async def get_saga(self, saga_id: UUID) -> SagaAdminSnapshot:
|
|
26
|
+
"""Return the current persisted state of one saga."""
|
|
27
|
+
return await self._engine.get_admin_snapshot(saga_id)
|
|
28
|
+
|
|
29
|
+
async def retry_step(self, saga_id: UUID) -> None:
|
|
30
|
+
"""Retry the current failed step of a saga."""
|
|
31
|
+
await self._engine.retry_step(saga_id)
|
|
32
|
+
|
|
33
|
+
async def skip_step(
|
|
34
|
+
self,
|
|
35
|
+
saga_id: UUID,
|
|
36
|
+
mock_output: BaseModel | dict[str, Any] | None = None,
|
|
37
|
+
) -> None:
|
|
38
|
+
"""Skip the current suspended step using a provided output value."""
|
|
39
|
+
await self._engine.skip_step(saga_id, mock_output)
|
|
40
|
+
|
|
41
|
+
async def compensate_step(self, saga_id: UUID) -> None:
|
|
42
|
+
"""Start or resume compensation for one saga."""
|
|
43
|
+
await self._engine.compensate_step(saga_id)
|
|
44
|
+
|
|
45
|
+
async def abort(self, saga_id: UUID) -> None:
|
|
46
|
+
"""Mark a saga as failed and invalidate its current execution token."""
|
|
47
|
+
await self._engine.abort(saga_id)
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Core module."""
|
|
2
|
+
|
|
3
|
+
from .builder import SagaBuilder
|
|
4
|
+
from .engine import SagaEngine
|
|
5
|
+
from .orchestrator import SagaOrchestrator
|
|
6
|
+
from .repository import SagaRepository
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"SagaBuilder",
|
|
10
|
+
"SagaEngine",
|
|
11
|
+
"SagaOrchestrator",
|
|
12
|
+
"SagaRepository",
|
|
13
|
+
]
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import inspect
|
|
4
|
+
from datetime import timedelta
|
|
5
|
+
from typing import Any, Callable, get_type_hints
|
|
6
|
+
|
|
7
|
+
from pydantic import BaseModel
|
|
8
|
+
|
|
9
|
+
from ..domain.exceptions import SagaDefinitionError, TypeValidationError
|
|
10
|
+
from ..domain.models import (
|
|
11
|
+
BaseStep,
|
|
12
|
+
InputContext,
|
|
13
|
+
NoRetry,
|
|
14
|
+
RetryPolicy,
|
|
15
|
+
SagaDefinition,
|
|
16
|
+
StepDefinition,
|
|
17
|
+
StepInputMap,
|
|
18
|
+
StepRef,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class SagaBuilder:
|
|
23
|
+
"""Build a saga definition from ordered step definitions."""
|
|
24
|
+
|
|
25
|
+
def __init__(self, *, compensate_on_failure: bool = True) -> None:
|
|
26
|
+
"""Initialize the builder configuration."""
|
|
27
|
+
self._steps: list[StepDefinition[Any, Any]] = []
|
|
28
|
+
self._compensate_on_failure = compensate_on_failure
|
|
29
|
+
|
|
30
|
+
def add_step(
|
|
31
|
+
self,
|
|
32
|
+
*,
|
|
33
|
+
step: BaseStep[Any, Any],
|
|
34
|
+
input_map: StepInputMap[Any],
|
|
35
|
+
timeout: timedelta | None = None,
|
|
36
|
+
retry_policy: RetryPolicy | None = None,
|
|
37
|
+
depends_on: StepRef[Any] | None = None,
|
|
38
|
+
step_id: str | None = None,
|
|
39
|
+
) -> StepRef[Any]:
|
|
40
|
+
"""Add one step definition and return a reference to its output."""
|
|
41
|
+
if not callable(input_map):
|
|
42
|
+
raise SagaDefinitionError("input_map must be callable")
|
|
43
|
+
self.validate_input_map_types(input_map, step.input_model, depends_on)
|
|
44
|
+
|
|
45
|
+
normalized_step_id = step_id or f"step_{len(self._steps)}"
|
|
46
|
+
if any(existing.step_id == normalized_step_id for existing in self._steps):
|
|
47
|
+
raise SagaDefinitionError(f"Duplicate step id: {normalized_step_id}")
|
|
48
|
+
|
|
49
|
+
definition = StepDefinition(
|
|
50
|
+
step_id=normalized_step_id,
|
|
51
|
+
step=step,
|
|
52
|
+
input_map=input_map,
|
|
53
|
+
timeout=timeout,
|
|
54
|
+
retry_policy=retry_policy or NoRetry(),
|
|
55
|
+
depends_on=depends_on,
|
|
56
|
+
)
|
|
57
|
+
self._steps.append(definition)
|
|
58
|
+
return StepRef(step_id=normalized_step_id, output_model=step.output_model)
|
|
59
|
+
|
|
60
|
+
def build(self) -> SagaDefinition:
|
|
61
|
+
"""Return the final saga definition."""
|
|
62
|
+
if not self._steps:
|
|
63
|
+
raise SagaDefinitionError("Saga must contain at least one step")
|
|
64
|
+
return SagaDefinition(
|
|
65
|
+
steps=tuple(self._steps),
|
|
66
|
+
compensate_on_failure=self._compensate_on_failure,
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
@staticmethod
|
|
70
|
+
def validate_input_map_types(
|
|
71
|
+
input_map: Callable[[Any], Any],
|
|
72
|
+
expected_input_model: type[BaseModel],
|
|
73
|
+
depends_on: StepRef[Any] | None,
|
|
74
|
+
) -> None:
|
|
75
|
+
"""Validate the input and return type annotations of ``input_map``."""
|
|
76
|
+
hints = get_type_hints(input_map)
|
|
77
|
+
params = list(inspect.signature(input_map).parameters.values())
|
|
78
|
+
|
|
79
|
+
if depends_on is not None and params:
|
|
80
|
+
dep_param_name = params[0].name
|
|
81
|
+
dep_type = hints.get(dep_param_name)
|
|
82
|
+
if dep_type is not None and dep_type is not depends_on.output_model:
|
|
83
|
+
raise TypeValidationError(
|
|
84
|
+
"input_map first arg is "
|
|
85
|
+
f"'{dep_type}', expected '{depends_on.output_model.__name__}'"
|
|
86
|
+
)
|
|
87
|
+
elif depends_on is None and params:
|
|
88
|
+
context_param_name = params[0].name
|
|
89
|
+
context_type = hints.get(context_param_name)
|
|
90
|
+
if context_type is not None and context_type is not InputContext:
|
|
91
|
+
raise TypeValidationError(
|
|
92
|
+
"input_map first arg is "
|
|
93
|
+
f"'{context_type}', expected '{InputContext.__name__}'"
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
return_type = hints.get("return")
|
|
97
|
+
if return_type is None:
|
|
98
|
+
return
|
|
99
|
+
if return_type is expected_input_model:
|
|
100
|
+
return
|
|
101
|
+
if return_type is dict or return_type is dict[str, Any]:
|
|
102
|
+
return
|
|
103
|
+
raise TypeValidationError(
|
|
104
|
+
"input_map return type "
|
|
105
|
+
f"'{return_type}' is incompatible with '{expected_input_model.__name__}'"
|
|
106
|
+
)
|