taipanstack 0.4.1__tar.gz → 0.4.3__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.4.1 → taipanstack-0.4.3}/PKG-INFO +8 -8
- {taipanstack-0.4.1 → taipanstack-0.4.3}/README.md +7 -7
- {taipanstack-0.4.1 → taipanstack-0.4.3}/pyproject.toml +7 -6
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/__init__.py +1 -1
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/bridges/_imports.py +1 -2
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/bridges/db_bridge.py +45 -32
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/bridges/http_bridge.py +144 -42
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/bridges/web_bridge.py +13 -10
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/core/result.py +19 -16
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/resilience/adaptive/adaptive_breaker.py +7 -2
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/resilience/adaptive/bulkhead.py +10 -5
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/resilience/adaptive/orchestrator.py +27 -21
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/resilience/circuit_breaker.py +34 -10
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/resilience/resilience.py +23 -8
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/resilience/retry.py +47 -25
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/resilience/watchdogs/_base.py +1 -2
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/resilience/watchdogs/config_watcher.py +5 -6
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/resilience/watchdogs/health_pinger.py +43 -36
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/security/decorators.py +15 -8
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/security/guards.py +29 -66
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/security/models.py +20 -18
- taipanstack-0.4.3/src/taipanstack/security/password.py +139 -0
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/security/sanitizers.py +93 -38
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/security/validators.py +73 -27
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/utils/cache.py +30 -21
- taipanstack-0.4.3/src/taipanstack/utils/filesystem.py +311 -0
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/utils/logging.py +21 -19
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/utils/rate_limit.py +24 -5
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/utils/subprocess.py +30 -12
- taipanstack-0.4.1/src/taipanstack/resilience/adaptive/adaptive_timeout.py +0 -177
- taipanstack-0.4.1/src/taipanstack/security/password.py +0 -94
- taipanstack-0.4.1/src/taipanstack/utils/filesystem.py +0 -456
- {taipanstack-0.4.1 → taipanstack-0.4.3}/LICENSE +0 -0
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/bridges/__init__.py +0 -0
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/config/__init__.py +0 -0
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/config/generators.py +0 -0
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/config/models.py +0 -0
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/config/version_config.py +0 -0
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/core/__init__.py +0 -0
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/core/compat.py +0 -0
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/core/optimizations.py +0 -0
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/resilience/__init__.py +0 -0
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/resilience/adaptive/__init__.py +0 -0
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/resilience/adaptive/adaptive_retry.py +0 -0
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/resilience/watchdogs/__init__.py +0 -0
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/resilience/watchdogs/resource_watcher.py +0 -0
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/security/__init__.py +0 -0
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/security/jwt.py +0 -0
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/security/types.py +0 -0
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/utils/__init__.py +0 -0
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/utils/circuit_breaker.py +0 -0
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/utils/concurrency.py +0 -0
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/utils/context.py +0 -0
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/utils/resilience.py +0 -0
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/utils/retry.py +0 -0
- {taipanstack-0.4.1 → taipanstack-0.4.3}/src/taipanstack/utils/serialization.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: taipanstack
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.3
|
|
4
4
|
Summary: TaipanStack - Modular, secure, and scalable Python stack for robust development
|
|
5
5
|
License-Expression: MIT
|
|
6
6
|
License-File: LICENSE
|
|
@@ -87,10 +87,10 @@ Description-Content-Type: text/markdown
|
|
|
87
87
|
|
|
88
88
|
TaipanStack is a battle-tested foundation for production-grade Python projects that combines **security**, **performance**, and **developer experience** into a single, cohesive toolkit.
|
|
89
89
|
|
|
90
|
-
### ✨ What's New in v0.4.
|
|
91
|
-
- **
|
|
92
|
-
- **
|
|
93
|
-
- **
|
|
90
|
+
### ✨ What's New in v0.4.3
|
|
91
|
+
- **Strict Static Typing**: Project-wide refactoring to eliminate all `Any` types, ensuring 100% type safety with `Mypy` strict mode.
|
|
92
|
+
- **SSRF & DoS Hardening**: Mitigates `urlparse` SSRF risks and algorithmic complexity DoS via bounded length and value validation.
|
|
93
|
+
- **Total Core Coverage**: Achieved true 100% branch and statement coverage in the core result module with 1,205 passing tests.
|
|
94
94
|
|
|
95
95
|
<table>
|
|
96
96
|
<tr>
|
|
@@ -128,7 +128,7 @@ TaipanStack is a battle-tested foundation for production-grade Python projects t
|
|
|
128
128
|
|
|
129
129
|
### 🔧 Developer Experience
|
|
130
130
|
- Pre-configured quality tools
|
|
131
|
-
- **100% code coverage** (
|
|
131
|
+
- **100% code coverage** (1205 tests)
|
|
132
132
|
- Architecture enforcement
|
|
133
133
|
- Hardened Docker template
|
|
134
134
|
|
|
@@ -170,7 +170,7 @@ make all
|
|
|
170
170
|
### Verify Installation
|
|
171
171
|
|
|
172
172
|
```bash
|
|
173
|
-
# Run tests with 100% coverage (
|
|
173
|
+
# Run tests with 100% coverage (1205 tests)
|
|
174
174
|
make test
|
|
175
175
|
|
|
176
176
|
# Check architecture contracts
|
|
@@ -225,7 +225,7 @@ TaipanStack/
|
|
|
225
225
|
│ ├── config/ # ⚙️ Configuration models & generators
|
|
226
226
|
│ ├── security/ # 🛡️ Guards, sanitizers, validators
|
|
227
227
|
│ └── utils/ # 🔧 Logging, metrics, retry, filesystem
|
|
228
|
-
├── tests/ # ✅
|
|
228
|
+
├── tests/ # ✅ 1205 tests, 100% coverage
|
|
229
229
|
├── .semgrep/ # 🔍 Custom SAST rules
|
|
230
230
|
├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
|
|
231
231
|
├── Dockerfile # 🐳 Hardened multi-stage container
|
|
@@ -31,10 +31,10 @@
|
|
|
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.
|
|
35
|
-
- **
|
|
36
|
-
- **
|
|
37
|
-
- **
|
|
34
|
+
### ✨ What's New in v0.4.3
|
|
35
|
+
- **Strict Static Typing**: Project-wide refactoring to eliminate all `Any` types, ensuring 100% type safety with `Mypy` strict mode.
|
|
36
|
+
- **SSRF & DoS Hardening**: Mitigates `urlparse` SSRF risks and algorithmic complexity DoS via bounded length and value validation.
|
|
37
|
+
- **Total Core Coverage**: Achieved true 100% branch and statement coverage in the core result module with 1,205 passing tests.
|
|
38
38
|
|
|
39
39
|
<table>
|
|
40
40
|
<tr>
|
|
@@ -72,7 +72,7 @@ TaipanStack is a battle-tested foundation for production-grade Python projects t
|
|
|
72
72
|
|
|
73
73
|
### 🔧 Developer Experience
|
|
74
74
|
- Pre-configured quality tools
|
|
75
|
-
- **100% code coverage** (
|
|
75
|
+
- **100% code coverage** (1205 tests)
|
|
76
76
|
- Architecture enforcement
|
|
77
77
|
- Hardened Docker template
|
|
78
78
|
|
|
@@ -114,7 +114,7 @@ make all
|
|
|
114
114
|
### Verify Installation
|
|
115
115
|
|
|
116
116
|
```bash
|
|
117
|
-
# Run tests with 100% coverage (
|
|
117
|
+
# Run tests with 100% coverage (1205 tests)
|
|
118
118
|
make test
|
|
119
119
|
|
|
120
120
|
# Check architecture contracts
|
|
@@ -169,7 +169,7 @@ TaipanStack/
|
|
|
169
169
|
│ ├── config/ # ⚙️ Configuration models & generators
|
|
170
170
|
│ ├── security/ # 🛡️ Guards, sanitizers, validators
|
|
171
171
|
│ └── utils/ # 🔧 Logging, metrics, retry, filesystem
|
|
172
|
-
├── tests/ # ✅
|
|
172
|
+
├── tests/ # ✅ 1205 tests, 100% coverage
|
|
173
173
|
├── .semgrep/ # 🔍 Custom SAST rules
|
|
174
174
|
├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
|
|
175
175
|
├── Dockerfile # 🐳 Hardened multi-stage container
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "taipanstack"
|
|
3
|
-
version = "0.4.
|
|
3
|
+
version = "0.4.3"
|
|
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"}
|
|
@@ -90,7 +90,6 @@ dev = [
|
|
|
90
90
|
"pytest-xdist (>=3.6.0)",
|
|
91
91
|
"vulture (>=2.11)",
|
|
92
92
|
"interrogate (>=1.5.0)",
|
|
93
|
-
"hypothesis (>=6.100.0)",
|
|
94
93
|
"polyfactory (>=2.0.0)",
|
|
95
94
|
"structlog (>=25.5.0,<26.0.0)",
|
|
96
95
|
"import-linter (>=2.1)",
|
|
@@ -107,6 +106,7 @@ dev = [
|
|
|
107
106
|
# CVSS 1.9/10 Low - local attack vector only, no upstream patch available yet
|
|
108
107
|
# Pinned to latest available; monitor for upstream fix in pygments >2.19.2
|
|
109
108
|
"pygments (>=2.19.2)",
|
|
109
|
+
"hypothesis (>=6.151.12,<7.0.0)",
|
|
110
110
|
]
|
|
111
111
|
|
|
112
112
|
|
|
@@ -174,7 +174,7 @@ max-complexity = 10
|
|
|
174
174
|
"src/taipanstack/resilience/*.py" = ["PLR0913", "D401", "S311", "TRY300", "TRY400"]
|
|
175
175
|
"src/taipanstack/resilience/watchdogs/*.py" = ["PLR0913", "D401", "TRY300", "TRY400"]
|
|
176
176
|
"src/taipanstack/resilience/adaptive/*.py" = ["PLR0913", "PLR0912", "D401", "TRY300", "TRY400"]
|
|
177
|
-
"src/taipanstack/bridges/*.py" = ["PLR0913", "D401", "TRY300", "TRY400"]
|
|
177
|
+
"src/taipanstack/bridges/*.py" = ["PLR0913", "D401", "TRY300", "TRY400", "ANN401"]
|
|
178
178
|
|
|
179
179
|
[tool.ruff.format]
|
|
180
180
|
quote-style = "double"
|
|
@@ -214,6 +214,7 @@ warn_required_dynamic_aliases = true
|
|
|
214
214
|
testpaths = ["tests"]
|
|
215
215
|
addopts = "-v --strict-markers --timeout=30"
|
|
216
216
|
asyncio_mode = "auto"
|
|
217
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
217
218
|
markers = [
|
|
218
219
|
"slow: marks tests as slow (deselect with '-m \"not slow\"')",
|
|
219
220
|
"security: marks tests as security-related",
|
|
@@ -222,7 +223,6 @@ markers = [
|
|
|
222
223
|
]
|
|
223
224
|
filterwarnings = [
|
|
224
225
|
|
|
225
|
-
"ignore::ResourceWarning",
|
|
226
226
|
"ignore::pytest.PytestUnraisableExceptionWarning",
|
|
227
227
|
]
|
|
228
228
|
|
|
@@ -267,8 +267,9 @@ fail-under = 80
|
|
|
267
267
|
verbose = 1
|
|
268
268
|
|
|
269
269
|
[tool.mutmut]
|
|
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"
|
|
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"
|
|
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"]
|
|
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"]
|
|
272
|
+
also_copy = ["src/"]
|
|
272
273
|
runner = "python -m pytest -x -q --tb=no --timeout=10 --no-cov"
|
|
273
274
|
dict_synonyms = "Struct, NamedStruct"
|
|
274
275
|
|
|
@@ -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.4.
|
|
8
|
+
__version__ = "0.4.3"
|
|
9
9
|
|
|
10
10
|
from taipanstack.config.version_config import (
|
|
11
11
|
VersionRecommendations,
|
|
@@ -7,7 +7,6 @@ that may or may not be installed at runtime.
|
|
|
7
7
|
|
|
8
8
|
import importlib
|
|
9
9
|
import types
|
|
10
|
-
from typing import Any
|
|
11
10
|
|
|
12
11
|
from taipanstack.core.result import Err, Ok, Result
|
|
13
12
|
|
|
@@ -51,7 +50,7 @@ def require_dependency(
|
|
|
51
50
|
def get_attr_or_err(
|
|
52
51
|
module: types.ModuleType,
|
|
53
52
|
name: str,
|
|
54
|
-
) -> Result[
|
|
53
|
+
) -> Result[object, AttributeError]:
|
|
55
54
|
"""Safely access an attribute from a module.
|
|
56
55
|
|
|
57
56
|
Args:
|
|
@@ -9,7 +9,7 @@ from __future__ import annotations
|
|
|
9
9
|
|
|
10
10
|
import asyncio
|
|
11
11
|
import logging
|
|
12
|
-
from typing import
|
|
12
|
+
from typing import TYPE_CHECKING
|
|
13
13
|
|
|
14
14
|
from taipanstack.core.result import Err, Ok, Result
|
|
15
15
|
from taipanstack.resilience.circuit_breaker import (
|
|
@@ -33,12 +33,16 @@ except ImportError: # pragma: no cover
|
|
|
33
33
|
_HAS_SQLALCHEMY = False
|
|
34
34
|
|
|
35
35
|
try:
|
|
36
|
-
import redis.asyncio as aioredis
|
|
36
|
+
import redis.asyncio as aioredis
|
|
37
37
|
|
|
38
38
|
_HAS_REDIS = True # pragma: no cover
|
|
39
39
|
except ImportError: # pragma: no cover
|
|
40
40
|
_HAS_REDIS = False
|
|
41
41
|
|
|
42
|
+
if TYPE_CHECKING:
|
|
43
|
+
import redis.asyncio as aioredis
|
|
44
|
+
from sqlalchemy.ext.asyncio import AsyncEngine
|
|
45
|
+
|
|
42
46
|
|
|
43
47
|
def _breaker_is_open(cb: CircuitBreaker) -> CircuitBreakerError | None:
|
|
44
48
|
"""Return a ``CircuitBreakerError`` if the breaker is OPEN.
|
|
@@ -74,7 +78,7 @@ class ResilientDatabase:
|
|
|
74
78
|
|
|
75
79
|
def __init__(
|
|
76
80
|
self,
|
|
77
|
-
engine:
|
|
81
|
+
engine: AsyncEngine,
|
|
78
82
|
*,
|
|
79
83
|
circuit_breaker: CircuitBreaker | None = None,
|
|
80
84
|
retry_config: RetryConfig | None = None,
|
|
@@ -91,11 +95,42 @@ class ResilientDatabase:
|
|
|
91
95
|
self._circuit_breaker = circuit_breaker
|
|
92
96
|
self._retry_config = retry_config
|
|
93
97
|
|
|
98
|
+
async def _execute_loop(
|
|
99
|
+
self,
|
|
100
|
+
statement: object,
|
|
101
|
+
max_attempts: int,
|
|
102
|
+
**kwargs: object,
|
|
103
|
+
) -> Result[object, Exception]:
|
|
104
|
+
"""Execute the retry loop for database operations."""
|
|
105
|
+
last_error: Exception | None = None
|
|
106
|
+
|
|
107
|
+
for attempt in range(1, max_attempts + 1):
|
|
108
|
+
try:
|
|
109
|
+
async with AsyncSession(self._engine) as session:
|
|
110
|
+
result = await session.execute(statement, **kwargs)
|
|
111
|
+
return Ok(result)
|
|
112
|
+
except Exception as exc:
|
|
113
|
+
last_error = exc
|
|
114
|
+
logger.warning(
|
|
115
|
+
"DB execute attempt %d failed: %s",
|
|
116
|
+
attempt,
|
|
117
|
+
exc,
|
|
118
|
+
)
|
|
119
|
+
if self._circuit_breaker is not None:
|
|
120
|
+
self._circuit_breaker._record_failure(exc)
|
|
121
|
+
if self._retry_config is not None and attempt < max_attempts:
|
|
122
|
+
delay = calculate_delay(attempt, self._retry_config)
|
|
123
|
+
await asyncio.sleep(min(delay, 3600.0))
|
|
124
|
+
continue
|
|
125
|
+
break
|
|
126
|
+
|
|
127
|
+
return Err(last_error or RuntimeError("Database execute failed"))
|
|
128
|
+
|
|
94
129
|
async def execute(
|
|
95
130
|
self,
|
|
96
|
-
statement:
|
|
97
|
-
**kwargs:
|
|
98
|
-
) -> Result[
|
|
131
|
+
statement: object,
|
|
132
|
+
**kwargs: object,
|
|
133
|
+
) -> Result[object, Exception]:
|
|
99
134
|
"""Execute a SQL statement with resilience.
|
|
100
135
|
|
|
101
136
|
Args:
|
|
@@ -124,29 +159,7 @@ class ResilientDatabase:
|
|
|
124
159
|
if self._retry_config is not None:
|
|
125
160
|
max_attempts = self._retry_config.max_attempts
|
|
126
161
|
|
|
127
|
-
|
|
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"))
|
|
162
|
+
return await self._execute_loop(statement, max_attempts, **kwargs)
|
|
150
163
|
|
|
151
164
|
async def health_check(self) -> Result[bool, Exception]:
|
|
152
165
|
"""Check database connectivity.
|
|
@@ -183,7 +196,7 @@ class ResilientRedis:
|
|
|
183
196
|
|
|
184
197
|
def __init__(
|
|
185
198
|
self,
|
|
186
|
-
client:
|
|
199
|
+
client: aioredis.Redis[bytes | str],
|
|
187
200
|
*,
|
|
188
201
|
circuit_breaker: CircuitBreaker | None = None,
|
|
189
202
|
) -> None:
|
|
@@ -200,8 +213,8 @@ class ResilientRedis:
|
|
|
200
213
|
async def execute(
|
|
201
214
|
self,
|
|
202
215
|
command: str,
|
|
203
|
-
*args:
|
|
204
|
-
) -> Result[
|
|
216
|
+
*args: object,
|
|
217
|
+
) -> Result[object, Exception]:
|
|
205
218
|
"""Execute a Redis command with resilience.
|
|
206
219
|
|
|
207
220
|
Args:
|
|
@@ -10,8 +10,10 @@ from __future__ import annotations
|
|
|
10
10
|
|
|
11
11
|
import asyncio
|
|
12
12
|
import logging
|
|
13
|
-
from collections.abc import Awaitable, Callable
|
|
14
|
-
from typing import
|
|
13
|
+
from collections.abc import Awaitable, Callable, Mapping, Sequence
|
|
14
|
+
from typing import TYPE_CHECKING
|
|
15
|
+
|
|
16
|
+
from typing_extensions import TypedDict, Unpack
|
|
15
17
|
|
|
16
18
|
from taipanstack.core.result import Err, Ok, Result
|
|
17
19
|
from taipanstack.resilience.circuit_breaker import (
|
|
@@ -23,6 +25,56 @@ from taipanstack.security.guards import guard_ssrf
|
|
|
23
25
|
|
|
24
26
|
logger = logging.getLogger("taipanstack.bridges.http")
|
|
25
27
|
|
|
28
|
+
|
|
29
|
+
class HttpRequestKwargs(TypedDict, total=False):
|
|
30
|
+
"""Type definitions for HTTP request kwargs."""
|
|
31
|
+
|
|
32
|
+
content: bytes | str | None
|
|
33
|
+
data: (
|
|
34
|
+
dict[str, str | int | float | bool | None]
|
|
35
|
+
| list[tuple[str, str]]
|
|
36
|
+
| bytes
|
|
37
|
+
| str
|
|
38
|
+
| None
|
|
39
|
+
)
|
|
40
|
+
files: dict[str, bytes | tuple[str, bytes]]
|
|
41
|
+
json: dict[str, object] | list[object] | str | int | float | bool | None
|
|
42
|
+
params: (
|
|
43
|
+
dict[
|
|
44
|
+
str,
|
|
45
|
+
str | int | float | bool | None | Sequence[str | int | float | bool | None],
|
|
46
|
+
]
|
|
47
|
+
| list[tuple[str, str | int | float | bool | None]]
|
|
48
|
+
| str
|
|
49
|
+
| bytes
|
|
50
|
+
| None
|
|
51
|
+
)
|
|
52
|
+
headers: dict[str, str]
|
|
53
|
+
cookies: dict[str, str]
|
|
54
|
+
auth: tuple[str, str]
|
|
55
|
+
follow_redirects: bool
|
|
56
|
+
extensions: dict[str, object]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class HttpClientKwargs(TypedDict, total=False):
|
|
60
|
+
"""Type definitions for HTTP client kwargs."""
|
|
61
|
+
|
|
62
|
+
base_url: str
|
|
63
|
+
headers: dict[str, str]
|
|
64
|
+
cookies: dict[str, str]
|
|
65
|
+
verify: bool | str
|
|
66
|
+
cert: str | tuple[str, str] | tuple[str, str, str]
|
|
67
|
+
http1: bool
|
|
68
|
+
http2: bool
|
|
69
|
+
proxy: str
|
|
70
|
+
mounts: Mapping[str, httpx.AsyncBaseTransport | None]
|
|
71
|
+
follow_redirects: bool
|
|
72
|
+
max_redirects: int
|
|
73
|
+
event_hooks: dict[str, list[Callable[..., object]]]
|
|
74
|
+
trust_env: bool
|
|
75
|
+
default_encoding: str | Callable[[bytes], str]
|
|
76
|
+
|
|
77
|
+
|
|
26
78
|
# --- optional httpx import ------------------------------------------------
|
|
27
79
|
|
|
28
80
|
try:
|
|
@@ -30,9 +82,11 @@ try:
|
|
|
30
82
|
|
|
31
83
|
_HAS_HTTPX = True # pragma: no cover
|
|
32
84
|
except ImportError: # pragma: no cover
|
|
33
|
-
httpx = None # type: ignore[assignment]
|
|
34
85
|
_HAS_HTTPX = False
|
|
35
86
|
|
|
87
|
+
if TYPE_CHECKING:
|
|
88
|
+
import httpx
|
|
89
|
+
|
|
36
90
|
# Default status codes that trigger a retry
|
|
37
91
|
_RETRYABLE_STATUS_CODES: frozenset[int] = frozenset({500, 502, 503, 504, 429})
|
|
38
92
|
|
|
@@ -79,12 +133,44 @@ def _check_ssrf(url: str, ssrf_protection: bool) -> Result[None, Exception]:
|
|
|
79
133
|
return Ok(None)
|
|
80
134
|
|
|
81
135
|
|
|
136
|
+
def _should_retry_status(
|
|
137
|
+
response: httpx.Response,
|
|
138
|
+
retry_config: RetryConfig | None,
|
|
139
|
+
retryable_status_codes: frozenset[int],
|
|
140
|
+
attempt: int,
|
|
141
|
+
max_attempts: int,
|
|
142
|
+
) -> bool:
|
|
143
|
+
"""Determine if a request should be retried based on status code."""
|
|
144
|
+
return (
|
|
145
|
+
retry_config is not None
|
|
146
|
+
and response.status_code in retryable_status_codes
|
|
147
|
+
and attempt < max_attempts
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
async def _handle_http_exception(
|
|
152
|
+
exc: Exception,
|
|
153
|
+
attempt: int,
|
|
154
|
+
max_attempts: int,
|
|
155
|
+
retry_config: RetryConfig | None,
|
|
156
|
+
circuit_breaker: CircuitBreaker | None,
|
|
157
|
+
) -> bool:
|
|
158
|
+
"""Handle exception and return True if we should retry, False otherwise."""
|
|
159
|
+
if circuit_breaker is not None: # pragma: no branch
|
|
160
|
+
circuit_breaker._record_failure(exc)
|
|
161
|
+
if retry_config is not None and attempt < max_attempts:
|
|
162
|
+
delay = calculate_delay(attempt, retry_config)
|
|
163
|
+
await asyncio.sleep(min(delay, 3600.0))
|
|
164
|
+
return True
|
|
165
|
+
return False
|
|
166
|
+
|
|
167
|
+
|
|
82
168
|
async def _execute_with_retries(
|
|
83
|
-
request_func: Callable[[], Awaitable[
|
|
169
|
+
request_func: Callable[[], Awaitable[httpx.Response]],
|
|
84
170
|
retry_config: RetryConfig | None,
|
|
85
171
|
circuit_breaker: CircuitBreaker | None,
|
|
86
172
|
retryable_status_codes: frozenset[int],
|
|
87
|
-
) -> Result[
|
|
173
|
+
) -> Result[httpx.Response, Exception]:
|
|
88
174
|
"""Execute a request function with optional retries and circuit breaker.
|
|
89
175
|
|
|
90
176
|
Args:
|
|
@@ -97,35 +183,29 @@ async def _execute_with_retries(
|
|
|
97
183
|
``Ok(Response)`` on success, ``Err`` on failure.
|
|
98
184
|
|
|
99
185
|
"""
|
|
100
|
-
max_attempts = 1
|
|
101
|
-
if retry_config is not None:
|
|
102
|
-
max_attempts = retry_config.max_attempts
|
|
103
|
-
|
|
186
|
+
max_attempts = retry_config.max_attempts if retry_config is not None else 1
|
|
104
187
|
last_error: Exception | None = None
|
|
105
188
|
|
|
106
189
|
for attempt in range(1, max_attempts + 1):
|
|
107
190
|
try:
|
|
108
191
|
response = await request_func()
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
192
|
+
if _should_retry_status(
|
|
193
|
+
response,
|
|
194
|
+
retry_config,
|
|
195
|
+
retryable_status_codes,
|
|
196
|
+
attempt,
|
|
197
|
+
max_attempts,
|
|
115
198
|
):
|
|
116
|
-
delay = calculate_delay(attempt, retry_config)
|
|
117
|
-
await asyncio.sleep(delay)
|
|
199
|
+
delay = calculate_delay(attempt, retry_config) # type: ignore[arg-type]
|
|
200
|
+
await asyncio.sleep(min(delay, 3600.0))
|
|
118
201
|
continue
|
|
119
|
-
|
|
120
202
|
return Ok(response)
|
|
121
|
-
|
|
122
203
|
except Exception as exc:
|
|
123
204
|
last_error = exc
|
|
124
|
-
|
|
125
|
-
circuit_breaker
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
await asyncio.sleep(delay)
|
|
205
|
+
should_retry = await _handle_http_exception(
|
|
206
|
+
exc, attempt, max_attempts, retry_config, circuit_breaker
|
|
207
|
+
)
|
|
208
|
+
if should_retry:
|
|
129
209
|
continue
|
|
130
210
|
break
|
|
131
211
|
|
|
@@ -140,8 +220,9 @@ async def safe_request(
|
|
|
140
220
|
retry_config: RetryConfig | None = None,
|
|
141
221
|
circuit_breaker: CircuitBreaker | None = None,
|
|
142
222
|
retryable_status_codes: frozenset[int] = _RETRYABLE_STATUS_CODES,
|
|
143
|
-
|
|
144
|
-
|
|
223
|
+
timeout: float | None = 10.0,
|
|
224
|
+
**kwargs: Unpack[HttpRequestKwargs],
|
|
225
|
+
) -> Result[httpx.Response, Exception]:
|
|
145
226
|
"""Perform a one-shot HTTP request with safety features.
|
|
146
227
|
|
|
147
228
|
Args:
|
|
@@ -151,6 +232,7 @@ async def safe_request(
|
|
|
151
232
|
retry_config: Optional retry configuration.
|
|
152
233
|
circuit_breaker: Optional circuit breaker.
|
|
153
234
|
retryable_status_codes: Status codes that trigger retries.
|
|
235
|
+
timeout: Explicit timeout in seconds (default: 10.0).
|
|
154
236
|
**kwargs: Passed to ``httpx.AsyncClient.request``.
|
|
155
237
|
|
|
156
238
|
Returns:
|
|
@@ -176,9 +258,10 @@ async def safe_request(
|
|
|
176
258
|
if cb_err is not None:
|
|
177
259
|
return Err(cb_err)
|
|
178
260
|
|
|
179
|
-
async def _do_request() ->
|
|
180
|
-
async with httpx.AsyncClient() as client:
|
|
181
|
-
|
|
261
|
+
async def _do_request() -> httpx.Response:
|
|
262
|
+
async with httpx.AsyncClient(timeout=timeout) as client: # nosemgrep
|
|
263
|
+
response = await client.request(method, url, **kwargs) # type: ignore[arg-type]
|
|
264
|
+
return response
|
|
182
265
|
|
|
183
266
|
return await _execute_with_retries(
|
|
184
267
|
_do_request,
|
|
@@ -214,7 +297,8 @@ class SafeHttpClient:
|
|
|
214
297
|
retry_config: RetryConfig | None = None,
|
|
215
298
|
circuit_breaker: CircuitBreaker | None = None,
|
|
216
299
|
retryable_status_codes: frozenset[int] = _RETRYABLE_STATUS_CODES,
|
|
217
|
-
|
|
300
|
+
timeout: float = 10.0,
|
|
301
|
+
**client_kwargs: Unpack[HttpClientKwargs],
|
|
218
302
|
) -> None:
|
|
219
303
|
"""Initialize the safe HTTP client.
|
|
220
304
|
|
|
@@ -224,6 +308,7 @@ class SafeHttpClient:
|
|
|
224
308
|
circuit_breaker: Circuit breaker instance.
|
|
225
309
|
retryable_status_codes: Status codes to retry.
|
|
226
310
|
**client_kwargs: Keyword args for httpx.AsyncClient.
|
|
311
|
+
Default timeout is 10.0 seconds if not provided.
|
|
227
312
|
|
|
228
313
|
"""
|
|
229
314
|
self._ssrf_protection = ssrf_protection
|
|
@@ -231,7 +316,8 @@ class SafeHttpClient:
|
|
|
231
316
|
self._circuit_breaker = circuit_breaker
|
|
232
317
|
self._retryable_status_codes = retryable_status_codes
|
|
233
318
|
self._client_kwargs = client_kwargs
|
|
234
|
-
self.
|
|
319
|
+
self._timeout = timeout
|
|
320
|
+
self._client: httpx.AsyncClient | None = None
|
|
235
321
|
|
|
236
322
|
async def __aenter__(self) -> SafeHttpClient:
|
|
237
323
|
"""Enter the async context manager."""
|
|
@@ -241,14 +327,17 @@ class SafeHttpClient:
|
|
|
241
327
|
"Install with: pip install taipanstack[bridges-http]"
|
|
242
328
|
)
|
|
243
329
|
raise ImportError(msg)
|
|
244
|
-
self._client = httpx.AsyncClient(
|
|
330
|
+
self._client = httpx.AsyncClient(
|
|
331
|
+
timeout=self._timeout,
|
|
332
|
+
**self._client_kwargs,
|
|
333
|
+
) # nosemgrep
|
|
245
334
|
return self
|
|
246
335
|
|
|
247
336
|
async def __aexit__(
|
|
248
337
|
self,
|
|
249
338
|
_exc_type: type[BaseException] | None,
|
|
250
339
|
_exc_val: BaseException | None,
|
|
251
|
-
_exc_tb:
|
|
340
|
+
_exc_tb: object,
|
|
252
341
|
) -> None:
|
|
253
342
|
"""Exit the async context manager."""
|
|
254
343
|
if self._client is not None:
|
|
@@ -259,8 +348,8 @@ class SafeHttpClient:
|
|
|
259
348
|
self,
|
|
260
349
|
method: str,
|
|
261
350
|
url: str,
|
|
262
|
-
**kwargs:
|
|
263
|
-
) -> Result[
|
|
351
|
+
**kwargs: Unpack[HttpRequestKwargs],
|
|
352
|
+
) -> Result[httpx.Response, Exception]:
|
|
264
353
|
"""Send an HTTP request with safety features.
|
|
265
354
|
|
|
266
355
|
Args:
|
|
@@ -286,8 +375,11 @@ class SafeHttpClient:
|
|
|
286
375
|
if cb_err is not None:
|
|
287
376
|
return Err(cb_err)
|
|
288
377
|
|
|
289
|
-
async def _do_request() ->
|
|
290
|
-
|
|
378
|
+
async def _do_request() -> httpx.Response:
|
|
379
|
+
# We explicitly verified client is not None above
|
|
380
|
+
client: httpx.AsyncClient = self._client # type: ignore[assignment]
|
|
381
|
+
response = await client.request(method, url, **kwargs) # type: ignore[arg-type]
|
|
382
|
+
return response
|
|
291
383
|
|
|
292
384
|
return await _execute_with_retries(
|
|
293
385
|
_do_request,
|
|
@@ -296,22 +388,32 @@ class SafeHttpClient:
|
|
|
296
388
|
self._retryable_status_codes,
|
|
297
389
|
)
|
|
298
390
|
|
|
299
|
-
async def get(
|
|
391
|
+
async def get(
|
|
392
|
+
self, url: str, **kw: Unpack[HttpRequestKwargs]
|
|
393
|
+
) -> Result[httpx.Response, Exception]:
|
|
300
394
|
"""Send a GET request."""
|
|
301
395
|
return await self.request("GET", url, **kw)
|
|
302
396
|
|
|
303
|
-
async def post(
|
|
397
|
+
async def post(
|
|
398
|
+
self, url: str, **kw: Unpack[HttpRequestKwargs]
|
|
399
|
+
) -> Result[httpx.Response, Exception]:
|
|
304
400
|
"""Send a POST request."""
|
|
305
401
|
return await self.request("POST", url, **kw)
|
|
306
402
|
|
|
307
|
-
async def put(
|
|
403
|
+
async def put(
|
|
404
|
+
self, url: str, **kw: Unpack[HttpRequestKwargs]
|
|
405
|
+
) -> Result[httpx.Response, Exception]:
|
|
308
406
|
"""Send a PUT request."""
|
|
309
407
|
return await self.request("PUT", url, **kw)
|
|
310
408
|
|
|
311
|
-
async def delete(
|
|
409
|
+
async def delete(
|
|
410
|
+
self, url: str, **kw: Unpack[HttpRequestKwargs]
|
|
411
|
+
) -> Result[httpx.Response, Exception]:
|
|
312
412
|
"""Send a DELETE request."""
|
|
313
413
|
return await self.request("DELETE", url, **kw)
|
|
314
414
|
|
|
315
|
-
async def patch(
|
|
415
|
+
async def patch(
|
|
416
|
+
self, url: str, **kw: Unpack[HttpRequestKwargs]
|
|
417
|
+
) -> Result[httpx.Response, Exception]:
|
|
316
418
|
"""Send a PATCH request."""
|
|
317
419
|
return await self.request("PATCH", url, **kw)
|