simple-saga 0.0.1__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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Tetsuya Wakita
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,315 @@
1
+ Metadata-Version: 2.4
2
+ Name: simple-saga
3
+ Version: 0.0.1
4
+ Summary: A lightweight implementation of the Saga pattern for managing distributed transactions in Python
5
+ License: MIT
6
+ License-File: LICENSE
7
+ Keywords: saga,distributed-transactions,microservices,transaction-management
8
+ Author: Tetsuya Wakita
9
+ Author-email: wakita181009@gmail.com
10
+ Requires-Python: >=3.10,<4.0
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
+ Classifier: Typing :: Typed
22
+ Description-Content-Type: text/markdown
23
+
24
+ # Simple Saga
25
+
26
+ A lightweight implementation of the Saga pattern for managing distributed transactions in Python.
27
+
28
+ ## Overview
29
+
30
+ The Saga pattern breaks down distributed transactions into a series of local transactions, each with a compensating transaction that can undo the changes if a later step fails. This library provides a simple, type-safe implementation with support for both synchronous and asynchronous operations.
31
+
32
+ ## Features
33
+
34
+ - ✅ **Simple API** - Easy to use with a fluent interface
35
+ - 🔄 **Automatic Compensation** - Failed transactions are automatically rolled back
36
+ - ⚡ **Sync & Async Support** - Works with both synchronous and asynchronous functions
37
+ - 🔒 **Type Safe** - Full type hints with mypy support
38
+ - ðŸŠķ **Lightweight** - Zero dependencies (uses only Python standard library)
39
+ - 📚 **Well Documented** - Comprehensive docstrings and examples
40
+
41
+ ## Installation
42
+
43
+ ```bash
44
+ pip install simple-saga
45
+ ```
46
+
47
+ Or with Poetry:
48
+
49
+ ```bash
50
+ poetry add simple-saga
51
+ ```
52
+
53
+ ## Quick Start
54
+
55
+ ```python
56
+ import asyncio
57
+ from simple_saga import SimpleSaga
58
+
59
+ # Define your actions
60
+ def create_order(order_id: str) -> dict:
61
+ print(f"Creating order: {order_id}")
62
+ return {"order_id": order_id, "status": "created"}
63
+
64
+ def cancel_order(order_result: dict) -> None:
65
+ print(f"Cancelling order: {order_result['order_id']}")
66
+
67
+ async def reserve_inventory(product_id: str) -> dict:
68
+ print(f"Reserving inventory for: {product_id}")
69
+ return {"product_id": product_id, "reserved": True}
70
+
71
+ async def release_inventory(inventory_result: dict) -> None:
72
+ print(f"Releasing inventory for: {inventory_result['product_id']}")
73
+
74
+ def charge_payment(amount: float) -> dict:
75
+ print(f"Charging payment: ${amount}")
76
+ # Simulating a payment failure
77
+ raise Exception("Payment failed")
78
+
79
+ def refund_payment(payment_result: dict) -> None:
80
+ print("Refunding payment")
81
+
82
+ # Create and execute saga
83
+ async def main():
84
+ saga = SimpleSaga()
85
+
86
+ # Add steps with actions and compensations
87
+ saga.add_step(
88
+ action=create_order,
89
+ compensation=cancel_order,
90
+ action_args=("ORDER-123",)
91
+ )
92
+
93
+ saga.add_step(
94
+ action=reserve_inventory,
95
+ compensation=release_inventory,
96
+ action_args=("PRODUCT-456",)
97
+ )
98
+
99
+ saga.add_step(
100
+ action=charge_payment,
101
+ compensation=refund_payment,
102
+ action_args=(99.99,)
103
+ )
104
+
105
+ try:
106
+ results = await saga.execute()
107
+ print("✅ Saga completed successfully!")
108
+ for result in results:
109
+ print(f" Step {result.step_index + 1}: {result.result}")
110
+ except Exception as e:
111
+ print(f"❌ Saga failed: {e}")
112
+ print("All completed steps have been compensated.")
113
+
114
+ if __name__ == "__main__":
115
+ asyncio.run(main())
116
+ ```
117
+
118
+ ### Output
119
+
120
+ ```
121
+ Creating order: ORDER-123
122
+ ✓ Step 1 completed: create_order
123
+ Reserving inventory for: PRODUCT-456
124
+ ✓ Step 2 completed: reserve_inventory
125
+ Charging payment: $99.99
126
+ ✗ Error at step 3: Payment failed
127
+ 🔄 Starting compensation...
128
+ Releasing inventory for: PRODUCT-456
129
+ ✓ Compensated step 2: release_inventory
130
+ Cancelling order: ORDER-123
131
+ ✓ Compensated step 1: cancel_order
132
+ ❌ Saga failed: Payment failed
133
+ All completed steps have been compensated.
134
+ ```
135
+
136
+ ## Advanced Usage
137
+
138
+ ### Passing Multiple Arguments
139
+
140
+ ```python
141
+ saga.add_step(
142
+ action=create_user,
143
+ compensation=delete_user,
144
+ action_args=("john_doe",),
145
+ action_kwargs={"email": "john@example.com", "age": 30}
146
+ )
147
+ ```
148
+
149
+ ### Custom Compensation Arguments
150
+
151
+ By default, the action's result is passed to the compensation function. You can override this:
152
+
153
+ ```python
154
+ saga.add_step(
155
+ action=allocate_resource,
156
+ compensation=deallocate_resource,
157
+ action_args=("resource-id",),
158
+ compensation_args=("resource-id",),
159
+ compensation_kwargs={"force": True}
160
+ )
161
+ ```
162
+
163
+ ### Method Chaining
164
+
165
+ ```python
166
+ saga = (
167
+ SimpleSaga()
168
+ .add_step(action=step1, compensation=undo_step1)
169
+ .add_step(action=step2, compensation=undo_step2)
170
+ .add_step(action=step3, compensation=undo_step3)
171
+ )
172
+
173
+ results = await saga.execute()
174
+ ```
175
+
176
+ ### Reusing Saga Definitions
177
+
178
+ ```python
179
+ saga = SimpleSaga()
180
+ saga.add_step(action=step1, compensation=undo_step1)
181
+ saga.add_step(action=step2, compensation=undo_step2)
182
+
183
+ # Execute multiple times
184
+ await saga.execute() # First execution
185
+ await saga.execute() # Second execution (automatically resets)
186
+ ```
187
+
188
+ ### Logging Control
189
+
190
+ The library uses Python's standard `logging` module:
191
+
192
+ ```python
193
+ import logging
194
+
195
+ # Configure logging
196
+ logging.basicConfig(level=logging.INFO)
197
+
198
+ # Or disable saga logs
199
+ logging.getLogger("simple_saga").setLevel(logging.WARNING)
200
+ ```
201
+
202
+ ## API Reference
203
+
204
+ ### `SimpleSaga`
205
+
206
+ Main class for defining and executing sagas.
207
+
208
+ #### `add_step(action, compensation, *, action_args=(), action_kwargs=None, compensation_args=(), compensation_kwargs=None)`
209
+
210
+ Add a step to the saga.
211
+
212
+ **Parameters:**
213
+ - `action`: Function to execute (can be sync or async)
214
+ - `compensation`: Function to compensate if this or later steps fail (can be sync or async)
215
+ - `action_args`: Positional arguments for the action
216
+ - `action_kwargs`: Keyword arguments for the action
217
+ - `compensation_args`: Positional arguments for the compensation
218
+ - `compensation_kwargs`: Keyword arguments for the compensation
219
+
220
+ **Returns:** Self (for method chaining)
221
+
222
+ #### `async execute() -> list[StepResult]`
223
+
224
+ Execute all steps in the saga. If any step fails, automatically runs compensation for all previously executed steps in reverse order.
225
+
226
+ **Returns:** List of `StepResult` objects
227
+
228
+ **Raises:** Re-raises the exception that caused the saga to fail
229
+
230
+ #### `reset() -> None`
231
+
232
+ Reset the saga state, clearing all executed steps. Called automatically by `execute()`.
233
+
234
+ ### `StepResult`
235
+
236
+ Dataclass containing the result of a saga step execution.
237
+
238
+ **Attributes:**
239
+ - `step_index`: int - The index of the step
240
+ - `step_name`: str - The name of the action function
241
+ - `result`: Any - The result returned by the action
242
+
243
+ ### `SagaStep`
244
+
245
+ Dataclass representing a single step in the saga with action and compensation.
246
+
247
+ **Attributes:**
248
+ - `action`: Callable - The action function
249
+ - `compensation`: Callable - The compensation function
250
+ - `action_args`: tuple - Positional arguments for the action
251
+ - `action_kwargs`: dict - Keyword arguments for the action
252
+ - `compensation_args`: tuple - Positional arguments for the compensation
253
+ - `compensation_kwargs`: dict - Keyword arguments for the compensation
254
+
255
+ ## Design Decisions
256
+
257
+ ### Why async execute()?
258
+
259
+ Even though the library supports synchronous functions, `execute()` is async to handle mixed sync/async steps uniformly. This allows you to:
260
+ - Mix sync and async functions in the same saga
261
+ - Use async patterns for I/O-bound operations
262
+ - Keep the API simple and consistent
263
+
264
+ ### Compensation Behavior
265
+
266
+ - Compensations run in **reverse order** (LIFO)
267
+ - Compensation failures are **logged but don't stop the chain**
268
+ - Each compensation receives the action's result by default
269
+ - You can override compensation arguments if needed
270
+
271
+ ## Development
272
+
273
+ ### Setup
274
+
275
+ ```bash
276
+ # Clone the repository
277
+ git clone https://github.com/yourusername/simple-saga.git
278
+ cd simple-saga
279
+
280
+ # Install dependencies
281
+ poetry install
282
+
283
+ # Run type checking
284
+ poetry run mypy simple_saga
285
+
286
+ # Run linting
287
+ poetry run ruff check simple_saga
288
+ ```
289
+
290
+ ### Project Structure
291
+
292
+ ```
293
+ simple-saga/
294
+ ├── simple_saga/
295
+ │ ├── __init__.py # Package exports
296
+ │ ├── saga.py # Main SimpleSaga implementation
297
+ │ └── schema.py # Data classes (StepResult, SagaStep)
298
+ ├── pyproject.toml # Project configuration
299
+ ├── README.md # This file
300
+ └── CLAUDE.md # Development guide
301
+ ```
302
+
303
+ ## License
304
+
305
+ MIT License - see LICENSE file for details
306
+
307
+ ## Contributing
308
+
309
+ Contributions are welcome! Please feel free to submit a Pull Request.
310
+
311
+ ## Acknowledgments
312
+
313
+ This library implements the Saga pattern as described in:
314
+ - ["Sagas" by Hector Garcia-Molina and Kenneth Salem (1987)](https://www.cs.cornell.edu/andru/cs711/2002fa/reading/sagas.pdf)
315
+ - [Microservices Patterns by Chris Richardson](https://microservices.io/patterns/data/saga.html)
@@ -0,0 +1,292 @@
1
+ # Simple Saga
2
+
3
+ A lightweight implementation of the Saga pattern for managing distributed transactions in Python.
4
+
5
+ ## Overview
6
+
7
+ The Saga pattern breaks down distributed transactions into a series of local transactions, each with a compensating transaction that can undo the changes if a later step fails. This library provides a simple, type-safe implementation with support for both synchronous and asynchronous operations.
8
+
9
+ ## Features
10
+
11
+ - ✅ **Simple API** - Easy to use with a fluent interface
12
+ - 🔄 **Automatic Compensation** - Failed transactions are automatically rolled back
13
+ - ⚡ **Sync & Async Support** - Works with both synchronous and asynchronous functions
14
+ - 🔒 **Type Safe** - Full type hints with mypy support
15
+ - ðŸŠķ **Lightweight** - Zero dependencies (uses only Python standard library)
16
+ - 📚 **Well Documented** - Comprehensive docstrings and examples
17
+
18
+ ## Installation
19
+
20
+ ```bash
21
+ pip install simple-saga
22
+ ```
23
+
24
+ Or with Poetry:
25
+
26
+ ```bash
27
+ poetry add simple-saga
28
+ ```
29
+
30
+ ## Quick Start
31
+
32
+ ```python
33
+ import asyncio
34
+ from simple_saga import SimpleSaga
35
+
36
+ # Define your actions
37
+ def create_order(order_id: str) -> dict:
38
+ print(f"Creating order: {order_id}")
39
+ return {"order_id": order_id, "status": "created"}
40
+
41
+ def cancel_order(order_result: dict) -> None:
42
+ print(f"Cancelling order: {order_result['order_id']}")
43
+
44
+ async def reserve_inventory(product_id: str) -> dict:
45
+ print(f"Reserving inventory for: {product_id}")
46
+ return {"product_id": product_id, "reserved": True}
47
+
48
+ async def release_inventory(inventory_result: dict) -> None:
49
+ print(f"Releasing inventory for: {inventory_result['product_id']}")
50
+
51
+ def charge_payment(amount: float) -> dict:
52
+ print(f"Charging payment: ${amount}")
53
+ # Simulating a payment failure
54
+ raise Exception("Payment failed")
55
+
56
+ def refund_payment(payment_result: dict) -> None:
57
+ print("Refunding payment")
58
+
59
+ # Create and execute saga
60
+ async def main():
61
+ saga = SimpleSaga()
62
+
63
+ # Add steps with actions and compensations
64
+ saga.add_step(
65
+ action=create_order,
66
+ compensation=cancel_order,
67
+ action_args=("ORDER-123",)
68
+ )
69
+
70
+ saga.add_step(
71
+ action=reserve_inventory,
72
+ compensation=release_inventory,
73
+ action_args=("PRODUCT-456",)
74
+ )
75
+
76
+ saga.add_step(
77
+ action=charge_payment,
78
+ compensation=refund_payment,
79
+ action_args=(99.99,)
80
+ )
81
+
82
+ try:
83
+ results = await saga.execute()
84
+ print("✅ Saga completed successfully!")
85
+ for result in results:
86
+ print(f" Step {result.step_index + 1}: {result.result}")
87
+ except Exception as e:
88
+ print(f"❌ Saga failed: {e}")
89
+ print("All completed steps have been compensated.")
90
+
91
+ if __name__ == "__main__":
92
+ asyncio.run(main())
93
+ ```
94
+
95
+ ### Output
96
+
97
+ ```
98
+ Creating order: ORDER-123
99
+ ✓ Step 1 completed: create_order
100
+ Reserving inventory for: PRODUCT-456
101
+ ✓ Step 2 completed: reserve_inventory
102
+ Charging payment: $99.99
103
+ ✗ Error at step 3: Payment failed
104
+ 🔄 Starting compensation...
105
+ Releasing inventory for: PRODUCT-456
106
+ ✓ Compensated step 2: release_inventory
107
+ Cancelling order: ORDER-123
108
+ ✓ Compensated step 1: cancel_order
109
+ ❌ Saga failed: Payment failed
110
+ All completed steps have been compensated.
111
+ ```
112
+
113
+ ## Advanced Usage
114
+
115
+ ### Passing Multiple Arguments
116
+
117
+ ```python
118
+ saga.add_step(
119
+ action=create_user,
120
+ compensation=delete_user,
121
+ action_args=("john_doe",),
122
+ action_kwargs={"email": "john@example.com", "age": 30}
123
+ )
124
+ ```
125
+
126
+ ### Custom Compensation Arguments
127
+
128
+ By default, the action's result is passed to the compensation function. You can override this:
129
+
130
+ ```python
131
+ saga.add_step(
132
+ action=allocate_resource,
133
+ compensation=deallocate_resource,
134
+ action_args=("resource-id",),
135
+ compensation_args=("resource-id",),
136
+ compensation_kwargs={"force": True}
137
+ )
138
+ ```
139
+
140
+ ### Method Chaining
141
+
142
+ ```python
143
+ saga = (
144
+ SimpleSaga()
145
+ .add_step(action=step1, compensation=undo_step1)
146
+ .add_step(action=step2, compensation=undo_step2)
147
+ .add_step(action=step3, compensation=undo_step3)
148
+ )
149
+
150
+ results = await saga.execute()
151
+ ```
152
+
153
+ ### Reusing Saga Definitions
154
+
155
+ ```python
156
+ saga = SimpleSaga()
157
+ saga.add_step(action=step1, compensation=undo_step1)
158
+ saga.add_step(action=step2, compensation=undo_step2)
159
+
160
+ # Execute multiple times
161
+ await saga.execute() # First execution
162
+ await saga.execute() # Second execution (automatically resets)
163
+ ```
164
+
165
+ ### Logging Control
166
+
167
+ The library uses Python's standard `logging` module:
168
+
169
+ ```python
170
+ import logging
171
+
172
+ # Configure logging
173
+ logging.basicConfig(level=logging.INFO)
174
+
175
+ # Or disable saga logs
176
+ logging.getLogger("simple_saga").setLevel(logging.WARNING)
177
+ ```
178
+
179
+ ## API Reference
180
+
181
+ ### `SimpleSaga`
182
+
183
+ Main class for defining and executing sagas.
184
+
185
+ #### `add_step(action, compensation, *, action_args=(), action_kwargs=None, compensation_args=(), compensation_kwargs=None)`
186
+
187
+ Add a step to the saga.
188
+
189
+ **Parameters:**
190
+ - `action`: Function to execute (can be sync or async)
191
+ - `compensation`: Function to compensate if this or later steps fail (can be sync or async)
192
+ - `action_args`: Positional arguments for the action
193
+ - `action_kwargs`: Keyword arguments for the action
194
+ - `compensation_args`: Positional arguments for the compensation
195
+ - `compensation_kwargs`: Keyword arguments for the compensation
196
+
197
+ **Returns:** Self (for method chaining)
198
+
199
+ #### `async execute() -> list[StepResult]`
200
+
201
+ Execute all steps in the saga. If any step fails, automatically runs compensation for all previously executed steps in reverse order.
202
+
203
+ **Returns:** List of `StepResult` objects
204
+
205
+ **Raises:** Re-raises the exception that caused the saga to fail
206
+
207
+ #### `reset() -> None`
208
+
209
+ Reset the saga state, clearing all executed steps. Called automatically by `execute()`.
210
+
211
+ ### `StepResult`
212
+
213
+ Dataclass containing the result of a saga step execution.
214
+
215
+ **Attributes:**
216
+ - `step_index`: int - The index of the step
217
+ - `step_name`: str - The name of the action function
218
+ - `result`: Any - The result returned by the action
219
+
220
+ ### `SagaStep`
221
+
222
+ Dataclass representing a single step in the saga with action and compensation.
223
+
224
+ **Attributes:**
225
+ - `action`: Callable - The action function
226
+ - `compensation`: Callable - The compensation function
227
+ - `action_args`: tuple - Positional arguments for the action
228
+ - `action_kwargs`: dict - Keyword arguments for the action
229
+ - `compensation_args`: tuple - Positional arguments for the compensation
230
+ - `compensation_kwargs`: dict - Keyword arguments for the compensation
231
+
232
+ ## Design Decisions
233
+
234
+ ### Why async execute()?
235
+
236
+ Even though the library supports synchronous functions, `execute()` is async to handle mixed sync/async steps uniformly. This allows you to:
237
+ - Mix sync and async functions in the same saga
238
+ - Use async patterns for I/O-bound operations
239
+ - Keep the API simple and consistent
240
+
241
+ ### Compensation Behavior
242
+
243
+ - Compensations run in **reverse order** (LIFO)
244
+ - Compensation failures are **logged but don't stop the chain**
245
+ - Each compensation receives the action's result by default
246
+ - You can override compensation arguments if needed
247
+
248
+ ## Development
249
+
250
+ ### Setup
251
+
252
+ ```bash
253
+ # Clone the repository
254
+ git clone https://github.com/yourusername/simple-saga.git
255
+ cd simple-saga
256
+
257
+ # Install dependencies
258
+ poetry install
259
+
260
+ # Run type checking
261
+ poetry run mypy simple_saga
262
+
263
+ # Run linting
264
+ poetry run ruff check simple_saga
265
+ ```
266
+
267
+ ### Project Structure
268
+
269
+ ```
270
+ simple-saga/
271
+ ├── simple_saga/
272
+ │ ├── __init__.py # Package exports
273
+ │ ├── saga.py # Main SimpleSaga implementation
274
+ │ └── schema.py # Data classes (StepResult, SagaStep)
275
+ ├── pyproject.toml # Project configuration
276
+ ├── README.md # This file
277
+ └── CLAUDE.md # Development guide
278
+ ```
279
+
280
+ ## License
281
+
282
+ MIT License - see LICENSE file for details
283
+
284
+ ## Contributing
285
+
286
+ Contributions are welcome! Please feel free to submit a Pull Request.
287
+
288
+ ## Acknowledgments
289
+
290
+ This library implements the Saga pattern as described in:
291
+ - ["Sagas" by Hector Garcia-Molina and Kenneth Salem (1987)](https://www.cs.cornell.edu/andru/cs711/2002fa/reading/sagas.pdf)
292
+ - [Microservices Patterns by Chris Richardson](https://microservices.io/patterns/data/saga.html)
@@ -0,0 +1,60 @@
1
+ [tool.poetry]
2
+ name = "simple-saga"
3
+ version = "0.0.1"
4
+ description = "A lightweight implementation of the Saga pattern for managing distributed transactions in Python"
5
+ authors = ["Tetsuya Wakita <wakita181009@gmail.com>"]
6
+ readme = "README.md"
7
+ license = "MIT"
8
+ keywords = ["saga", "distributed-transactions", "microservices", "transaction-management"]
9
+ classifiers = [
10
+ "Development Status :: 3 - Alpha",
11
+ "Intended Audience :: Developers",
12
+ "License :: OSI Approved :: MIT License",
13
+ "Programming Language :: Python :: 3",
14
+ "Programming Language :: Python :: 3.10",
15
+ "Programming Language :: Python :: 3.11",
16
+ "Programming Language :: Python :: 3.12",
17
+ "Programming Language :: Python :: 3.13",
18
+ "Programming Language :: Python :: 3.14",
19
+ "Topic :: Software Development :: Libraries :: Python Modules",
20
+ "Typing :: Typed",
21
+ ]
22
+ packages = [{ include = "simple_saga" }]
23
+
24
+ [tool.poetry.dependencies]
25
+ python = "^3.10"
26
+
27
+ [tool.poetry.group.dev.dependencies]
28
+ pytest = "^9.0.1"
29
+ pytest-asyncio = "^1.3.0"
30
+ mypy = "^1.5.0"
31
+ ruff = "^0.1.0"
32
+
33
+ [build-system]
34
+ requires = ["poetry-core"]
35
+ build-backend = "poetry.core.masonry.api"
36
+
37
+ [tool.mypy]
38
+ python_version = "3.10"
39
+ strict = true
40
+
41
+ [tool.ruff]
42
+ target-version = "py310"
43
+ line-length = 120
44
+ select = [
45
+ "E", # pycodestyle errors
46
+ "W", # pycodestyle warnings
47
+ "F", # pyflakes
48
+ "I", # isort
49
+ "B", # flake8-bugbear
50
+ "C4", # flake8-comprehensions
51
+ "UP", # pyupgrade
52
+ "ARG", # flake8-unused-arguments
53
+ ]
54
+ ignore = [
55
+ "ARG001",
56
+ "E501", # line too long (handled by black)
57
+ ]
58
+
59
+ [tool.ruff.per-file-ignores]
60
+ "__init__.py" = ["F401"]
@@ -0,0 +1,10 @@
1
+ """Simple Saga Pattern Library for Python.
2
+
3
+ A lightweight implementation of the Saga pattern for managing distributed transactions.
4
+ """
5
+
6
+ from .saga import SimpleSaga
7
+ from .schema import SagaStep, StepResult
8
+
9
+ __version__ = "0.0.1"
10
+ __all__ = ["SimpleSaga", "StepResult", "SagaStep"]
@@ -0,0 +1,159 @@
1
+ import asyncio
2
+ import logging
3
+ from collections.abc import Callable
4
+ from typing import Any
5
+
6
+ from .schema import SagaStep, StepResult
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ class SimpleSaga:
12
+ """
13
+ A simple implementation of the Saga pattern for managing distributed transactions.
14
+
15
+ The Saga pattern breaks down a distributed transaction into a series of local transactions,
16
+ each with a compensating transaction that can undo the changes if a later step fails.
17
+
18
+ Example:
19
+ saga = SimpleSaga()
20
+ saga.add_step(
21
+ action=create_order,
22
+ compensation=cancel_order,
23
+ action_args=(order_id,),
24
+ action_kwargs={'user_id': 123}
25
+ )
26
+ saga.add_step(
27
+ action=reserve_inventory,
28
+ compensation=release_inventory
29
+ )
30
+
31
+ results = await saga.execute()
32
+ """
33
+
34
+ def __init__(self) -> None:
35
+ """
36
+ Initialize a new SimpleSaga instance.
37
+ """
38
+ self.steps: list[SagaStep] = []
39
+ self.executed: list[StepResult] = []
40
+
41
+ def add_step(
42
+ self,
43
+ action: Callable[..., Any],
44
+ compensation: Callable[..., Any],
45
+ *,
46
+ action_args: tuple[Any, ...] = (),
47
+ action_kwargs: dict[str, Any] | None = None,
48
+ compensation_args: tuple[Any, ...] = (),
49
+ compensation_kwargs: dict[str, Any] | None = None,
50
+ ) -> "SimpleSaga":
51
+ """
52
+ Add a step to the saga.
53
+
54
+ Args:
55
+ action: The function to execute for this step (can be sync or async)
56
+ compensation: The function to compensate if this or later steps fail (can be sync or async)
57
+ action_args: Positional arguments to pass to the action
58
+ action_kwargs: Keyword arguments to pass to the action
59
+ compensation_args: Positional arguments to pass to the compensation
60
+ compensation_kwargs: Keyword arguments to pass to the compensation
61
+
62
+ Returns:
63
+ self: Returns the saga instance for method chaining
64
+ """
65
+ step = SagaStep(
66
+ action=action,
67
+ compensation=compensation,
68
+ action_args=action_args,
69
+ action_kwargs=action_kwargs or {},
70
+ compensation_args=compensation_args,
71
+ compensation_kwargs=compensation_kwargs or {},
72
+ )
73
+ self.steps.append(step)
74
+ return self
75
+
76
+ def reset(self) -> None:
77
+ """Reset the saga state, clearing all executed steps."""
78
+ self.executed.clear()
79
+
80
+ async def execute(self) -> list[StepResult]:
81
+ """
82
+ Execute all steps in the saga.
83
+
84
+ If any step fails, automatically runs compensation for all previously
85
+ executed steps in reverse order.
86
+
87
+ Returns:
88
+ list[StepResult]: List of results from each executed step
89
+
90
+ Raises:
91
+ Exception: Re-raises the exception that caused the saga to fail
92
+ """
93
+ self.reset()
94
+
95
+ try:
96
+ for idx, step in enumerate(self.steps):
97
+ logger.info(f"Executing step {idx + 1}/{len(self.steps)}: {step.action.__name__}")
98
+
99
+ # Execute the action (async or sync)
100
+ if asyncio.iscoroutinefunction(step.action):
101
+ result = await step.action(*step.action_args, **step.action_kwargs)
102
+ else:
103
+ result = step.action(*step.action_args, **step.action_kwargs)
104
+
105
+ # Record the successful execution
106
+ step_result = StepResult(
107
+ step_index=idx,
108
+ step_name=step.action.__name__,
109
+ result=result,
110
+ )
111
+ self.executed.append(step_result)
112
+
113
+ logger.info(f"✅ Step {idx + 1} completed: {step.action.__name__}")
114
+
115
+ return self.executed
116
+
117
+ except Exception as e:
118
+ logger.error(f"❌ Error at step {len(self.executed) + 1}: {e}")
119
+ await self.__compensate()
120
+ raise
121
+
122
+ async def __compensate(self) -> list[Exception]:
123
+ """
124
+ Run compensation for all executed steps in reverse order.
125
+
126
+ This is called automatically when a step fails during execution.
127
+ Compensation failures are logged but do not stop the compensation chain.
128
+ """
129
+ logger.info("🔄 Starting compensation...")
130
+
131
+ errors: list[Exception] = []
132
+ for step_result in reversed(self.executed):
133
+ step = self.steps[step_result.step_index]
134
+ try:
135
+ logger.info(f"Compensating step {step_result.step_index + 1}: {step.compensation.__name__}")
136
+
137
+ # Use compensation_args/kwargs if provided, otherwise use the action result
138
+ if step.compensation_args or step.compensation_kwargs:
139
+ comp_args = step.compensation_args
140
+ comp_kwargs = step.compensation_kwargs
141
+ else:
142
+ # Default: pass the action result as the first argument
143
+ comp_args = (step_result.result,)
144
+ comp_kwargs = {}
145
+
146
+ # Execute compensation (async or sync)
147
+ if asyncio.iscoroutinefunction(step.compensation):
148
+ await step.compensation(*comp_args, **comp_kwargs)
149
+ else:
150
+ step.compensation(*comp_args, **comp_kwargs)
151
+
152
+ logger.info(f"✅ Compensated step {step_result.step_index + 1}: {step.compensation.__name__}")
153
+ except Exception as e:
154
+ errors.append(e)
155
+ logger.exception(f"⚠ïļ Compensation failed for step {step_result.step_index + 1}")
156
+
157
+ if errors:
158
+ logger.warning(f"Compensation completed with {len(errors)} error(s)")
159
+ return errors
@@ -0,0 +1,24 @@
1
+ from collections.abc import Callable
2
+ from dataclasses import dataclass, field
3
+ from typing import Any
4
+
5
+
6
+ @dataclass(frozen=True)
7
+ class StepResult:
8
+ """Result of a saga step execution."""
9
+
10
+ step_index: int
11
+ step_name: str
12
+ result: Any
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class SagaStep:
17
+ """Represents a single step in the saga with action and compensation."""
18
+
19
+ action: Callable[..., Any]
20
+ compensation: Callable[..., Any]
21
+ action_args: tuple[Any, ...] = ()
22
+ action_kwargs: dict[str, Any] = field(default_factory=dict)
23
+ compensation_args: tuple[Any, ...] = ()
24
+ compensation_kwargs: dict[str, Any] = field(default_factory=dict)