simple-saga 0.0.1__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.
@@ -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"]
simple_saga/saga.py ADDED
@@ -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
simple_saga/schema.py ADDED
@@ -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)
@@ -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,7 @@
1
+ simple_saga/__init__.py,sha256=uQbuuhDakPQcB32ZKk1Rt2XiUeYp4W6NuyR7qS5lV0M,281
2
+ simple_saga/saga.py,sha256=YAz_L-1jQXmJmMERXBE9kXDRBpQsxDstKwQgqgRl1J8,5753
3
+ simple_saga/schema.py,sha256=V9AZ0XJXmuSv53SD9xAtmj0df7SnKCh3WPh02SL2DF8,648
4
+ simple_saga-0.0.1.dist-info/METADATA,sha256=6vBxDNxRXgjbQFV4z757T9luLpkfEaSgkmO2y66JEJo,9023
5
+ simple_saga-0.0.1.dist-info/WHEEL,sha256=zp0Cn7JsFoX2ATtOhtaFYIiE2rmFAD4OcMhtUki8W3U,88
6
+ simple_saga-0.0.1.dist-info/licenses/LICENSE,sha256=9JVuVShS6rMoWbgJ3DjooGiDG2MZIXfDHWveQkfkFzI,1071
7
+ simple_saga-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.2.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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.