taipanstack 0.3.11__tar.gz → 0.4.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.11 → taipanstack-0.4.1}/PKG-INFO +50 -4
- {taipanstack-0.3.11 → taipanstack-0.4.1}/README.md +30 -3
- {taipanstack-0.3.11 → taipanstack-0.4.1}/pyproject.toml +44 -6
- {taipanstack-0.3.11 → taipanstack-0.4.1}/src/taipanstack/__init__.py +1 -1
- taipanstack-0.4.1/src/taipanstack/bridges/__init__.py +31 -0
- taipanstack-0.4.1/src/taipanstack/bridges/_imports.py +68 -0
- taipanstack-0.4.1/src/taipanstack/bridges/db_bridge.py +253 -0
- taipanstack-0.4.1/src/taipanstack/bridges/http_bridge.py +317 -0
- taipanstack-0.4.1/src/taipanstack/bridges/web_bridge.py +234 -0
- {taipanstack-0.3.11 → taipanstack-0.4.1}/src/taipanstack/config/generators.py +0 -104
- {taipanstack-0.3.11 → taipanstack-0.4.1}/src/taipanstack/config/models.py +3 -0
- {taipanstack-0.3.11 → taipanstack-0.4.1}/src/taipanstack/core/optimizations.py +0 -21
- {taipanstack-0.3.11 → taipanstack-0.4.1}/src/taipanstack/core/result.py +54 -43
- taipanstack-0.4.1/src/taipanstack/resilience/__init__.py +71 -0
- taipanstack-0.4.1/src/taipanstack/resilience/adaptive/__init__.py +32 -0
- taipanstack-0.4.1/src/taipanstack/resilience/adaptive/adaptive_breaker.py +209 -0
- taipanstack-0.4.1/src/taipanstack/resilience/adaptive/adaptive_retry.py +186 -0
- taipanstack-0.4.1/src/taipanstack/resilience/adaptive/adaptive_timeout.py +177 -0
- taipanstack-0.4.1/src/taipanstack/resilience/adaptive/bulkhead.py +160 -0
- taipanstack-0.4.1/src/taipanstack/resilience/adaptive/orchestrator.py +371 -0
- {taipanstack-0.3.11/src/taipanstack/utils → taipanstack-0.4.1/src/taipanstack/resilience}/circuit_breaker.py +22 -2
- {taipanstack-0.3.11/src/taipanstack/utils → taipanstack-0.4.1/src/taipanstack/resilience}/resilience.py +2 -2
- {taipanstack-0.3.11/src/taipanstack/utils → taipanstack-0.4.1/src/taipanstack/resilience}/retry.py +2 -4
- taipanstack-0.4.1/src/taipanstack/resilience/watchdogs/__init__.py +36 -0
- taipanstack-0.4.1/src/taipanstack/resilience/watchdogs/_base.py +110 -0
- taipanstack-0.4.1/src/taipanstack/resilience/watchdogs/config_watcher.py +249 -0
- taipanstack-0.4.1/src/taipanstack/resilience/watchdogs/health_pinger.py +184 -0
- taipanstack-0.4.1/src/taipanstack/resilience/watchdogs/resource_watcher.py +155 -0
- {taipanstack-0.3.11 → taipanstack-0.4.1}/src/taipanstack/security/decorators.py +2 -2
- {taipanstack-0.3.11 → taipanstack-0.4.1}/src/taipanstack/security/guards.py +16 -2
- {taipanstack-0.3.11 → taipanstack-0.4.1}/src/taipanstack/security/jwt.py +7 -4
- {taipanstack-0.3.11 → taipanstack-0.4.1}/src/taipanstack/security/password.py +1 -1
- {taipanstack-0.3.11 → taipanstack-0.4.1}/src/taipanstack/security/sanitizers.py +104 -79
- {taipanstack-0.3.11 → taipanstack-0.4.1}/src/taipanstack/utils/cache.py +24 -10
- taipanstack-0.4.1/src/taipanstack/utils/circuit_breaker.py +30 -0
- {taipanstack-0.3.11 → taipanstack-0.4.1}/src/taipanstack/utils/concurrency.py +8 -10
- {taipanstack-0.3.11 → taipanstack-0.4.1}/src/taipanstack/utils/rate_limit.py +6 -8
- taipanstack-0.4.1/src/taipanstack/utils/resilience.py +27 -0
- taipanstack-0.4.1/src/taipanstack/utils/retry.py +29 -0
- {taipanstack-0.3.11 → taipanstack-0.4.1}/src/taipanstack/utils/subprocess.py +1 -1
- taipanstack-0.3.11/src/taipanstack/utils/metrics.py +0 -289
- {taipanstack-0.3.11 → taipanstack-0.4.1}/LICENSE +0 -0
- {taipanstack-0.3.11 → taipanstack-0.4.1}/src/taipanstack/config/__init__.py +0 -0
- {taipanstack-0.3.11 → taipanstack-0.4.1}/src/taipanstack/config/version_config.py +0 -0
- {taipanstack-0.3.11 → taipanstack-0.4.1}/src/taipanstack/core/__init__.py +0 -0
- {taipanstack-0.3.11 → taipanstack-0.4.1}/src/taipanstack/core/compat.py +0 -0
- {taipanstack-0.3.11 → taipanstack-0.4.1}/src/taipanstack/security/__init__.py +0 -0
- {taipanstack-0.3.11 → taipanstack-0.4.1}/src/taipanstack/security/models.py +0 -0
- {taipanstack-0.3.11 → taipanstack-0.4.1}/src/taipanstack/security/types.py +0 -0
- {taipanstack-0.3.11 → taipanstack-0.4.1}/src/taipanstack/security/validators.py +0 -0
- {taipanstack-0.3.11 → taipanstack-0.4.1}/src/taipanstack/utils/__init__.py +0 -0
- {taipanstack-0.3.11 → taipanstack-0.4.1}/src/taipanstack/utils/context.py +0 -0
- {taipanstack-0.3.11 → taipanstack-0.4.1}/src/taipanstack/utils/filesystem.py +0 -0
- {taipanstack-0.3.11 → taipanstack-0.4.1}/src/taipanstack/utils/logging.py +0 -0
- {taipanstack-0.3.11 → taipanstack-0.4.1}/src/taipanstack/utils/serialization.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: taipanstack
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.1
|
|
4
4
|
Summary: TaipanStack - Modular, secure, and scalable Python stack for robust development
|
|
5
5
|
License-Expression: MIT
|
|
6
6
|
License-File: LICENSE
|
|
@@ -18,15 +18,34 @@ Classifier: Programming Language :: Python :: 3.14
|
|
|
18
18
|
Classifier: Topic :: Software Development :: Quality Assurance
|
|
19
19
|
Classifier: Topic :: Security
|
|
20
20
|
Classifier: Typing :: Typed
|
|
21
|
+
Provides-Extra: all
|
|
22
|
+
Provides-Extra: bridges-db
|
|
23
|
+
Provides-Extra: bridges-http
|
|
24
|
+
Provides-Extra: bridges-web
|
|
25
|
+
Provides-Extra: resilience
|
|
21
26
|
Provides-Extra: runtime
|
|
22
27
|
Requires-Dist: argon2-cffi (>=25.1.0,<26.0.0)
|
|
23
28
|
Requires-Dist: email-validator (>=2.0.0)
|
|
29
|
+
Requires-Dist: fastapi (>=0.100.0) ; extra == "all"
|
|
30
|
+
Requires-Dist: fastapi (>=0.100.0) ; extra == "bridges-web"
|
|
31
|
+
Requires-Dist: httpx (>=0.24.0) ; extra == "all"
|
|
32
|
+
Requires-Dist: httpx (>=0.24.0) ; extra == "bridges-http"
|
|
33
|
+
Requires-Dist: litestar (>=2.0.0) ; extra == "all"
|
|
34
|
+
Requires-Dist: litestar (>=2.0.0) ; extra == "bridges-web"
|
|
24
35
|
Requires-Dist: orjson (>=3.9.0)
|
|
36
|
+
Requires-Dist: psutil (>=5.9.0) ; extra == "all"
|
|
37
|
+
Requires-Dist: psutil (>=5.9.0) ; extra == "resilience"
|
|
25
38
|
Requires-Dist: pydantic (>=2.0)
|
|
26
39
|
Requires-Dist: pydantic-settings (>=2.0.0)
|
|
27
40
|
Requires-Dist: pyjwt (>=2.11.0,<3.0.0)
|
|
41
|
+
Requires-Dist: redis (>=5.0.0) ; extra == "all"
|
|
42
|
+
Requires-Dist: redis (>=5.0.0) ; extra == "bridges-db"
|
|
28
43
|
Requires-Dist: result (>=0.17.0)
|
|
44
|
+
Requires-Dist: sqlalchemy (>=2.0.0) ; extra == "all"
|
|
45
|
+
Requires-Dist: sqlalchemy (>=2.0.0) ; extra == "bridges-db"
|
|
46
|
+
Requires-Dist: structlog (>=23.0.0) ; extra == "all"
|
|
29
47
|
Requires-Dist: structlog (>=23.0.0) ; extra == "runtime"
|
|
48
|
+
Requires-Dist: uvloop (>=0.19.0) ; (sys_platform != "win32") and (extra == "all")
|
|
30
49
|
Requires-Dist: uvloop (>=0.19.0) ; (sys_platform != "win32") and (extra == "runtime")
|
|
31
50
|
Project-URL: Changelog, https://github.com/gabrielima7/TaipanStack/blob/main/CHANGELOG.md
|
|
32
51
|
Project-URL: Documentation, https://gabrielima7.github.io/TaipanStack/
|
|
@@ -68,6 +87,11 @@ Description-Content-Type: text/markdown
|
|
|
68
87
|
|
|
69
88
|
TaipanStack is a battle-tested foundation for production-grade Python projects that combines **security**, **performance**, and **developer experience** into a single, cohesive toolkit.
|
|
70
89
|
|
|
90
|
+
### ✨ What's New in v0.4.0
|
|
91
|
+
- **Taipan Bridges**: Native ASGI middleware integrations (Rate Limiting, Security Headers) out of the box.
|
|
92
|
+
- **Adaptive Resilience**: Self-healing with AI-style failure thresholds and dynamic timeout tracking.
|
|
93
|
+
- **Watchdogs**: Active CPU/Memory monitoring, background Health Checks, and Hot Reload of settings via Pydantic.
|
|
94
|
+
|
|
71
95
|
<table>
|
|
72
96
|
<tr>
|
|
73
97
|
<td width="50%">
|
|
@@ -104,7 +128,7 @@ TaipanStack is a battle-tested foundation for production-grade Python projects t
|
|
|
104
128
|
|
|
105
129
|
### 🔧 Developer Experience
|
|
106
130
|
- Pre-configured quality tools
|
|
107
|
-
- **100% code coverage** (
|
|
131
|
+
- **100% code coverage** (1184 tests)
|
|
108
132
|
- Architecture enforcement
|
|
109
133
|
- Hardened Docker template
|
|
110
134
|
|
|
@@ -146,7 +170,7 @@ make all
|
|
|
146
170
|
### Verify Installation
|
|
147
171
|
|
|
148
172
|
```bash
|
|
149
|
-
# Run tests with 100% coverage (
|
|
173
|
+
# Run tests with 100% coverage (1184 tests)
|
|
150
174
|
make test
|
|
151
175
|
|
|
152
176
|
# Check architecture contracts
|
|
@@ -201,7 +225,7 @@ TaipanStack/
|
|
|
201
225
|
│ ├── config/ # ⚙️ Configuration models & generators
|
|
202
226
|
│ ├── security/ # 🛡️ Guards, sanitizers, validators
|
|
203
227
|
│ └── utils/ # 🔧 Logging, metrics, retry, filesystem
|
|
204
|
-
├── tests/ # ✅
|
|
228
|
+
├── tests/ # ✅ 1184 tests, 100% coverage
|
|
205
229
|
├── .semgrep/ # 🔍 Custom SAST rules
|
|
206
230
|
├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
|
|
207
231
|
├── Dockerfile # 🐳 Hardened multi-stage container
|
|
@@ -340,6 +364,28 @@ def fetch_user_profile(user_id: str) -> dict:
|
|
|
340
364
|
profile = unwrap_or(fetch_user_profile("usr_456"), {"name": "Unknown"})
|
|
341
365
|
```
|
|
342
366
|
|
|
367
|
+
### 🔗 Adaptive Resilience Pipeline
|
|
368
|
+
|
|
369
|
+
```python
|
|
370
|
+
from taipanstack.core.result import Result, Ok, Err
|
|
371
|
+
from taipanstack.resilience.adaptive import ResilienceOrchestrator, AdaptiveCircuitBreaker, AdaptiveTimeout
|
|
372
|
+
from taipanstack.resilience.retry import RetryConfig
|
|
373
|
+
|
|
374
|
+
# Compose an intelligent pipeline: Bulkhead -> Breaker -> Retry -> Timeout -> Fallback
|
|
375
|
+
orch = (
|
|
376
|
+
ResilienceOrchestrator("billing_api")
|
|
377
|
+
.with_bulkhead(max_concurrent=10, max_queue=50) # Prevent resource exhaustion
|
|
378
|
+
.with_circuit_breaker(AdaptiveCircuitBreaker("billing", target_error_rate=0.1)) # Auto-tunes thresholds
|
|
379
|
+
.with_timeout(AdaptiveTimeout(min_timeout=1.0, max_timeout=10.0))
|
|
380
|
+
.with_retry(RetryConfig(max_attempts=3, initial_delay=0.1))
|
|
381
|
+
.with_fallback({"status": "unavailable"})
|
|
382
|
+
)
|
|
383
|
+
|
|
384
|
+
async def process_billing() -> Result[dict, Exception]:
|
|
385
|
+
# The orchestrator handles all concurrency, retry, circuit breaking, and fallbacks
|
|
386
|
+
return await orch.execute(stripe_gateway.charge)
|
|
387
|
+
```
|
|
388
|
+
|
|
343
389
|
### Intelligent Caching
|
|
344
390
|
|
|
345
391
|
```python
|
|
@@ -31,6 +31,11 @@
|
|
|
31
31
|
|
|
32
32
|
TaipanStack is a battle-tested foundation for production-grade Python projects that combines **security**, **performance**, and **developer experience** into a single, cohesive toolkit.
|
|
33
33
|
|
|
34
|
+
### ✨ What's New in v0.4.0
|
|
35
|
+
- **Taipan Bridges**: Native ASGI middleware integrations (Rate Limiting, Security Headers) out of the box.
|
|
36
|
+
- **Adaptive Resilience**: Self-healing with AI-style failure thresholds and dynamic timeout tracking.
|
|
37
|
+
- **Watchdogs**: Active CPU/Memory monitoring, background Health Checks, and Hot Reload of settings via Pydantic.
|
|
38
|
+
|
|
34
39
|
<table>
|
|
35
40
|
<tr>
|
|
36
41
|
<td width="50%">
|
|
@@ -67,7 +72,7 @@ TaipanStack is a battle-tested foundation for production-grade Python projects t
|
|
|
67
72
|
|
|
68
73
|
### 🔧 Developer Experience
|
|
69
74
|
- Pre-configured quality tools
|
|
70
|
-
- **100% code coverage** (
|
|
75
|
+
- **100% code coverage** (1184 tests)
|
|
71
76
|
- Architecture enforcement
|
|
72
77
|
- Hardened Docker template
|
|
73
78
|
|
|
@@ -109,7 +114,7 @@ make all
|
|
|
109
114
|
### Verify Installation
|
|
110
115
|
|
|
111
116
|
```bash
|
|
112
|
-
# Run tests with 100% coverage (
|
|
117
|
+
# Run tests with 100% coverage (1184 tests)
|
|
113
118
|
make test
|
|
114
119
|
|
|
115
120
|
# Check architecture contracts
|
|
@@ -164,7 +169,7 @@ TaipanStack/
|
|
|
164
169
|
│ ├── config/ # ⚙️ Configuration models & generators
|
|
165
170
|
│ ├── security/ # 🛡️ Guards, sanitizers, validators
|
|
166
171
|
│ └── utils/ # 🔧 Logging, metrics, retry, filesystem
|
|
167
|
-
├── tests/ # ✅
|
|
172
|
+
├── tests/ # ✅ 1184 tests, 100% coverage
|
|
168
173
|
├── .semgrep/ # 🔍 Custom SAST rules
|
|
169
174
|
├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
|
|
170
175
|
├── Dockerfile # 🐳 Hardened multi-stage container
|
|
@@ -303,6 +308,28 @@ def fetch_user_profile(user_id: str) -> dict:
|
|
|
303
308
|
profile = unwrap_or(fetch_user_profile("usr_456"), {"name": "Unknown"})
|
|
304
309
|
```
|
|
305
310
|
|
|
311
|
+
### 🔗 Adaptive Resilience Pipeline
|
|
312
|
+
|
|
313
|
+
```python
|
|
314
|
+
from taipanstack.core.result import Result, Ok, Err
|
|
315
|
+
from taipanstack.resilience.adaptive import ResilienceOrchestrator, AdaptiveCircuitBreaker, AdaptiveTimeout
|
|
316
|
+
from taipanstack.resilience.retry import RetryConfig
|
|
317
|
+
|
|
318
|
+
# Compose an intelligent pipeline: Bulkhead -> Breaker -> Retry -> Timeout -> Fallback
|
|
319
|
+
orch = (
|
|
320
|
+
ResilienceOrchestrator("billing_api")
|
|
321
|
+
.with_bulkhead(max_concurrent=10, max_queue=50) # Prevent resource exhaustion
|
|
322
|
+
.with_circuit_breaker(AdaptiveCircuitBreaker("billing", target_error_rate=0.1)) # Auto-tunes thresholds
|
|
323
|
+
.with_timeout(AdaptiveTimeout(min_timeout=1.0, max_timeout=10.0))
|
|
324
|
+
.with_retry(RetryConfig(max_attempts=3, initial_delay=0.1))
|
|
325
|
+
.with_fallback({"status": "unavailable"})
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
async def process_billing() -> Result[dict, Exception]:
|
|
329
|
+
# The orchestrator handles all concurrency, retry, circuit breaking, and fallbacks
|
|
330
|
+
return await orch.execute(stripe_gateway.charge)
|
|
331
|
+
```
|
|
332
|
+
|
|
306
333
|
### Intelligent Caching
|
|
307
334
|
|
|
308
335
|
```python
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "taipanstack"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.4.1"
|
|
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"}
|
|
@@ -44,6 +44,35 @@ runtime = [
|
|
|
44
44
|
"uvloop (>=0.19.0); sys_platform != 'win32'",
|
|
45
45
|
"structlog (>=23.0.0)",
|
|
46
46
|
]
|
|
47
|
+
bridges-web = [
|
|
48
|
+
"fastapi (>=0.100.0)",
|
|
49
|
+
"litestar (>=2.0.0)",
|
|
50
|
+
]
|
|
51
|
+
bridges-http = [
|
|
52
|
+
"httpx (>=0.24.0)",
|
|
53
|
+
]
|
|
54
|
+
bridges-db = [
|
|
55
|
+
"sqlalchemy (>=2.0.0)",
|
|
56
|
+
"redis (>=5.0.0)",
|
|
57
|
+
]
|
|
58
|
+
resilience = [
|
|
59
|
+
"psutil (>=5.9.0)",
|
|
60
|
+
]
|
|
61
|
+
all = [
|
|
62
|
+
# runtime
|
|
63
|
+
"uvloop (>=0.19.0); sys_platform != 'win32'",
|
|
64
|
+
"structlog (>=23.0.0)",
|
|
65
|
+
# bridges-web
|
|
66
|
+
"fastapi (>=0.100.0)",
|
|
67
|
+
"litestar (>=2.0.0)",
|
|
68
|
+
# bridges-http
|
|
69
|
+
"httpx (>=0.24.0)",
|
|
70
|
+
# bridges-db
|
|
71
|
+
"sqlalchemy (>=2.0.0)",
|
|
72
|
+
"redis (>=5.0.0)",
|
|
73
|
+
# resilience
|
|
74
|
+
"psutil (>=5.9.0)",
|
|
75
|
+
]
|
|
47
76
|
|
|
48
77
|
[build-system]
|
|
49
78
|
requires = ["poetry-core>=2.0.0,<3.0.0"]
|
|
@@ -71,6 +100,13 @@ dev = [
|
|
|
71
100
|
"pytest-asyncio (>=0.23.0)",
|
|
72
101
|
"radon (>=6.0.1,<7.0.0)",
|
|
73
102
|
"pip-audit (>=2.10.0,<3.0.0)",
|
|
103
|
+
# Security: CVE fix - requests <2.33.0 has insecure temp file reuse (CWE-377)
|
|
104
|
+
# Dependabot alert #17 - CVSS 4.4/10 Moderate
|
|
105
|
+
"requests (>=2.33.0)",
|
|
106
|
+
# Security note: Pygments <=2.19.2 has ReDoS via AdILexer (Dependabot alert #16)
|
|
107
|
+
# CVSS 1.9/10 Low - local attack vector only, no upstream patch available yet
|
|
108
|
+
# Pinned to latest available; monitor for upstream fix in pygments >2.19.2
|
|
109
|
+
"pygments (>=2.19.2)",
|
|
74
110
|
]
|
|
75
111
|
|
|
76
112
|
|
|
@@ -132,11 +168,13 @@ max-complexity = 10
|
|
|
132
168
|
"src/taipanstack/security/sanitizers.py" = ["PLR0912"]
|
|
133
169
|
# Decorators: allow inline imports for lazy loading, unused signal args, D401 imperative mood
|
|
134
170
|
"src/taipanstack/security/decorators.py" = ["PLC0415", "ARG001", "D401"]
|
|
135
|
-
# Circuit breaker and metrics: allow D401 for decorator docstrings
|
|
136
|
-
"src/taipanstack/utils/circuit_breaker.py" = ["D401"]
|
|
137
|
-
"src/taipanstack/utils/metrics.py" = ["D401"]
|
|
138
171
|
# Core result: allow D401 for utility function docstrings
|
|
139
172
|
"src/taipanstack/core/result.py" = ["D401"]
|
|
173
|
+
# Resilience module: allow D401, too many args, random for jitter
|
|
174
|
+
"src/taipanstack/resilience/*.py" = ["PLR0913", "D401", "S311", "TRY300", "TRY400"]
|
|
175
|
+
"src/taipanstack/resilience/watchdogs/*.py" = ["PLR0913", "D401", "TRY300", "TRY400"]
|
|
176
|
+
"src/taipanstack/resilience/adaptive/*.py" = ["PLR0913", "PLR0912", "D401", "TRY300", "TRY400"]
|
|
177
|
+
"src/taipanstack/bridges/*.py" = ["PLR0913", "D401", "TRY300", "TRY400"]
|
|
140
178
|
|
|
141
179
|
[tool.ruff.format]
|
|
142
180
|
quote-style = "double"
|
|
@@ -174,7 +212,7 @@ warn_required_dynamic_aliases = true
|
|
|
174
212
|
|
|
175
213
|
[tool.pytest.ini_options]
|
|
176
214
|
testpaths = ["tests"]
|
|
177
|
-
addopts = "-v
|
|
215
|
+
addopts = "-v --strict-markers --timeout=30"
|
|
178
216
|
asyncio_mode = "auto"
|
|
179
217
|
markers = [
|
|
180
218
|
"slow: marks tests as slow (deselect with '-m \"not slow\"')",
|
|
@@ -229,7 +267,7 @@ fail-under = 80
|
|
|
229
267
|
verbose = 1
|
|
230
268
|
|
|
231
269
|
[tool.mutmut]
|
|
232
|
-
paths_to_mutate = "src/taipanstack/security/sanitizers.py,src/taipanstack/security/validators.py,src/taipanstack/security/guards.py,src/taipanstack/
|
|
270
|
+
paths_to_mutate = "src/taipanstack/security/sanitizers.py,src/taipanstack/security/validators.py,src/taipanstack/security/guards.py,src/taipanstack/resilience/retry.py,src/taipanstack/resilience/circuit_breaker.py"
|
|
233
271
|
tests_dir = "tests/test_property_sanitizers.py,tests/test_security_validators.py,tests/test_security_guards.py,tests/test_security_ssrf.py,tests/test_utils_retry.py,tests/test_utils_circuit_breaker.py"
|
|
234
272
|
runner = "python -m pytest -x -q --tb=no --timeout=10 --no-cov"
|
|
235
273
|
dict_synonyms = "Struct, NamedStruct"
|
|
@@ -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__ = "0.
|
|
8
|
+
__version__ = "0.4.1"
|
|
9
9
|
|
|
10
10
|
from taipanstack.config.version_config import (
|
|
11
11
|
VersionRecommendations,
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Taipan Bridges — universal integration layer.
|
|
2
|
+
|
|
3
|
+
Provides adapters connecting TaipanStack's security, resilience,
|
|
4
|
+
and error handling with popular Python libraries.
|
|
5
|
+
|
|
6
|
+
Sub-modules:
|
|
7
|
+
http_bridge: Safe httpx client with SSRF protection.
|
|
8
|
+
web_bridge: ASGI middleware for rate limiting / security headers.
|
|
9
|
+
db_bridge: Resilient SQLAlchemy / Redis wrappers.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from taipanstack.bridges._imports import get_attr_or_err, require_dependency
|
|
13
|
+
from taipanstack.bridges.db_bridge import ResilientDatabase, ResilientRedis
|
|
14
|
+
from taipanstack.bridges.http_bridge import SafeHttpClient, safe_request
|
|
15
|
+
from taipanstack.bridges.web_bridge import (
|
|
16
|
+
SecurityHeadersConfig,
|
|
17
|
+
TaipanMiddleware,
|
|
18
|
+
result_to_response,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
__all__ = (
|
|
22
|
+
"ResilientDatabase",
|
|
23
|
+
"ResilientRedis",
|
|
24
|
+
"SafeHttpClient",
|
|
25
|
+
"SecurityHeadersConfig",
|
|
26
|
+
"TaipanMiddleware",
|
|
27
|
+
"get_attr_or_err",
|
|
28
|
+
"require_dependency",
|
|
29
|
+
"result_to_response",
|
|
30
|
+
"safe_request",
|
|
31
|
+
)
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Lazy optional import helpers for Taipan Bridges.
|
|
3
|
+
|
|
4
|
+
Provides a centralised mechanism to handle optional dependencies
|
|
5
|
+
that may or may not be installed at runtime.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import importlib
|
|
9
|
+
import types
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from taipanstack.core.result import Err, Ok, Result
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def require_dependency(
|
|
16
|
+
module_name: str,
|
|
17
|
+
*,
|
|
18
|
+
pip_extra: str = "",
|
|
19
|
+
) -> Result[types.ModuleType, ImportError]:
|
|
20
|
+
"""Attempt to import *module_name* and return a ``Result``.
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
module_name: Dotted module path (e.g. ``"httpx"``).
|
|
24
|
+
pip_extra: Optional pip extra name for the error message.
|
|
25
|
+
|
|
26
|
+
Returns:
|
|
27
|
+
``Ok(module)`` if available, ``Err(ImportError)`` otherwise.
|
|
28
|
+
|
|
29
|
+
Example:
|
|
30
|
+
>>> require_dependency("httpx", pip_extra="bridges-http")
|
|
31
|
+
Ok(<module 'httpx' ...>)
|
|
32
|
+
|
|
33
|
+
"""
|
|
34
|
+
try:
|
|
35
|
+
mod = importlib.import_module(module_name)
|
|
36
|
+
return Ok(mod)
|
|
37
|
+
except ImportError:
|
|
38
|
+
install_hint = (
|
|
39
|
+
f"pip install taipanstack[{pip_extra}]"
|
|
40
|
+
if pip_extra
|
|
41
|
+
else f"pip install {module_name}"
|
|
42
|
+
)
|
|
43
|
+
return Err(
|
|
44
|
+
ImportError(
|
|
45
|
+
f"'{module_name}' is required but not installed. "
|
|
46
|
+
f"Install with: {install_hint}"
|
|
47
|
+
)
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def get_attr_or_err(
|
|
52
|
+
module: types.ModuleType,
|
|
53
|
+
name: str,
|
|
54
|
+
) -> Result[Any, AttributeError]:
|
|
55
|
+
"""Safely access an attribute from a module.
|
|
56
|
+
|
|
57
|
+
Args:
|
|
58
|
+
module: The imported module.
|
|
59
|
+
name: Attribute name to retrieve.
|
|
60
|
+
|
|
61
|
+
Returns:
|
|
62
|
+
``Ok(attr)`` if found, ``Err(AttributeError)`` otherwise.
|
|
63
|
+
|
|
64
|
+
"""
|
|
65
|
+
try:
|
|
66
|
+
return Ok(getattr(module, name))
|
|
67
|
+
except AttributeError as exc:
|
|
68
|
+
return Err(exc)
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
"""
|
|
2
|
+
DB Bridge — resilient database wrappers.
|
|
3
|
+
|
|
4
|
+
Wraps SQLAlchemy async engine and Redis async client with
|
|
5
|
+
TaipanStack's circuit breaker and retry patterns.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import logging
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from taipanstack.core.result import Err, Ok, Result
|
|
15
|
+
from taipanstack.resilience.circuit_breaker import (
|
|
16
|
+
CircuitBreaker,
|
|
17
|
+
CircuitBreakerError,
|
|
18
|
+
CircuitState,
|
|
19
|
+
)
|
|
20
|
+
from taipanstack.resilience.retry import RetryConfig, calculate_delay
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger("taipanstack.bridges.db")
|
|
23
|
+
|
|
24
|
+
# --- optional imports ------------------------------------------------------
|
|
25
|
+
|
|
26
|
+
try:
|
|
27
|
+
import sqlalchemy # noqa: F401
|
|
28
|
+
from sqlalchemy import text as sa_text # pragma: no cover
|
|
29
|
+
from sqlalchemy.ext.asyncio import AsyncSession # pragma: no cover
|
|
30
|
+
|
|
31
|
+
_HAS_SQLALCHEMY = True # pragma: no cover
|
|
32
|
+
except ImportError: # pragma: no cover
|
|
33
|
+
_HAS_SQLALCHEMY = False
|
|
34
|
+
|
|
35
|
+
try:
|
|
36
|
+
import redis.asyncio as aioredis # noqa: F401
|
|
37
|
+
|
|
38
|
+
_HAS_REDIS = True # pragma: no cover
|
|
39
|
+
except ImportError: # pragma: no cover
|
|
40
|
+
_HAS_REDIS = False
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _breaker_is_open(cb: CircuitBreaker) -> CircuitBreakerError | None:
|
|
44
|
+
"""Return a ``CircuitBreakerError`` if the breaker is OPEN.
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
cb: The circuit breaker to check.
|
|
48
|
+
|
|
49
|
+
Returns:
|
|
50
|
+
Error if open, ``None`` otherwise.
|
|
51
|
+
|
|
52
|
+
"""
|
|
53
|
+
if cb.state == CircuitState.OPEN:
|
|
54
|
+
return CircuitBreakerError(
|
|
55
|
+
f"Circuit breaker '{cb.name}' is OPEN",
|
|
56
|
+
state=cb.state,
|
|
57
|
+
)
|
|
58
|
+
return None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class ResilientDatabase:
|
|
62
|
+
"""Wraps a SQLAlchemy async engine with resilience patterns.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
engine: SQLAlchemy ``AsyncEngine`` instance.
|
|
66
|
+
circuit_breaker: Optional circuit breaker.
|
|
67
|
+
retry_config: Optional retry configuration.
|
|
68
|
+
|
|
69
|
+
Example:
|
|
70
|
+
>>> db = ResilientDatabase(engine, circuit_breaker=breaker)
|
|
71
|
+
>>> result = await db.execute(text("SELECT 1"))
|
|
72
|
+
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
def __init__(
|
|
76
|
+
self,
|
|
77
|
+
engine: Any,
|
|
78
|
+
*,
|
|
79
|
+
circuit_breaker: CircuitBreaker | None = None,
|
|
80
|
+
retry_config: RetryConfig | None = None,
|
|
81
|
+
) -> None:
|
|
82
|
+
"""Initialize the resilient database wrapper.
|
|
83
|
+
|
|
84
|
+
Args:
|
|
85
|
+
engine: SQLAlchemy AsyncEngine.
|
|
86
|
+
circuit_breaker: Optional circuit breaker.
|
|
87
|
+
retry_config: Optional retry config.
|
|
88
|
+
|
|
89
|
+
"""
|
|
90
|
+
self._engine = engine
|
|
91
|
+
self._circuit_breaker = circuit_breaker
|
|
92
|
+
self._retry_config = retry_config
|
|
93
|
+
|
|
94
|
+
async def execute(
|
|
95
|
+
self,
|
|
96
|
+
statement: Any,
|
|
97
|
+
**kwargs: Any,
|
|
98
|
+
) -> Result[Any, Exception]:
|
|
99
|
+
"""Execute a SQL statement with resilience.
|
|
100
|
+
|
|
101
|
+
Args:
|
|
102
|
+
statement: SQLAlchemy statement to execute.
|
|
103
|
+
**kwargs: Passed to ``session.execute``.
|
|
104
|
+
|
|
105
|
+
Returns:
|
|
106
|
+
``Ok(result)`` on success, ``Err`` on failure.
|
|
107
|
+
|
|
108
|
+
"""
|
|
109
|
+
if not _HAS_SQLALCHEMY:
|
|
110
|
+
return Err(
|
|
111
|
+
ImportError(
|
|
112
|
+
"sqlalchemy is required for ResilientDatabase. "
|
|
113
|
+
"Install with: pip install taipanstack[bridges-db]"
|
|
114
|
+
)
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
# Circuit breaker gate
|
|
118
|
+
if self._circuit_breaker is not None:
|
|
119
|
+
cb_err = _breaker_is_open(self._circuit_breaker)
|
|
120
|
+
if cb_err is not None:
|
|
121
|
+
return Err(cb_err)
|
|
122
|
+
|
|
123
|
+
max_attempts = 1
|
|
124
|
+
if self._retry_config is not None:
|
|
125
|
+
max_attempts = self._retry_config.max_attempts
|
|
126
|
+
|
|
127
|
+
last_error: Exception | None = None
|
|
128
|
+
|
|
129
|
+
for attempt in range(1, max_attempts + 1):
|
|
130
|
+
try:
|
|
131
|
+
async with AsyncSession(self._engine) as session:
|
|
132
|
+
result = await session.execute(statement, **kwargs)
|
|
133
|
+
return Ok(result)
|
|
134
|
+
except Exception as exc:
|
|
135
|
+
last_error = exc
|
|
136
|
+
logger.warning(
|
|
137
|
+
"DB execute attempt %d failed: %s",
|
|
138
|
+
attempt,
|
|
139
|
+
exc,
|
|
140
|
+
)
|
|
141
|
+
if self._circuit_breaker is not None:
|
|
142
|
+
self._circuit_breaker._record_failure(exc)
|
|
143
|
+
if self._retry_config is not None and attempt < max_attempts:
|
|
144
|
+
delay = calculate_delay(attempt, self._retry_config)
|
|
145
|
+
await asyncio.sleep(delay)
|
|
146
|
+
continue
|
|
147
|
+
break
|
|
148
|
+
|
|
149
|
+
return Err(last_error or RuntimeError("Database execute failed"))
|
|
150
|
+
|
|
151
|
+
async def health_check(self) -> Result[bool, Exception]:
|
|
152
|
+
"""Check database connectivity.
|
|
153
|
+
|
|
154
|
+
Executes ``SELECT 1`` to verify the connection is alive.
|
|
155
|
+
|
|
156
|
+
Returns:
|
|
157
|
+
``Ok(True)`` if healthy, ``Err`` on failure.
|
|
158
|
+
|
|
159
|
+
"""
|
|
160
|
+
if not _HAS_SQLALCHEMY:
|
|
161
|
+
return Err(ImportError("sqlalchemy is required for health check"))
|
|
162
|
+
|
|
163
|
+
try:
|
|
164
|
+
async with AsyncSession(self._engine) as session:
|
|
165
|
+
await session.execute(sa_text("SELECT 1"))
|
|
166
|
+
return Ok(True)
|
|
167
|
+
except Exception as exc:
|
|
168
|
+
return Err(exc)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
class ResilientRedis:
|
|
172
|
+
"""Wraps a Redis async client with resilience patterns.
|
|
173
|
+
|
|
174
|
+
Args:
|
|
175
|
+
client: ``redis.asyncio.Redis`` instance.
|
|
176
|
+
circuit_breaker: Optional circuit breaker.
|
|
177
|
+
|
|
178
|
+
Example:
|
|
179
|
+
>>> r = ResilientRedis(redis_client, circuit_breaker=breaker)
|
|
180
|
+
>>> result = await r.execute("GET", "my_key")
|
|
181
|
+
|
|
182
|
+
"""
|
|
183
|
+
|
|
184
|
+
def __init__(
|
|
185
|
+
self,
|
|
186
|
+
client: Any,
|
|
187
|
+
*,
|
|
188
|
+
circuit_breaker: CircuitBreaker | None = None,
|
|
189
|
+
) -> None:
|
|
190
|
+
"""Initialize the resilient Redis wrapper.
|
|
191
|
+
|
|
192
|
+
Args:
|
|
193
|
+
client: Redis async client.
|
|
194
|
+
circuit_breaker: Optional circuit breaker.
|
|
195
|
+
|
|
196
|
+
"""
|
|
197
|
+
self._client = client
|
|
198
|
+
self._circuit_breaker = circuit_breaker
|
|
199
|
+
|
|
200
|
+
async def execute(
|
|
201
|
+
self,
|
|
202
|
+
command: str,
|
|
203
|
+
*args: Any,
|
|
204
|
+
) -> Result[Any, Exception]:
|
|
205
|
+
"""Execute a Redis command with resilience.
|
|
206
|
+
|
|
207
|
+
Args:
|
|
208
|
+
command: Redis command name (e.g. ``"GET"``, ``"SET"``).
|
|
209
|
+
*args: Command arguments.
|
|
210
|
+
|
|
211
|
+
Returns:
|
|
212
|
+
``Ok(result)`` on success, ``Err`` on failure.
|
|
213
|
+
|
|
214
|
+
"""
|
|
215
|
+
if not _HAS_REDIS:
|
|
216
|
+
return Err(
|
|
217
|
+
ImportError(
|
|
218
|
+
"redis is required for ResilientRedis. "
|
|
219
|
+
"Install with: pip install taipanstack[bridges-db]"
|
|
220
|
+
)
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
# Circuit breaker gate
|
|
224
|
+
if self._circuit_breaker is not None:
|
|
225
|
+
cb_err = _breaker_is_open(self._circuit_breaker)
|
|
226
|
+
if cb_err is not None:
|
|
227
|
+
return Err(cb_err)
|
|
228
|
+
|
|
229
|
+
try:
|
|
230
|
+
fn = getattr(self._client, command.lower())
|
|
231
|
+
result = await fn(*args)
|
|
232
|
+
return Ok(result)
|
|
233
|
+
except Exception as exc:
|
|
234
|
+
logger.warning("Redis command '%s' failed: %s", command, exc)
|
|
235
|
+
if self._circuit_breaker is not None:
|
|
236
|
+
self._circuit_breaker._record_failure(exc)
|
|
237
|
+
return Err(exc)
|
|
238
|
+
|
|
239
|
+
async def health_check(self) -> Result[bool, Exception]:
|
|
240
|
+
"""Check Redis connectivity via PING.
|
|
241
|
+
|
|
242
|
+
Returns:
|
|
243
|
+
``Ok(True)`` if healthy, ``Err`` on failure.
|
|
244
|
+
|
|
245
|
+
"""
|
|
246
|
+
if not _HAS_REDIS:
|
|
247
|
+
return Err(ImportError("redis is required for health check"))
|
|
248
|
+
|
|
249
|
+
try:
|
|
250
|
+
pong = await self._client.ping()
|
|
251
|
+
return Ok(bool(pong))
|
|
252
|
+
except Exception as exc:
|
|
253
|
+
return Err(exc)
|