taipanstack 0.3.0__tar.gz → 0.3.2__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.2}/PKG-INFO +45 -2
- {taipanstack-0.3.0 → taipanstack-0.3.2}/README.md +43 -0
- {taipanstack-0.3.0 → taipanstack-0.3.2}/pyproject.toml +7 -2
- {taipanstack-0.3.0 → taipanstack-0.3.2}/src/taipanstack/__init__.py +1 -5
- {taipanstack-0.3.0 → taipanstack-0.3.2}/src/taipanstack/config/__init__.py +0 -2
- {taipanstack-0.3.0 → taipanstack-0.3.2}/src/taipanstack/config/generators.py +59 -13
- {taipanstack-0.3.0 → taipanstack-0.3.2}/src/taipanstack/config/models.py +1 -3
- {taipanstack-0.3.0 → taipanstack-0.3.2}/src/taipanstack/config/version_config.py +0 -2
- {taipanstack-0.3.0 → taipanstack-0.3.2}/src/taipanstack/core/compat.py +1 -6
- {taipanstack-0.3.0 → taipanstack-0.3.2}/src/taipanstack/core/result.py +37 -4
- {taipanstack-0.3.0 → taipanstack-0.3.2}/src/taipanstack/security/__init__.py +0 -2
- {taipanstack-0.3.0 → taipanstack-0.3.2}/src/taipanstack/security/guards.py +99 -75
- {taipanstack-0.3.0 → taipanstack-0.3.2}/src/taipanstack/security/sanitizers.py +14 -4
- {taipanstack-0.3.0 → taipanstack-0.3.2}/src/taipanstack/security/validators.py +13 -1
- {taipanstack-0.3.0 → taipanstack-0.3.2}/src/taipanstack/utils/circuit_breaker.py +69 -5
- {taipanstack-0.3.0 → taipanstack-0.3.2}/src/taipanstack/utils/filesystem.py +0 -2
- {taipanstack-0.3.0 → taipanstack-0.3.2}/src/taipanstack/utils/logging.py +3 -1
- {taipanstack-0.3.0 → taipanstack-0.3.2}/src/taipanstack/utils/retry.py +19 -5
- {taipanstack-0.3.0 → taipanstack-0.3.2}/LICENSE +0 -0
- {taipanstack-0.3.0 → taipanstack-0.3.2}/src/taipanstack/core/__init__.py +0 -0
- {taipanstack-0.3.0 → taipanstack-0.3.2}/src/taipanstack/core/optimizations.py +0 -0
- {taipanstack-0.3.0 → taipanstack-0.3.2}/src/taipanstack/security/decorators.py +0 -0
- {taipanstack-0.3.0 → taipanstack-0.3.2}/src/taipanstack/utils/__init__.py +0 -0
- {taipanstack-0.3.0 → taipanstack-0.3.2}/src/taipanstack/utils/metrics.py +0 -0
- {taipanstack-0.3.0 → taipanstack-0.3.2}/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.2
|
|
4
4
|
Summary: TaipanStack - Modular, secure, and scalable Python stack for robust development
|
|
5
5
|
License-Expression: MIT
|
|
6
6
|
License-File: LICENSE
|
|
@@ -27,7 +27,7 @@ Requires-Dist: result (>=0.17.0)
|
|
|
27
27
|
Requires-Dist: structlog (>=23.0.0) ; extra == "runtime"
|
|
28
28
|
Requires-Dist: uvloop (>=0.19.0) ; (sys_platform != "win32") and (extra == "runtime")
|
|
29
29
|
Project-URL: Changelog, https://github.com/gabrielima7/TaipanStack/blob/main/CHANGELOG.md
|
|
30
|
-
Project-URL: Documentation, https://github.
|
|
30
|
+
Project-URL: Documentation, https://gabrielima7.github.io/TaipanStack/
|
|
31
31
|
Project-URL: Homepage, https://github.com/gabrielima7/TaipanStack
|
|
32
32
|
Project-URL: Issues, https://github.com/gabrielima7/TaipanStack/issues
|
|
33
33
|
Project-URL: Repository, https://github.com/gabrielima7/TaipanStack
|
|
@@ -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
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "taipanstack"
|
|
3
|
-
version = "0.3.
|
|
3
|
+
version = "0.3.2"
|
|
4
4
|
description = "TaipanStack - Modular, secure, and scalable Python stack for robust development"
|
|
5
5
|
authors = [
|
|
6
6
|
{name = "gabrielima7", email = "gabrielima.alu.lmb@gmail.com"}
|
|
@@ -31,7 +31,7 @@ dependencies = [
|
|
|
31
31
|
|
|
32
32
|
[project.urls]
|
|
33
33
|
Homepage = "https://github.com/gabrielima7/TaipanStack"
|
|
34
|
-
Documentation = "https://github.
|
|
34
|
+
Documentation = "https://gabrielima7.github.io/TaipanStack/"
|
|
35
35
|
Repository = "https://github.com/gabrielima7/TaipanStack"
|
|
36
36
|
Changelog = "https://github.com/gabrielima7/TaipanStack/blob/main/CHANGELOG.md"
|
|
37
37
|
Issues = "https://github.com/gabrielima7/TaipanStack/issues"
|
|
@@ -71,7 +71,12 @@ dev = [
|
|
|
71
71
|
|
|
72
72
|
|
|
73
73
|
|
|
74
|
+
|
|
74
75
|
# --- TaipanStack v2.0 Quality Configuration ---
|
|
76
|
+
docs = [
|
|
77
|
+
"mkdocs-material (>=9.7.3,<10.0.0)",
|
|
78
|
+
"mkdocstrings[python] (>=1.0.3,<2.0.0)"
|
|
79
|
+
]
|
|
75
80
|
[tool.ruff]
|
|
76
81
|
line-length = 88
|
|
77
82
|
target-version = "py311"
|
|
@@ -5,15 +5,13 @@ 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.2"
|
|
9
9
|
|
|
10
|
-
from taipanstack.config.models import StackConfig
|
|
11
10
|
from taipanstack.config.version_config import (
|
|
12
11
|
VersionRecommendations,
|
|
13
12
|
get_version_recommendations,
|
|
14
13
|
)
|
|
15
14
|
from taipanstack.core.compat import (
|
|
16
|
-
PY311,
|
|
17
15
|
PY312,
|
|
18
16
|
PY313,
|
|
19
17
|
PY314,
|
|
@@ -33,12 +31,10 @@ from taipanstack.security.validators import (
|
|
|
33
31
|
)
|
|
34
32
|
|
|
35
33
|
__all__ = [
|
|
36
|
-
"PY311",
|
|
37
34
|
"PY312",
|
|
38
35
|
"PY313",
|
|
39
36
|
"PY314",
|
|
40
37
|
"PY_VERSION",
|
|
41
|
-
"StackConfig",
|
|
42
38
|
"VersionRecommendations",
|
|
43
39
|
"apply_optimizations",
|
|
44
40
|
"get_features",
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
"""Configuration models package."""
|
|
2
2
|
|
|
3
3
|
from taipanstack.config.generators import (
|
|
4
|
-
generate_dependabot_config,
|
|
5
4
|
generate_pre_commit_config,
|
|
6
5
|
generate_pyproject_config,
|
|
7
6
|
generate_security_policy,
|
|
@@ -18,7 +17,6 @@ __all__ = [
|
|
|
18
17
|
"LoggingConfig",
|
|
19
18
|
"SecurityConfig",
|
|
20
19
|
"StackConfig",
|
|
21
|
-
"generate_dependabot_config",
|
|
22
20
|
"generate_pre_commit_config",
|
|
23
21
|
"generate_pyproject_config",
|
|
24
22
|
"generate_security_policy",
|
|
@@ -14,22 +14,17 @@ if TYPE_CHECKING:
|
|
|
14
14
|
from taipanstack.config.models import StackConfig
|
|
15
15
|
|
|
16
16
|
|
|
17
|
-
def
|
|
18
|
-
"""Generate Ruff
|
|
17
|
+
def _generate_ruff_config(target_version: str) -> str:
|
|
18
|
+
"""Generate Ruff configuration.
|
|
19
19
|
|
|
20
20
|
Args:
|
|
21
|
-
|
|
21
|
+
target_version: The target Python version.
|
|
22
22
|
|
|
23
23
|
Returns:
|
|
24
|
-
|
|
24
|
+
Ruff configuration string.
|
|
25
25
|
|
|
26
26
|
"""
|
|
27
|
-
|
|
28
|
-
python_version = config.python_version
|
|
29
|
-
|
|
30
|
-
return f"""
|
|
31
|
-
# --- Stack v2.0 Quality Configuration ---
|
|
32
|
-
[tool.ruff]
|
|
27
|
+
return f"""[tool.ruff]
|
|
33
28
|
line-length = 88
|
|
34
29
|
target-version = "{target_version}"
|
|
35
30
|
|
|
@@ -72,8 +67,20 @@ max-complexity = 10
|
|
|
72
67
|
[tool.ruff.format]
|
|
73
68
|
quote-style = "double"
|
|
74
69
|
indent-style = "space"
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _generate_mypy_config(python_version: str) -> str:
|
|
74
|
+
"""Generate Mypy configuration.
|
|
75
75
|
|
|
76
|
-
|
|
76
|
+
Args:
|
|
77
|
+
python_version: The target Python version.
|
|
78
|
+
|
|
79
|
+
Returns:
|
|
80
|
+
Mypy configuration string.
|
|
81
|
+
|
|
82
|
+
"""
|
|
83
|
+
return f"""[tool.mypy]
|
|
77
84
|
python_version = "{python_version}"
|
|
78
85
|
warn_return_any = true
|
|
79
86
|
warn_unused_configs = true
|
|
@@ -86,16 +93,34 @@ strict_equality = true
|
|
|
86
93
|
ignore_missing_imports = true
|
|
87
94
|
show_error_codes = true
|
|
88
95
|
enable_error_code = ["ignore-without-code", "redundant-cast", "truthy-bool"]
|
|
96
|
+
"""
|
|
89
97
|
|
|
90
|
-
|
|
98
|
+
|
|
99
|
+
def _generate_pytest_config() -> str:
|
|
100
|
+
"""Generate Pytest configuration.
|
|
101
|
+
|
|
102
|
+
Returns:
|
|
103
|
+
Pytest configuration string.
|
|
104
|
+
|
|
105
|
+
"""
|
|
106
|
+
return """[tool.pytest.ini_options]
|
|
91
107
|
testpaths = ["tests"]
|
|
92
108
|
addopts = "-v --cov=src --cov-report=html --cov-report=term-missing --cov-fail-under=80 --strict-markers"
|
|
93
109
|
markers = [
|
|
94
110
|
"slow: marks tests as slow (deselect with '-m \"not slow\"')",
|
|
95
111
|
"security: marks tests as security-related",
|
|
96
112
|
]
|
|
113
|
+
"""
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _generate_coverage_config() -> str:
|
|
117
|
+
"""Generate Coverage configuration.
|
|
97
118
|
|
|
98
|
-
|
|
119
|
+
Returns:
|
|
120
|
+
Coverage configuration string.
|
|
121
|
+
|
|
122
|
+
"""
|
|
123
|
+
return """[tool.coverage.run]
|
|
99
124
|
branch = true
|
|
100
125
|
source = ["src"]
|
|
101
126
|
omit = ["*/tests/*", "*/__pycache__/*"]
|
|
@@ -111,6 +136,27 @@ exclude_lines = [
|
|
|
111
136
|
"""
|
|
112
137
|
|
|
113
138
|
|
|
139
|
+
def generate_pyproject_config(config: StackConfig) -> str:
|
|
140
|
+
"""Generate Ruff, Mypy, and Pytest configuration for pyproject.toml.
|
|
141
|
+
|
|
142
|
+
Args:
|
|
143
|
+
config: The Stack configuration.
|
|
144
|
+
|
|
145
|
+
Returns:
|
|
146
|
+
Configuration string to append to pyproject.toml.
|
|
147
|
+
|
|
148
|
+
"""
|
|
149
|
+
target_version = config.to_target_version()
|
|
150
|
+
python_version = config.python_version
|
|
151
|
+
|
|
152
|
+
return f"""
|
|
153
|
+
# --- Stack v2.0 Quality Configuration ---
|
|
154
|
+
{_generate_ruff_config(target_version)}
|
|
155
|
+
{_generate_mypy_config(python_version)}
|
|
156
|
+
{_generate_pytest_config()}
|
|
157
|
+
{_generate_coverage_config()}"""
|
|
158
|
+
|
|
159
|
+
|
|
114
160
|
def generate_pre_commit_config(config: StackConfig) -> str:
|
|
115
161
|
"""Generate .pre-commit-config.yaml content.
|
|
116
162
|
|
|
@@ -5,8 +5,6 @@ This module provides type-safe configuration models that validate
|
|
|
5
5
|
all inputs at runtime, preventing errors and AI hallucinations.
|
|
6
6
|
"""
|
|
7
7
|
|
|
8
|
-
from __future__ import annotations
|
|
9
|
-
|
|
10
8
|
import re
|
|
11
9
|
import sys
|
|
12
10
|
from pathlib import Path
|
|
@@ -281,7 +279,7 @@ class StackConfig(BaseModel):
|
|
|
281
279
|
return resolved
|
|
282
280
|
|
|
283
281
|
@model_validator(mode="after")
|
|
284
|
-
def validate_config_consistency(self) -> StackConfig:
|
|
282
|
+
def validate_config_consistency(self) -> "StackConfig":
|
|
285
283
|
"""Validate configuration consistency.
|
|
286
284
|
|
|
287
285
|
Returns:
|
|
@@ -8,17 +8,12 @@ maintaining compatibility with Python 3.11+.
|
|
|
8
8
|
Following Stack pillars: Security, Stability, Simplicity, Scalability, Compatibility.
|
|
9
9
|
"""
|
|
10
10
|
|
|
11
|
-
from __future__ import annotations
|
|
12
|
-
|
|
13
11
|
import logging
|
|
14
12
|
import os
|
|
15
13
|
import sys
|
|
16
14
|
from dataclasses import dataclass
|
|
17
15
|
from enum import StrEnum
|
|
18
|
-
from typing import
|
|
19
|
-
|
|
20
|
-
if TYPE_CHECKING:
|
|
21
|
-
from typing import Final
|
|
16
|
+
from typing import Final
|
|
22
17
|
|
|
23
18
|
__all__ = [
|
|
24
19
|
"PY311",
|
|
@@ -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:
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
"""Security package for runtime protection."""
|
|
2
2
|
|
|
3
3
|
from taipanstack.security.decorators import (
|
|
4
|
-
OperationTimeoutError,
|
|
5
4
|
ValidationError,
|
|
6
5
|
deprecated,
|
|
7
6
|
guard_exceptions,
|
|
@@ -30,7 +29,6 @@ from taipanstack.security.validators import (
|
|
|
30
29
|
|
|
31
30
|
__all__ = [
|
|
32
31
|
# Decorators
|
|
33
|
-
"OperationTimeoutError",
|
|
34
32
|
# Guards
|
|
35
33
|
"SecurityError",
|
|
36
34
|
"ValidationError",
|
|
@@ -13,6 +13,78 @@ import re
|
|
|
13
13
|
from collections.abc import Sequence
|
|
14
14
|
from pathlib import Path
|
|
15
15
|
|
|
16
|
+
_TRAVERSAL_PATTERNS: frozenset[str] = frozenset(
|
|
17
|
+
[
|
|
18
|
+
"..",
|
|
19
|
+
"~",
|
|
20
|
+
r"\.\.",
|
|
21
|
+
"%2e%2e", # URL encoded ..
|
|
22
|
+
"%252e%252e", # Double URL encoded
|
|
23
|
+
]
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
_DANGEROUS_COMMAND_PATTERNS: tuple[tuple[str, str], ...] = (
|
|
27
|
+
(";", "command separator"),
|
|
28
|
+
("|", "pipe"),
|
|
29
|
+
("&", "background/and operator"),
|
|
30
|
+
("$", "variable expansion"),
|
|
31
|
+
("`", "command substitution"),
|
|
32
|
+
("$(", "command substitution"),
|
|
33
|
+
("${", "variable expansion"),
|
|
34
|
+
(">", "redirect"),
|
|
35
|
+
("<", "redirect"),
|
|
36
|
+
(">>", "redirect append"),
|
|
37
|
+
("||", "or operator"),
|
|
38
|
+
("&&", "and operator"),
|
|
39
|
+
("\n", "newline"),
|
|
40
|
+
("\r", "carriage return"),
|
|
41
|
+
("\x00", "null byte"),
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
_DEFAULT_DENIED_EXTENSIONS = frozenset(
|
|
45
|
+
[
|
|
46
|
+
"exe",
|
|
47
|
+
"dll",
|
|
48
|
+
"so",
|
|
49
|
+
"dylib", # Executables
|
|
50
|
+
"sh",
|
|
51
|
+
"bash",
|
|
52
|
+
"zsh",
|
|
53
|
+
"ps1",
|
|
54
|
+
"bat",
|
|
55
|
+
"cmd", # Scripts
|
|
56
|
+
"php",
|
|
57
|
+
"jsp",
|
|
58
|
+
"asp",
|
|
59
|
+
"aspx", # Server-side scripts
|
|
60
|
+
]
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
_DEFAULT_DENIED_ENV_VARS = frozenset(
|
|
64
|
+
[
|
|
65
|
+
"AWS_SECRET_ACCESS_KEY",
|
|
66
|
+
"AWS_SESSION_TOKEN",
|
|
67
|
+
"GITHUB_TOKEN",
|
|
68
|
+
"GH_TOKEN",
|
|
69
|
+
"GITLAB_TOKEN",
|
|
70
|
+
"DATABASE_URL",
|
|
71
|
+
"DB_PASSWORD",
|
|
72
|
+
"PASSWORD",
|
|
73
|
+
"SECRET_KEY",
|
|
74
|
+
"PRIVATE_KEY",
|
|
75
|
+
"API_KEY",
|
|
76
|
+
"API_SECRET",
|
|
77
|
+
]
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
_SENSITIVE_ENV_VAR_PATTERNS = (
|
|
81
|
+
re.compile(r".*SECRET.*"),
|
|
82
|
+
re.compile(r".*PASSWORD.*"),
|
|
83
|
+
re.compile(r".*TOKEN.*"),
|
|
84
|
+
re.compile(r".*PRIVATE.*KEY.*"),
|
|
85
|
+
re.compile(r".*API.*KEY.*"),
|
|
86
|
+
)
|
|
87
|
+
|
|
16
88
|
|
|
17
89
|
class SecurityError(Exception):
|
|
18
90
|
"""Raised when a security guard detects a violation.
|
|
@@ -70,20 +142,15 @@ def guard_path_traversal(
|
|
|
70
142
|
SecurityError: [path_traversal] Path escapes base directory
|
|
71
143
|
|
|
72
144
|
"""
|
|
145
|
+
if not isinstance(path, (str, Path)):
|
|
146
|
+
raise TypeError(f"path must be str or Path, got {type(path).__name__}")
|
|
73
147
|
path = Path(path) if isinstance(path, str) else path
|
|
74
148
|
base_dir = Path(base_dir).resolve() if base_dir else Path.cwd().resolve()
|
|
75
149
|
|
|
76
150
|
# Check for explicit traversal patterns before resolution
|
|
77
151
|
path_str = str(path)
|
|
78
|
-
traversal_patterns = [
|
|
79
|
-
"..",
|
|
80
|
-
"~",
|
|
81
|
-
r"\.\.",
|
|
82
|
-
"%2e%2e", # URL encoded ..
|
|
83
|
-
"%252e%252e", # Double URL encoded
|
|
84
|
-
]
|
|
85
152
|
|
|
86
|
-
for pattern in
|
|
153
|
+
for pattern in _TRAVERSAL_PATTERNS:
|
|
87
154
|
if pattern.lower() in path_str.lower():
|
|
88
155
|
raise SecurityError(
|
|
89
156
|
f"Path traversal pattern detected: {pattern}",
|
|
@@ -157,27 +224,16 @@ def guard_command_injection(
|
|
|
157
224
|
|
|
158
225
|
cmd_list = list(command)
|
|
159
226
|
|
|
160
|
-
#
|
|
161
|
-
|
|
162
|
-
(
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
("$(", "command substitution"),
|
|
168
|
-
("${", "variable expansion"),
|
|
169
|
-
(">", "redirect"),
|
|
170
|
-
("<", "redirect"),
|
|
171
|
-
(">>", "redirect append"),
|
|
172
|
-
("||", "or operator"),
|
|
173
|
-
("&&", "and operator"),
|
|
174
|
-
("\n", "newline"),
|
|
175
|
-
("\r", "carriage return"),
|
|
176
|
-
("\x00", "null byte"),
|
|
177
|
-
]
|
|
227
|
+
# Validate all items are strings
|
|
228
|
+
for i, arg in enumerate(cmd_list):
|
|
229
|
+
if not isinstance(arg, str):
|
|
230
|
+
raise TypeError(
|
|
231
|
+
f"All command arguments must be strings, "
|
|
232
|
+
f"got {type(arg).__name__} at index {i}"
|
|
233
|
+
)
|
|
178
234
|
|
|
179
235
|
for arg in cmd_list:
|
|
180
|
-
for pattern, description in
|
|
236
|
+
for pattern, description in _DANGEROUS_COMMAND_PATTERNS:
|
|
181
237
|
if pattern in arg:
|
|
182
238
|
raise SecurityError(
|
|
183
239
|
f"Dangerous shell character detected: {description}",
|
|
@@ -227,32 +283,14 @@ def guard_file_extension(
|
|
|
227
283
|
path = Path(filename)
|
|
228
284
|
ext = path.suffix.lower().lstrip(".")
|
|
229
285
|
|
|
230
|
-
# Default dangerous extensions
|
|
231
|
-
default_denied = {
|
|
232
|
-
"exe",
|
|
233
|
-
"dll",
|
|
234
|
-
"so",
|
|
235
|
-
"dylib", # Executables
|
|
236
|
-
"sh",
|
|
237
|
-
"bash",
|
|
238
|
-
"zsh",
|
|
239
|
-
"ps1",
|
|
240
|
-
"bat",
|
|
241
|
-
"cmd", # Scripts
|
|
242
|
-
"php",
|
|
243
|
-
"jsp",
|
|
244
|
-
"asp",
|
|
245
|
-
"aspx", # Server-side scripts
|
|
246
|
-
}
|
|
247
|
-
|
|
248
286
|
# Normalize extension lists
|
|
249
287
|
def normalize_ext(e: str) -> str:
|
|
250
288
|
return e.lower().lstrip(".")
|
|
251
289
|
|
|
252
290
|
if denied_extensions is not None:
|
|
253
|
-
denied =
|
|
291
|
+
denied = frozenset(normalize_ext(e) for e in denied_extensions)
|
|
254
292
|
else:
|
|
255
|
-
denied =
|
|
293
|
+
denied = _DEFAULT_DENIED_EXTENSIONS
|
|
256
294
|
|
|
257
295
|
if ext in denied:
|
|
258
296
|
raise SecurityError(
|
|
@@ -293,37 +331,23 @@ def guard_env_variable(
|
|
|
293
331
|
SecurityError: If variable access is not allowed.
|
|
294
332
|
|
|
295
333
|
"""
|
|
296
|
-
#
|
|
297
|
-
|
|
298
|
-
"
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
"SECRET_KEY",
|
|
307
|
-
"PRIVATE_KEY",
|
|
308
|
-
"API_KEY",
|
|
309
|
-
"API_SECRET",
|
|
310
|
-
}
|
|
334
|
+
# Validate input type
|
|
335
|
+
if not isinstance(name, str):
|
|
336
|
+
raise TypeError(f"Variable name must be str, got {type(name).__name__}")
|
|
337
|
+
|
|
338
|
+
# Reject empty/whitespace-only variable names
|
|
339
|
+
if not name or not name.strip():
|
|
340
|
+
raise SecurityError(
|
|
341
|
+
"Environment variable name cannot be empty or whitespace",
|
|
342
|
+
guard_name="env_variable",
|
|
343
|
+
)
|
|
311
344
|
|
|
312
345
|
name_upper = name.upper()
|
|
313
346
|
|
|
314
347
|
if denied_names is not None:
|
|
315
|
-
denied =
|
|
348
|
+
denied = frozenset(n.upper() for n in denied_names)
|
|
316
349
|
else:
|
|
317
|
-
denied =
|
|
318
|
-
|
|
319
|
-
# Check against patterns
|
|
320
|
-
sensitive_patterns = [
|
|
321
|
-
r".*SECRET.*",
|
|
322
|
-
r".*PASSWORD.*",
|
|
323
|
-
r".*TOKEN.*",
|
|
324
|
-
r".*PRIVATE.*KEY.*",
|
|
325
|
-
r".*API.*KEY.*",
|
|
326
|
-
]
|
|
350
|
+
denied = _DEFAULT_DENIED_ENV_VARS
|
|
327
351
|
|
|
328
352
|
if name_upper in denied:
|
|
329
353
|
raise SecurityError(
|
|
@@ -332,8 +356,8 @@ def guard_env_variable(
|
|
|
332
356
|
value=name,
|
|
333
357
|
)
|
|
334
358
|
|
|
335
|
-
for pattern in
|
|
336
|
-
if
|
|
359
|
+
for pattern in _SENSITIVE_ENV_VAR_PATTERNS:
|
|
360
|
+
if pattern.match(name_upper):
|
|
337
361
|
# Only block if not explicitly allowed
|
|
338
362
|
if allowed_names is not None:
|
|
339
363
|
allowed = {n.upper() for n in allowed_names}
|
|
@@ -65,10 +65,15 @@ def sanitize_string(
|
|
|
65
65
|
The sanitized string.
|
|
66
66
|
|
|
67
67
|
Example:
|
|
68
|
-
|
|
69
|
-
"
|
|
68
|
+
```python
|
|
69
|
+
sanitize_string("<script>alert('xss')</script>Hello")
|
|
70
|
+
# Returns: "scriptalert('xss')/scriptHello"
|
|
71
|
+
```
|
|
70
72
|
|
|
71
73
|
"""
|
|
74
|
+
if not isinstance(value, str):
|
|
75
|
+
raise TypeError(f"value must be str, got {type(value).__name__}")
|
|
76
|
+
|
|
72
77
|
if not value:
|
|
73
78
|
return ""
|
|
74
79
|
|
|
@@ -127,10 +132,15 @@ def sanitize_filename(
|
|
|
127
132
|
The sanitized filename.
|
|
128
133
|
|
|
129
134
|
Example:
|
|
130
|
-
|
|
131
|
-
|
|
135
|
+
```python
|
|
136
|
+
sanitize_filename("my/../file<>:name.txt")
|
|
137
|
+
# Returns: 'my_file_name.txt'
|
|
138
|
+
```
|
|
132
139
|
|
|
133
140
|
"""
|
|
141
|
+
if not isinstance(filename, str):
|
|
142
|
+
raise TypeError(f"filename must be str, got {type(filename).__name__}")
|
|
143
|
+
|
|
134
144
|
if not filename:
|
|
135
145
|
return "unnamed"
|
|
136
146
|
|
|
@@ -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):
|
|
@@ -125,7 +131,7 @@ def validate_python_version(version: str) -> str:
|
|
|
125
131
|
|
|
126
132
|
try:
|
|
127
133
|
major, minor = map(int, version.split("."))
|
|
128
|
-
except ValueError as e:
|
|
134
|
+
except ValueError as e:
|
|
129
135
|
msg = f"Invalid version numbers in '{version}'"
|
|
130
136
|
raise ValueError(msg) from e
|
|
131
137
|
|
|
@@ -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)
|
|
@@ -55,6 +55,7 @@ class CircuitBreakerConfig:
|
|
|
55
55
|
success_threshold: Successes needed in half-open to close.
|
|
56
56
|
timeout: Seconds before trying half-open after open.
|
|
57
57
|
excluded_exceptions: Exceptions that don't count as failures.
|
|
58
|
+
failure_exceptions: Exceptions that count as failures.
|
|
58
59
|
|
|
59
60
|
"""
|
|
60
61
|
|
|
@@ -62,6 +63,7 @@ class CircuitBreakerConfig:
|
|
|
62
63
|
success_threshold: int = 2
|
|
63
64
|
timeout: float = 30.0
|
|
64
65
|
excluded_exceptions: tuple[type[Exception], ...] = ()
|
|
66
|
+
failure_exceptions: tuple[type[Exception], ...] = (Exception,)
|
|
65
67
|
|
|
66
68
|
|
|
67
69
|
@dataclass
|
|
@@ -97,7 +99,9 @@ class CircuitBreaker:
|
|
|
97
99
|
success_threshold: int = 2,
|
|
98
100
|
timeout: float = 30.0,
|
|
99
101
|
excluded_exceptions: tuple[type[Exception], ...] = (),
|
|
102
|
+
failure_exceptions: tuple[type[Exception], ...] = (Exception,),
|
|
100
103
|
name: str = "default",
|
|
104
|
+
on_state_change: Callable[[CircuitState, CircuitState], None] | None = None,
|
|
101
105
|
) -> None:
|
|
102
106
|
"""Initialize CircuitBreaker.
|
|
103
107
|
|
|
@@ -106,7 +110,10 @@ class CircuitBreaker:
|
|
|
106
110
|
success_threshold: Successes to close from half-open.
|
|
107
111
|
timeout: Seconds before attempting half-open.
|
|
108
112
|
excluded_exceptions: Exceptions that don't trip circuit.
|
|
113
|
+
failure_exceptions: Exceptions that count as failures.
|
|
109
114
|
name: Name for logging/identification.
|
|
115
|
+
on_state_change: Optional callback invoked on state transitions
|
|
116
|
+
with (old_state, new_state). Useful for custom monitoring.
|
|
110
117
|
|
|
111
118
|
"""
|
|
112
119
|
self.config = CircuitBreakerConfig(
|
|
@@ -114,9 +121,11 @@ class CircuitBreaker:
|
|
|
114
121
|
success_threshold=success_threshold,
|
|
115
122
|
timeout=timeout,
|
|
116
123
|
excluded_exceptions=excluded_exceptions,
|
|
124
|
+
failure_exceptions=failure_exceptions,
|
|
117
125
|
)
|
|
118
126
|
self.name = name
|
|
119
127
|
self._state = CircuitBreakerState()
|
|
128
|
+
self._on_state_change = on_state_change
|
|
120
129
|
|
|
121
130
|
@property
|
|
122
131
|
def state(self) -> CircuitState:
|
|
@@ -128,6 +137,15 @@ class CircuitBreaker:
|
|
|
128
137
|
"""Get current failure count."""
|
|
129
138
|
return self._state.failure_count
|
|
130
139
|
|
|
140
|
+
def _notify_state_change(
|
|
141
|
+
self,
|
|
142
|
+
old_state: CircuitState,
|
|
143
|
+
new_state: CircuitState,
|
|
144
|
+
) -> None:
|
|
145
|
+
"""Notify callback of state transition if registered."""
|
|
146
|
+
if self._on_state_change is not None:
|
|
147
|
+
self._on_state_change(old_state, new_state)
|
|
148
|
+
|
|
131
149
|
def _should_attempt(self) -> bool:
|
|
132
150
|
"""Check if a call should be attempted."""
|
|
133
151
|
with self._state.lock:
|
|
@@ -141,7 +159,17 @@ class CircuitBreaker:
|
|
|
141
159
|
if elapsed >= self.config.timeout:
|
|
142
160
|
self._state.state = CircuitState.HALF_OPEN
|
|
143
161
|
self._state.success_count = 0
|
|
144
|
-
logger.info(
|
|
162
|
+
logger.info(
|
|
163
|
+
"Circuit %s entering half-open state "
|
|
164
|
+
"(was open for %.1fs, failures=%d)",
|
|
165
|
+
self.name,
|
|
166
|
+
elapsed,
|
|
167
|
+
self._state.failure_count,
|
|
168
|
+
)
|
|
169
|
+
self._notify_state_change(
|
|
170
|
+
CircuitState.OPEN,
|
|
171
|
+
CircuitState.HALF_OPEN,
|
|
172
|
+
)
|
|
145
173
|
return True
|
|
146
174
|
return False
|
|
147
175
|
|
|
@@ -149,6 +177,8 @@ class CircuitBreaker:
|
|
|
149
177
|
# Allow limited attempts
|
|
150
178
|
return True
|
|
151
179
|
|
|
180
|
+
return False # pragma: no cover — unreachable, satisfies type checker
|
|
181
|
+
|
|
152
182
|
def _record_success(self) -> None:
|
|
153
183
|
"""Record a successful call."""
|
|
154
184
|
with self._state.lock:
|
|
@@ -158,7 +188,16 @@ class CircuitBreaker:
|
|
|
158
188
|
if self._state.success_count >= self.config.success_threshold:
|
|
159
189
|
self._state.state = CircuitState.CLOSED
|
|
160
190
|
self._state.failure_count = 0
|
|
161
|
-
logger.info(
|
|
191
|
+
logger.info(
|
|
192
|
+
"Circuit %s closed after recovery "
|
|
193
|
+
"(%d consecutive successes)",
|
|
194
|
+
self.name,
|
|
195
|
+
self._state.success_count,
|
|
196
|
+
)
|
|
197
|
+
self._notify_state_change(
|
|
198
|
+
CircuitState.HALF_OPEN,
|
|
199
|
+
CircuitState.CLOSED,
|
|
200
|
+
)
|
|
162
201
|
|
|
163
202
|
case CircuitState.CLOSED:
|
|
164
203
|
# Reset failure count on success
|
|
@@ -182,17 +221,28 @@ class CircuitBreaker:
|
|
|
182
221
|
# Any failure in half-open reopens circuit
|
|
183
222
|
self._state.state = CircuitState.OPEN
|
|
184
223
|
logger.warning(
|
|
185
|
-
"Circuit %s reopened after failure in half-open"
|
|
224
|
+
"Circuit %s reopened after failure in half-open "
|
|
225
|
+
"(total failures=%d)",
|
|
186
226
|
self.name,
|
|
227
|
+
self._state.failure_count,
|
|
228
|
+
)
|
|
229
|
+
self._notify_state_change(
|
|
230
|
+
CircuitState.HALF_OPEN,
|
|
231
|
+
CircuitState.OPEN,
|
|
187
232
|
)
|
|
188
233
|
|
|
189
234
|
case CircuitState.CLOSED:
|
|
190
235
|
if self._state.failure_count >= self.config.failure_threshold:
|
|
191
236
|
self._state.state = CircuitState.OPEN
|
|
192
237
|
logger.warning(
|
|
193
|
-
"Circuit %s opened after %d failures",
|
|
238
|
+
"Circuit %s opened after %d failures (threshold=%d)",
|
|
194
239
|
self.name,
|
|
195
240
|
self._state.failure_count,
|
|
241
|
+
self.config.failure_threshold,
|
|
242
|
+
)
|
|
243
|
+
self._notify_state_change(
|
|
244
|
+
CircuitState.CLOSED,
|
|
245
|
+
CircuitState.OPEN,
|
|
196
246
|
)
|
|
197
247
|
|
|
198
248
|
case CircuitState.OPEN: # pragma: no branch
|
|
@@ -221,7 +271,7 @@ class CircuitBreaker:
|
|
|
221
271
|
result = func(*args, **kwargs)
|
|
222
272
|
self._record_success()
|
|
223
273
|
return result
|
|
224
|
-
except
|
|
274
|
+
except self.config.failure_exceptions as e:
|
|
225
275
|
self._record_failure(e)
|
|
226
276
|
raise
|
|
227
277
|
|
|
@@ -234,7 +284,9 @@ def circuit_breaker(
|
|
|
234
284
|
success_threshold: int = 2,
|
|
235
285
|
timeout: float = 30.0,
|
|
236
286
|
excluded_exceptions: tuple[type[Exception], ...] = (),
|
|
287
|
+
failure_exceptions: tuple[type[Exception], ...] = (Exception,),
|
|
237
288
|
name: str | None = None,
|
|
289
|
+
on_state_change: Callable[[CircuitState, CircuitState], None] | None = None,
|
|
238
290
|
) -> Callable[[Callable[P, R]], Callable[P, R]]:
|
|
239
291
|
"""Decorator to apply circuit breaker pattern.
|
|
240
292
|
|
|
@@ -243,7 +295,10 @@ def circuit_breaker(
|
|
|
243
295
|
success_threshold: Successes to close from half-open.
|
|
244
296
|
timeout: Seconds before attempting half-open.
|
|
245
297
|
excluded_exceptions: Exceptions that don't trip circuit.
|
|
298
|
+
failure_exceptions: Exceptions that count as failures.
|
|
246
299
|
name: Optional name for the circuit.
|
|
300
|
+
on_state_change: Optional callback invoked on state transitions
|
|
301
|
+
with (old_state, new_state).
|
|
247
302
|
|
|
248
303
|
Returns:
|
|
249
304
|
Decorated function with circuit breaker protection.
|
|
@@ -253,6 +308,13 @@ def circuit_breaker(
|
|
|
253
308
|
... def call_api(endpoint: str) -> dict:
|
|
254
309
|
... return requests.get(endpoint).json()
|
|
255
310
|
|
|
311
|
+
>>> @circuit_breaker(
|
|
312
|
+
... failure_threshold=3,
|
|
313
|
+
... on_state_change=lambda old, new: print(f"{old} -> {new}"),
|
|
314
|
+
... )
|
|
315
|
+
... def monitored_call() -> str:
|
|
316
|
+
... return service.call()
|
|
317
|
+
|
|
256
318
|
"""
|
|
257
319
|
|
|
258
320
|
def decorator(func: Callable[P, R]) -> Callable[P, R]:
|
|
@@ -261,7 +323,9 @@ def circuit_breaker(
|
|
|
261
323
|
success_threshold=success_threshold,
|
|
262
324
|
timeout=timeout,
|
|
263
325
|
excluded_exceptions=excluded_exceptions,
|
|
326
|
+
failure_exceptions=failure_exceptions,
|
|
264
327
|
name=name or func.__name__,
|
|
328
|
+
on_state_change=on_state_change,
|
|
265
329
|
)
|
|
266
330
|
return breaker(func)
|
|
267
331
|
|
|
@@ -281,6 +281,7 @@ def log_operation(
|
|
|
281
281
|
*,
|
|
282
282
|
logger: StackLogger | None = None,
|
|
283
283
|
level: str = "INFO",
|
|
284
|
+
expected_exceptions: tuple[type[Exception], ...] | type[Exception] = Exception,
|
|
284
285
|
) -> Any:
|
|
285
286
|
"""Context manager for logging operations.
|
|
286
287
|
|
|
@@ -288,6 +289,7 @@ def log_operation(
|
|
|
288
289
|
operation: Name of the operation.
|
|
289
290
|
logger: Logger to use (creates one if not provided).
|
|
290
291
|
level: Log level for messages.
|
|
292
|
+
expected_exceptions: Exceptions to catch and log as failures.
|
|
291
293
|
|
|
292
294
|
Yields:
|
|
293
295
|
The logger instance.
|
|
@@ -314,7 +316,7 @@ def log_operation(
|
|
|
314
316
|
yield logger
|
|
315
317
|
duration = (datetime.now(UTC) - start_time).total_seconds()
|
|
316
318
|
log_method(f"Completed: {operation}", duration_seconds=duration)
|
|
317
|
-
except
|
|
319
|
+
except expected_exceptions as e:
|
|
318
320
|
duration = (datetime.now(UTC) - start_time).total_seconds()
|
|
319
321
|
logger.exception(
|
|
320
322
|
f"Failed: {operation}",
|
|
@@ -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
|