taipanstack 0.3.0__tar.gz → 0.3.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.
- {taipanstack-0.3.0 → taipanstack-0.3.1}/PKG-INFO +44 -1
- {taipanstack-0.3.0 → taipanstack-0.3.1}/README.md +43 -0
- {taipanstack-0.3.0 → taipanstack-0.3.1}/pyproject.toml +1 -1
- {taipanstack-0.3.0 → taipanstack-0.3.1}/src/taipanstack/__init__.py +1 -1
- {taipanstack-0.3.0 → taipanstack-0.3.1}/src/taipanstack/core/result.py +37 -4
- {taipanstack-0.3.0 → taipanstack-0.3.1}/src/taipanstack/security/guards.py +21 -0
- {taipanstack-0.3.0 → taipanstack-0.3.1}/src/taipanstack/security/sanitizers.py +6 -0
- {taipanstack-0.3.0 → taipanstack-0.3.1}/src/taipanstack/security/validators.py +12 -0
- {taipanstack-0.3.0 → taipanstack-0.3.1}/src/taipanstack/utils/circuit_breaker.py +60 -4
- {taipanstack-0.3.0 → taipanstack-0.3.1}/src/taipanstack/utils/retry.py +19 -5
- {taipanstack-0.3.0 → taipanstack-0.3.1}/LICENSE +0 -0
- {taipanstack-0.3.0 → taipanstack-0.3.1}/src/taipanstack/config/__init__.py +0 -0
- {taipanstack-0.3.0 → taipanstack-0.3.1}/src/taipanstack/config/generators.py +0 -0
- {taipanstack-0.3.0 → taipanstack-0.3.1}/src/taipanstack/config/models.py +0 -0
- {taipanstack-0.3.0 → taipanstack-0.3.1}/src/taipanstack/config/version_config.py +0 -0
- {taipanstack-0.3.0 → taipanstack-0.3.1}/src/taipanstack/core/__init__.py +0 -0
- {taipanstack-0.3.0 → taipanstack-0.3.1}/src/taipanstack/core/compat.py +0 -0
- {taipanstack-0.3.0 → taipanstack-0.3.1}/src/taipanstack/core/optimizations.py +0 -0
- {taipanstack-0.3.0 → taipanstack-0.3.1}/src/taipanstack/security/__init__.py +0 -0
- {taipanstack-0.3.0 → taipanstack-0.3.1}/src/taipanstack/security/decorators.py +0 -0
- {taipanstack-0.3.0 → taipanstack-0.3.1}/src/taipanstack/utils/__init__.py +0 -0
- {taipanstack-0.3.0 → taipanstack-0.3.1}/src/taipanstack/utils/filesystem.py +0 -0
- {taipanstack-0.3.0 → taipanstack-0.3.1}/src/taipanstack/utils/logging.py +0 -0
- {taipanstack-0.3.0 → taipanstack-0.3.1}/src/taipanstack/utils/metrics.py +0 -0
- {taipanstack-0.3.0 → taipanstack-0.3.1}/src/taipanstack/utils/subprocess.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: taipanstack
|
|
3
|
-
Version: 0.3.
|
|
3
|
+
Version: 0.3.1
|
|
4
4
|
Summary: TaipanStack - Modular, secure, and scalable Python stack for robust development
|
|
5
5
|
License-Expression: MIT
|
|
6
6
|
License-File: LICENSE
|
|
@@ -295,6 +295,49 @@ def call_external_service() -> Response:
|
|
|
295
295
|
return service.call()
|
|
296
296
|
```
|
|
297
297
|
|
|
298
|
+
### 🔗 Combining Result + Circuit Breaker
|
|
299
|
+
|
|
300
|
+
```python
|
|
301
|
+
from taipanstack.core.result import safe, Ok, Err
|
|
302
|
+
from taipanstack.utils.circuit_breaker import CircuitBreaker
|
|
303
|
+
|
|
304
|
+
breaker = CircuitBreaker(failure_threshold=3, timeout=60, name="payments")
|
|
305
|
+
|
|
306
|
+
@breaker
|
|
307
|
+
@safe
|
|
308
|
+
def charge_customer(customer_id: str, amount: float) -> dict:
|
|
309
|
+
return payment_gateway.charge(customer_id, amount)
|
|
310
|
+
|
|
311
|
+
# Both circuit protection AND explicit error handling
|
|
312
|
+
result = charge_customer("cust_123", 49.99)
|
|
313
|
+
match result:
|
|
314
|
+
case Ok(receipt):
|
|
315
|
+
print(f"Payment successful: {receipt}")
|
|
316
|
+
case Err(error):
|
|
317
|
+
print(f"Payment failed safely: {error}")
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
### 🔗 Combining Result + Retry with Monitoring
|
|
321
|
+
|
|
322
|
+
```python
|
|
323
|
+
from taipanstack.core.result import safe, unwrap_or
|
|
324
|
+
from taipanstack.utils.retry import retry
|
|
325
|
+
|
|
326
|
+
@retry(
|
|
327
|
+
max_attempts=3,
|
|
328
|
+
on=(ConnectionError, TimeoutError),
|
|
329
|
+
on_retry=lambda attempt, max_a, exc, delay: print(
|
|
330
|
+
f"⚠️ Attempt {attempt}/{max_a} failed, retrying in {delay:.1f}s..."
|
|
331
|
+
),
|
|
332
|
+
)
|
|
333
|
+
@safe
|
|
334
|
+
def fetch_user_profile(user_id: str) -> dict:
|
|
335
|
+
return api_client.get(f"/users/{user_id}")
|
|
336
|
+
|
|
337
|
+
# Retry handles transient failures, Result handles business errors
|
|
338
|
+
profile = unwrap_or(fetch_user_profile("usr_456"), {"name": "Unknown"})
|
|
339
|
+
```
|
|
340
|
+
|
|
298
341
|
---
|
|
299
342
|
|
|
300
343
|
## 🐳 Docker
|
|
@@ -260,6 +260,49 @@ def call_external_service() -> Response:
|
|
|
260
260
|
return service.call()
|
|
261
261
|
```
|
|
262
262
|
|
|
263
|
+
### 🔗 Combining Result + Circuit Breaker
|
|
264
|
+
|
|
265
|
+
```python
|
|
266
|
+
from taipanstack.core.result import safe, Ok, Err
|
|
267
|
+
from taipanstack.utils.circuit_breaker import CircuitBreaker
|
|
268
|
+
|
|
269
|
+
breaker = CircuitBreaker(failure_threshold=3, timeout=60, name="payments")
|
|
270
|
+
|
|
271
|
+
@breaker
|
|
272
|
+
@safe
|
|
273
|
+
def charge_customer(customer_id: str, amount: float) -> dict:
|
|
274
|
+
return payment_gateway.charge(customer_id, amount)
|
|
275
|
+
|
|
276
|
+
# Both circuit protection AND explicit error handling
|
|
277
|
+
result = charge_customer("cust_123", 49.99)
|
|
278
|
+
match result:
|
|
279
|
+
case Ok(receipt):
|
|
280
|
+
print(f"Payment successful: {receipt}")
|
|
281
|
+
case Err(error):
|
|
282
|
+
print(f"Payment failed safely: {error}")
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
### 🔗 Combining Result + Retry with Monitoring
|
|
286
|
+
|
|
287
|
+
```python
|
|
288
|
+
from taipanstack.core.result import safe, unwrap_or
|
|
289
|
+
from taipanstack.utils.retry import retry
|
|
290
|
+
|
|
291
|
+
@retry(
|
|
292
|
+
max_attempts=3,
|
|
293
|
+
on=(ConnectionError, TimeoutError),
|
|
294
|
+
on_retry=lambda attempt, max_a, exc, delay: print(
|
|
295
|
+
f"⚠️ Attempt {attempt}/{max_a} failed, retrying in {delay:.1f}s..."
|
|
296
|
+
),
|
|
297
|
+
)
|
|
298
|
+
@safe
|
|
299
|
+
def fetch_user_profile(user_id: str) -> dict:
|
|
300
|
+
return api_client.get(f"/users/{user_id}")
|
|
301
|
+
|
|
302
|
+
# Retry handles transient failures, Result handles business errors
|
|
303
|
+
profile = unwrap_or(fetch_user_profile("usr_456"), {"name": "Unknown"})
|
|
304
|
+
```
|
|
305
|
+
|
|
263
306
|
---
|
|
264
307
|
|
|
265
308
|
## 🐳 Docker
|
|
@@ -5,7 +5,7 @@ A modular, secure, and scalable Python stack for robust development.
|
|
|
5
5
|
Supports Python 3.11+ with version-aware optimizations for 3.13/3.14.
|
|
6
6
|
"""
|
|
7
7
|
|
|
8
|
-
__version__ = "
|
|
8
|
+
__version__ = "0.3.1"
|
|
9
9
|
|
|
10
10
|
from taipanstack.config.models import StackConfig
|
|
11
11
|
from taipanstack.config.version_config import (
|
|
@@ -26,7 +26,7 @@ from __future__ import annotations
|
|
|
26
26
|
|
|
27
27
|
import functools
|
|
28
28
|
from collections.abc import Callable, Iterable
|
|
29
|
-
from typing import ParamSpec, TypeVar
|
|
29
|
+
from typing import ParamSpec, TypeVar, overload
|
|
30
30
|
|
|
31
31
|
from result import Err, Ok, Result
|
|
32
32
|
|
|
@@ -148,7 +148,19 @@ def collect_results(
|
|
|
148
148
|
return Ok(values)
|
|
149
149
|
|
|
150
150
|
|
|
151
|
-
|
|
151
|
+
@overload
|
|
152
|
+
def unwrap_or(result: Ok[T], default: U) -> T: ... # pragma: no cover
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
@overload
|
|
156
|
+
def unwrap_or(result: Err[E], default: U) -> U: ... # pragma: no cover
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
@overload
|
|
160
|
+
def unwrap_or(result: Result[T, E], default: U) -> T | U: ... # pragma: no cover
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def unwrap_or(result: Result[T, E], default: U) -> T | U:
|
|
152
164
|
"""Extract value from Result or return default.
|
|
153
165
|
|
|
154
166
|
Args:
|
|
@@ -172,10 +184,31 @@ def unwrap_or(result: Result[T, E], default: T) -> T:
|
|
|
172
184
|
return default
|
|
173
185
|
|
|
174
186
|
|
|
187
|
+
@overload
|
|
188
|
+
def unwrap_or_else(
|
|
189
|
+
result: Ok[T],
|
|
190
|
+
default_fn: Callable[[E], U],
|
|
191
|
+
) -> T: ... # pragma: no cover
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
@overload
|
|
195
|
+
def unwrap_or_else(
|
|
196
|
+
result: Err[E],
|
|
197
|
+
default_fn: Callable[[E], U],
|
|
198
|
+
) -> U: ... # pragma: no cover
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
@overload
|
|
202
|
+
def unwrap_or_else(
|
|
203
|
+
result: Result[T, E],
|
|
204
|
+
default_fn: Callable[[E], U],
|
|
205
|
+
) -> T | U: ... # pragma: no cover
|
|
206
|
+
|
|
207
|
+
|
|
175
208
|
def unwrap_or_else(
|
|
176
209
|
result: Result[T, E],
|
|
177
|
-
default_fn: Callable[[E],
|
|
178
|
-
) -> T:
|
|
210
|
+
default_fn: Callable[[E], U],
|
|
211
|
+
) -> T | U:
|
|
179
212
|
"""Extract value from Result or compute default from error.
|
|
180
213
|
|
|
181
214
|
Args:
|
|
@@ -70,6 +70,8 @@ def guard_path_traversal(
|
|
|
70
70
|
SecurityError: [path_traversal] Path escapes base directory
|
|
71
71
|
|
|
72
72
|
"""
|
|
73
|
+
if not isinstance(path, (str, Path)):
|
|
74
|
+
raise TypeError(f"path must be str or Path, got {type(path).__name__}")
|
|
73
75
|
path = Path(path) if isinstance(path, str) else path
|
|
74
76
|
base_dir = Path(base_dir).resolve() if base_dir else Path.cwd().resolve()
|
|
75
77
|
|
|
@@ -157,6 +159,14 @@ def guard_command_injection(
|
|
|
157
159
|
|
|
158
160
|
cmd_list = list(command)
|
|
159
161
|
|
|
162
|
+
# Validate all items are strings
|
|
163
|
+
for i, arg in enumerate(cmd_list):
|
|
164
|
+
if not isinstance(arg, str):
|
|
165
|
+
raise TypeError(
|
|
166
|
+
f"All command arguments must be strings, "
|
|
167
|
+
f"got {type(arg).__name__} at index {i}"
|
|
168
|
+
)
|
|
169
|
+
|
|
160
170
|
# Dangerous shell metacharacters
|
|
161
171
|
dangerous_patterns: list[tuple[str, str]] = [
|
|
162
172
|
(";", "command separator"),
|
|
@@ -309,6 +319,17 @@ def guard_env_variable(
|
|
|
309
319
|
"API_SECRET",
|
|
310
320
|
}
|
|
311
321
|
|
|
322
|
+
# Validate input type
|
|
323
|
+
if not isinstance(name, str):
|
|
324
|
+
raise TypeError(f"Variable name must be str, got {type(name).__name__}")
|
|
325
|
+
|
|
326
|
+
# Reject empty/whitespace-only variable names
|
|
327
|
+
if not name or not name.strip():
|
|
328
|
+
raise SecurityError(
|
|
329
|
+
"Environment variable name cannot be empty or whitespace",
|
|
330
|
+
guard_name="env_variable",
|
|
331
|
+
)
|
|
332
|
+
|
|
312
333
|
name_upper = name.upper()
|
|
313
334
|
|
|
314
335
|
if denied_names is not None:
|
|
@@ -69,6 +69,9 @@ def sanitize_string(
|
|
|
69
69
|
"scriptalert('xss')/scriptHello"
|
|
70
70
|
|
|
71
71
|
"""
|
|
72
|
+
if not isinstance(value, str):
|
|
73
|
+
raise TypeError(f"value must be str, got {type(value).__name__}")
|
|
74
|
+
|
|
72
75
|
if not value:
|
|
73
76
|
return ""
|
|
74
77
|
|
|
@@ -131,6 +134,9 @@ def sanitize_filename(
|
|
|
131
134
|
'my_file_name.txt'
|
|
132
135
|
|
|
133
136
|
"""
|
|
137
|
+
if not isinstance(filename, str):
|
|
138
|
+
raise TypeError(f"filename must be str, got {type(filename).__name__}")
|
|
139
|
+
|
|
134
140
|
if not filename:
|
|
135
141
|
return "unnamed"
|
|
136
142
|
|
|
@@ -50,6 +50,9 @@ def validate_project_name(
|
|
|
50
50
|
ValueError: Project name must start with a letter
|
|
51
51
|
|
|
52
52
|
"""
|
|
53
|
+
if not isinstance(name, str):
|
|
54
|
+
raise TypeError(f"Project name must be str, got {type(name).__name__}")
|
|
55
|
+
|
|
53
56
|
if not name:
|
|
54
57
|
msg = "Project name cannot be empty"
|
|
55
58
|
raise ValueError(msg)
|
|
@@ -117,6 +120,9 @@ def validate_python_version(version: str) -> str:
|
|
|
117
120
|
ValueError: If version format is invalid or unsupported.
|
|
118
121
|
|
|
119
122
|
"""
|
|
123
|
+
if not isinstance(version, str):
|
|
124
|
+
raise TypeError(f"Version must be str, got {type(version).__name__}")
|
|
125
|
+
|
|
120
126
|
pattern = r"^\d+\.\d+$"
|
|
121
127
|
|
|
122
128
|
if not re.match(pattern, version):
|
|
@@ -159,6 +165,9 @@ def validate_email(email: str) -> str:
|
|
|
159
165
|
ValueError: If email format is invalid.
|
|
160
166
|
|
|
161
167
|
"""
|
|
168
|
+
if not isinstance(email, str):
|
|
169
|
+
raise TypeError(f"Email must be str, got {type(email).__name__}")
|
|
170
|
+
|
|
162
171
|
if not email:
|
|
163
172
|
msg = "Email cannot be empty"
|
|
164
173
|
raise ValueError(msg)
|
|
@@ -204,6 +213,9 @@ def validate_url(
|
|
|
204
213
|
ValueError: If URL format is invalid.
|
|
205
214
|
|
|
206
215
|
"""
|
|
216
|
+
if not isinstance(url, str):
|
|
217
|
+
raise TypeError(f"URL must be str, got {type(url).__name__}")
|
|
218
|
+
|
|
207
219
|
if not url:
|
|
208
220
|
msg = "URL cannot be empty"
|
|
209
221
|
raise ValueError(msg)
|
|
@@ -98,6 +98,7 @@ class CircuitBreaker:
|
|
|
98
98
|
timeout: float = 30.0,
|
|
99
99
|
excluded_exceptions: tuple[type[Exception], ...] = (),
|
|
100
100
|
name: str = "default",
|
|
101
|
+
on_state_change: Callable[[CircuitState, CircuitState], None] | None = None,
|
|
101
102
|
) -> None:
|
|
102
103
|
"""Initialize CircuitBreaker.
|
|
103
104
|
|
|
@@ -107,6 +108,8 @@ class CircuitBreaker:
|
|
|
107
108
|
timeout: Seconds before attempting half-open.
|
|
108
109
|
excluded_exceptions: Exceptions that don't trip circuit.
|
|
109
110
|
name: Name for logging/identification.
|
|
111
|
+
on_state_change: Optional callback invoked on state transitions
|
|
112
|
+
with (old_state, new_state). Useful for custom monitoring.
|
|
110
113
|
|
|
111
114
|
"""
|
|
112
115
|
self.config = CircuitBreakerConfig(
|
|
@@ -117,6 +120,7 @@ class CircuitBreaker:
|
|
|
117
120
|
)
|
|
118
121
|
self.name = name
|
|
119
122
|
self._state = CircuitBreakerState()
|
|
123
|
+
self._on_state_change = on_state_change
|
|
120
124
|
|
|
121
125
|
@property
|
|
122
126
|
def state(self) -> CircuitState:
|
|
@@ -128,6 +132,15 @@ class CircuitBreaker:
|
|
|
128
132
|
"""Get current failure count."""
|
|
129
133
|
return self._state.failure_count
|
|
130
134
|
|
|
135
|
+
def _notify_state_change(
|
|
136
|
+
self,
|
|
137
|
+
old_state: CircuitState,
|
|
138
|
+
new_state: CircuitState,
|
|
139
|
+
) -> None:
|
|
140
|
+
"""Notify callback of state transition if registered."""
|
|
141
|
+
if self._on_state_change is not None:
|
|
142
|
+
self._on_state_change(old_state, new_state)
|
|
143
|
+
|
|
131
144
|
def _should_attempt(self) -> bool:
|
|
132
145
|
"""Check if a call should be attempted."""
|
|
133
146
|
with self._state.lock:
|
|
@@ -141,7 +154,17 @@ class CircuitBreaker:
|
|
|
141
154
|
if elapsed >= self.config.timeout:
|
|
142
155
|
self._state.state = CircuitState.HALF_OPEN
|
|
143
156
|
self._state.success_count = 0
|
|
144
|
-
logger.info(
|
|
157
|
+
logger.info(
|
|
158
|
+
"Circuit %s entering half-open state "
|
|
159
|
+
"(was open for %.1fs, failures=%d)",
|
|
160
|
+
self.name,
|
|
161
|
+
elapsed,
|
|
162
|
+
self._state.failure_count,
|
|
163
|
+
)
|
|
164
|
+
self._notify_state_change(
|
|
165
|
+
CircuitState.OPEN,
|
|
166
|
+
CircuitState.HALF_OPEN,
|
|
167
|
+
)
|
|
145
168
|
return True
|
|
146
169
|
return False
|
|
147
170
|
|
|
@@ -149,6 +172,8 @@ class CircuitBreaker:
|
|
|
149
172
|
# Allow limited attempts
|
|
150
173
|
return True
|
|
151
174
|
|
|
175
|
+
return False # pragma: no cover — unreachable, satisfies type checker
|
|
176
|
+
|
|
152
177
|
def _record_success(self) -> None:
|
|
153
178
|
"""Record a successful call."""
|
|
154
179
|
with self._state.lock:
|
|
@@ -158,7 +183,16 @@ class CircuitBreaker:
|
|
|
158
183
|
if self._state.success_count >= self.config.success_threshold:
|
|
159
184
|
self._state.state = CircuitState.CLOSED
|
|
160
185
|
self._state.failure_count = 0
|
|
161
|
-
logger.info(
|
|
186
|
+
logger.info(
|
|
187
|
+
"Circuit %s closed after recovery "
|
|
188
|
+
"(%d consecutive successes)",
|
|
189
|
+
self.name,
|
|
190
|
+
self._state.success_count,
|
|
191
|
+
)
|
|
192
|
+
self._notify_state_change(
|
|
193
|
+
CircuitState.HALF_OPEN,
|
|
194
|
+
CircuitState.CLOSED,
|
|
195
|
+
)
|
|
162
196
|
|
|
163
197
|
case CircuitState.CLOSED:
|
|
164
198
|
# Reset failure count on success
|
|
@@ -182,17 +216,28 @@ class CircuitBreaker:
|
|
|
182
216
|
# Any failure in half-open reopens circuit
|
|
183
217
|
self._state.state = CircuitState.OPEN
|
|
184
218
|
logger.warning(
|
|
185
|
-
"Circuit %s reopened after failure in half-open"
|
|
219
|
+
"Circuit %s reopened after failure in half-open "
|
|
220
|
+
"(total failures=%d)",
|
|
186
221
|
self.name,
|
|
222
|
+
self._state.failure_count,
|
|
223
|
+
)
|
|
224
|
+
self._notify_state_change(
|
|
225
|
+
CircuitState.HALF_OPEN,
|
|
226
|
+
CircuitState.OPEN,
|
|
187
227
|
)
|
|
188
228
|
|
|
189
229
|
case CircuitState.CLOSED:
|
|
190
230
|
if self._state.failure_count >= self.config.failure_threshold:
|
|
191
231
|
self._state.state = CircuitState.OPEN
|
|
192
232
|
logger.warning(
|
|
193
|
-
"Circuit %s opened after %d failures",
|
|
233
|
+
"Circuit %s opened after %d failures (threshold=%d)",
|
|
194
234
|
self.name,
|
|
195
235
|
self._state.failure_count,
|
|
236
|
+
self.config.failure_threshold,
|
|
237
|
+
)
|
|
238
|
+
self._notify_state_change(
|
|
239
|
+
CircuitState.CLOSED,
|
|
240
|
+
CircuitState.OPEN,
|
|
196
241
|
)
|
|
197
242
|
|
|
198
243
|
case CircuitState.OPEN: # pragma: no branch
|
|
@@ -235,6 +280,7 @@ def circuit_breaker(
|
|
|
235
280
|
timeout: float = 30.0,
|
|
236
281
|
excluded_exceptions: tuple[type[Exception], ...] = (),
|
|
237
282
|
name: str | None = None,
|
|
283
|
+
on_state_change: Callable[[CircuitState, CircuitState], None] | None = None,
|
|
238
284
|
) -> Callable[[Callable[P, R]], Callable[P, R]]:
|
|
239
285
|
"""Decorator to apply circuit breaker pattern.
|
|
240
286
|
|
|
@@ -244,6 +290,8 @@ def circuit_breaker(
|
|
|
244
290
|
timeout: Seconds before attempting half-open.
|
|
245
291
|
excluded_exceptions: Exceptions that don't trip circuit.
|
|
246
292
|
name: Optional name for the circuit.
|
|
293
|
+
on_state_change: Optional callback invoked on state transitions
|
|
294
|
+
with (old_state, new_state).
|
|
247
295
|
|
|
248
296
|
Returns:
|
|
249
297
|
Decorated function with circuit breaker protection.
|
|
@@ -253,6 +301,13 @@ def circuit_breaker(
|
|
|
253
301
|
... def call_api(endpoint: str) -> dict:
|
|
254
302
|
... return requests.get(endpoint).json()
|
|
255
303
|
|
|
304
|
+
>>> @circuit_breaker(
|
|
305
|
+
... failure_threshold=3,
|
|
306
|
+
... on_state_change=lambda old, new: print(f"{old} -> {new}"),
|
|
307
|
+
... )
|
|
308
|
+
... def monitored_call() -> str:
|
|
309
|
+
... return service.call()
|
|
310
|
+
|
|
256
311
|
"""
|
|
257
312
|
|
|
258
313
|
def decorator(func: Callable[P, R]) -> Callable[P, R]:
|
|
@@ -262,6 +317,7 @@ def circuit_breaker(
|
|
|
262
317
|
timeout=timeout,
|
|
263
318
|
excluded_exceptions=excluded_exceptions,
|
|
264
319
|
name=name or func.__name__,
|
|
320
|
+
on_state_change=on_state_change,
|
|
265
321
|
)
|
|
266
322
|
return breaker(func)
|
|
267
323
|
|
|
@@ -14,7 +14,8 @@ import random
|
|
|
14
14
|
import time
|
|
15
15
|
from collections.abc import Callable
|
|
16
16
|
from dataclasses import dataclass
|
|
17
|
-
from
|
|
17
|
+
from types import TracebackType
|
|
18
|
+
from typing import ParamSpec, TypeVar
|
|
18
19
|
|
|
19
20
|
P = ParamSpec("P")
|
|
20
21
|
R = TypeVar("R")
|
|
@@ -106,6 +107,7 @@ def retry(
|
|
|
106
107
|
on: tuple[type[Exception], ...] = (Exception,),
|
|
107
108
|
reraise: bool = True,
|
|
108
109
|
log_retries: bool = True,
|
|
110
|
+
on_retry: Callable[[int, int, Exception, float], None] | None = None,
|
|
109
111
|
) -> Callable[[Callable[P, R]], Callable[P, R]]:
|
|
110
112
|
"""Retry a function with exponential backoff.
|
|
111
113
|
|
|
@@ -121,6 +123,9 @@ def retry(
|
|
|
121
123
|
on: Exception types to retry on.
|
|
122
124
|
reraise: Whether to reraise the last exception on failure.
|
|
123
125
|
log_retries: Whether to log retry attempts.
|
|
126
|
+
on_retry: Optional callback invoked on each retry with
|
|
127
|
+
(attempt, max_attempts, exception, delay). Useful for
|
|
128
|
+
custom monitoring or metrics collection.
|
|
124
129
|
|
|
125
130
|
Returns:
|
|
126
131
|
Decorated function with retry logic.
|
|
@@ -130,6 +135,10 @@ def retry(
|
|
|
130
135
|
... def fetch_data(url: str) -> dict:
|
|
131
136
|
... return requests.get(url).json()
|
|
132
137
|
|
|
138
|
+
>>> @retry(max_attempts=3, on_retry=lambda a, m, e, d: print(f"Retry {a}/{m}"))
|
|
139
|
+
... def fragile_operation() -> str:
|
|
140
|
+
... return do_something()
|
|
141
|
+
|
|
133
142
|
"""
|
|
134
143
|
config = RetryConfig(
|
|
135
144
|
max_attempts=max_attempts,
|
|
@@ -175,6 +184,10 @@ def retry(
|
|
|
175
184
|
delay,
|
|
176
185
|
)
|
|
177
186
|
|
|
187
|
+
# Invoke callback if provided
|
|
188
|
+
if on_retry is not None:
|
|
189
|
+
on_retry(attempt, max_attempts, e, delay)
|
|
190
|
+
|
|
178
191
|
time.sleep(delay)
|
|
179
192
|
|
|
180
193
|
# All attempts failed
|
|
@@ -274,9 +287,9 @@ class Retrier:
|
|
|
274
287
|
|
|
275
288
|
def __exit__(
|
|
276
289
|
self,
|
|
277
|
-
exc_type: type[
|
|
278
|
-
exc_val:
|
|
279
|
-
_exc_tb:
|
|
290
|
+
exc_type: type[BaseException] | None,
|
|
291
|
+
exc_val: BaseException | None,
|
|
292
|
+
_exc_tb: TracebackType | None,
|
|
280
293
|
) -> bool:
|
|
281
294
|
"""Exit the retry context.
|
|
282
295
|
|
|
@@ -289,7 +302,8 @@ class Retrier:
|
|
|
289
302
|
if not issubclass(exc_type, self.exception_types):
|
|
290
303
|
return False # Exception type not in retry list
|
|
291
304
|
|
|
292
|
-
|
|
305
|
+
# Safe cast: issubclass guard above ensures exc_val is Exception
|
|
306
|
+
self.last_exception = exc_val if isinstance(exc_val, Exception) else None
|
|
293
307
|
self.attempt += 1
|
|
294
308
|
|
|
295
309
|
if self.attempt >= self.config.max_attempts:
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|