taipanstack 0.4.6__tar.gz → 0.4.7__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.6 → taipanstack-0.4.7}/PKG-INFO +10 -10
- {taipanstack-0.4.6 → taipanstack-0.4.7}/README.md +9 -9
- {taipanstack-0.4.6 → taipanstack-0.4.7}/pyproject.toml +1 -1
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/__init__.py +1 -1
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/bridges/db_bridge.py +31 -10
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/bridges/web_bridge.py +5 -5
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/core/compat.py +41 -29
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/resilience/adaptive/bulkhead.py +2 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/resilience/adaptive/orchestrator.py +18 -4
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/resilience/circuit_breaker.py +73 -58
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/security/guards.py +2 -2
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/security/models.py +3 -3
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/security/password.py +1 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/security/validators.py +21 -10
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/utils/filesystem.py +8 -4
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/utils/rate_limit.py +7 -4
- {taipanstack-0.4.6 → taipanstack-0.4.7}/LICENSE +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/bridges/__init__.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/bridges/_imports.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/bridges/http_bridge.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/config/__init__.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/config/generators.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/config/models.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/config/version_config.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/core/__init__.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/core/optimizations.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/core/result.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/resilience/__init__.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/resilience/adaptive/__init__.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/resilience/adaptive/adaptive_breaker.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/resilience/adaptive/adaptive_retry.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/resilience/resilience.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/resilience/retry.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/resilience/watchdogs/__init__.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/resilience/watchdogs/_base.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/resilience/watchdogs/config_watcher.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/resilience/watchdogs/health_pinger.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/resilience/watchdogs/resource_watcher.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/security/__init__.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/security/decorators.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/security/jwt.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/security/sanitizers.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/security/types.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/utils/__init__.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/utils/cache.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/utils/circuit_breaker.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/utils/concurrency.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/utils/context.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/utils/logging.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/utils/resilience.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/utils/retry.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/utils/serialization.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/utils/subprocess.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.7
|
|
4
4
|
Summary: TaipanStack - Modular, secure, and scalable Python stack for robust development
|
|
5
5
|
License-Expression: MIT
|
|
6
6
|
License-File: LICENSE
|
|
@@ -87,12 +87,12 @@ Description-Content-Type: text/markdown
|
|
|
87
87
|
|
|
88
88
|
Taipan Stack 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
|
-
- **Security Hardening**:
|
|
92
|
-
- **
|
|
93
|
-
- **
|
|
94
|
-
- **
|
|
95
|
-
- **Total Stack Coverage**: Reached **1,
|
|
90
|
+
### ✨ What's New in v0.4.7
|
|
91
|
+
- **Security Hardening**: Fixed TOCTOU, SSRF Unicode bypasses, and hardened Argon2 password verification (PR #663, #667, #661).
|
|
92
|
+
- **Resource Resilience**: Handled system resource exhaustion in Bulkhead and hardened adaptive orchestrator (PR #662, #668).
|
|
93
|
+
- **Complexity Reduction**: Significantly reduced cyclomatic complexity across core resilience and circuit breaker modules (PR #680, #676, #666).
|
|
94
|
+
- **Test Suite Audit**: Comprehensive audit and refactor of the entire suite for strict compliance and isolation (PR #683, #671, #665).
|
|
95
|
+
- **Total Stack Coverage**: Reached **1,299 passing tests** with 100% verified genuine coverage across all modules.
|
|
96
96
|
|
|
97
97
|
<table>
|
|
98
98
|
<tr>
|
|
@@ -130,7 +130,7 @@ Taipan Stack is a battle-tested foundation for production-grade Python projects
|
|
|
130
130
|
|
|
131
131
|
### 🔧 Developer Experience
|
|
132
132
|
- Pre-configured quality tools
|
|
133
|
-
- **100% code coverage** (
|
|
133
|
+
- **100% code coverage** (1299 tests)
|
|
134
134
|
- Architecture enforcement
|
|
135
135
|
- Hardened Docker template
|
|
136
136
|
|
|
@@ -172,7 +172,7 @@ make all
|
|
|
172
172
|
### Verify Installation
|
|
173
173
|
|
|
174
174
|
```bash
|
|
175
|
-
# Run tests with 100% coverage (
|
|
175
|
+
# Run tests with 100% coverage (1299 tests)
|
|
176
176
|
make test
|
|
177
177
|
|
|
178
178
|
# Check architecture contracts
|
|
@@ -227,7 +227,7 @@ TaipanStack/
|
|
|
227
227
|
│ ├── config/ # ⚙️ Configuration models & generators
|
|
228
228
|
│ ├── security/ # 🛡️ Guards, sanitizers, validators
|
|
229
229
|
│ └── utils/ # 🔧 Logging, metrics, retry, filesystem
|
|
230
|
-
├── tests/ # ✅
|
|
230
|
+
├── tests/ # ✅ 1299 tests, 100% coverage
|
|
231
231
|
├── .semgrep/ # 🔍 Custom SAST rules
|
|
232
232
|
├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
|
|
233
233
|
├── Dockerfile # 🐳 Hardened multi-stage container
|
|
@@ -30,12 +30,12 @@
|
|
|
30
30
|
|
|
31
31
|
Taipan Stack is a battle-tested foundation for production-grade Python projects that combines **security**, **performance**, and **developer experience** into a single, cohesive toolkit.
|
|
32
32
|
|
|
33
|
-
### ✨ What's New in v0.4.
|
|
34
|
-
- **Security Hardening**:
|
|
35
|
-
- **
|
|
36
|
-
- **
|
|
37
|
-
- **
|
|
38
|
-
- **Total Stack Coverage**: Reached **1,
|
|
33
|
+
### ✨ What's New in v0.4.7
|
|
34
|
+
- **Security Hardening**: Fixed TOCTOU, SSRF Unicode bypasses, and hardened Argon2 password verification (PR #663, #667, #661).
|
|
35
|
+
- **Resource Resilience**: Handled system resource exhaustion in Bulkhead and hardened adaptive orchestrator (PR #662, #668).
|
|
36
|
+
- **Complexity Reduction**: Significantly reduced cyclomatic complexity across core resilience and circuit breaker modules (PR #680, #676, #666).
|
|
37
|
+
- **Test Suite Audit**: Comprehensive audit and refactor of the entire suite for strict compliance and isolation (PR #683, #671, #665).
|
|
38
|
+
- **Total Stack Coverage**: Reached **1,299 passing tests** with 100% verified genuine coverage across all modules.
|
|
39
39
|
|
|
40
40
|
<table>
|
|
41
41
|
<tr>
|
|
@@ -73,7 +73,7 @@ Taipan Stack is a battle-tested foundation for production-grade Python projects
|
|
|
73
73
|
|
|
74
74
|
### 🔧 Developer Experience
|
|
75
75
|
- Pre-configured quality tools
|
|
76
|
-
- **100% code coverage** (
|
|
76
|
+
- **100% code coverage** (1299 tests)
|
|
77
77
|
- Architecture enforcement
|
|
78
78
|
- Hardened Docker template
|
|
79
79
|
|
|
@@ -115,7 +115,7 @@ make all
|
|
|
115
115
|
### Verify Installation
|
|
116
116
|
|
|
117
117
|
```bash
|
|
118
|
-
# Run tests with 100% coverage (
|
|
118
|
+
# Run tests with 100% coverage (1299 tests)
|
|
119
119
|
make test
|
|
120
120
|
|
|
121
121
|
# Check architecture contracts
|
|
@@ -170,7 +170,7 @@ TaipanStack/
|
|
|
170
170
|
│ ├── config/ # ⚙️ Configuration models & generators
|
|
171
171
|
│ ├── security/ # 🛡️ Guards, sanitizers, validators
|
|
172
172
|
│ └── utils/ # 🔧 Logging, metrics, retry, filesystem
|
|
173
|
-
├── tests/ # ✅
|
|
173
|
+
├── tests/ # ✅ 1299 tests, 100% coverage
|
|
174
174
|
├── .semgrep/ # 🔍 Custom SAST rules
|
|
175
175
|
├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
|
|
176
176
|
├── Dockerfile # 🐳 Hardened multi-stage container
|
|
@@ -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.7"
|
|
9
9
|
|
|
10
10
|
from taipanstack.config.version_config import (
|
|
11
11
|
VersionRecommendations,
|
|
@@ -95,6 +95,36 @@ class ResilientDatabase:
|
|
|
95
95
|
self._circuit_breaker = circuit_breaker
|
|
96
96
|
self._retry_config = retry_config
|
|
97
97
|
|
|
98
|
+
async def _handle_attempt_failure(
|
|
99
|
+
self,
|
|
100
|
+
exc: Exception,
|
|
101
|
+
attempt: int,
|
|
102
|
+
max_attempts: int,
|
|
103
|
+
) -> bool:
|
|
104
|
+
"""Handle a failed execution attempt.
|
|
105
|
+
|
|
106
|
+
Args:
|
|
107
|
+
exc: The exception that occurred.
|
|
108
|
+
attempt: The current attempt number.
|
|
109
|
+
max_attempts: Maximum number of attempts allowed.
|
|
110
|
+
|
|
111
|
+
Returns:
|
|
112
|
+
True if the operation should be retried, False otherwise.
|
|
113
|
+
|
|
114
|
+
"""
|
|
115
|
+
logger.warning(
|
|
116
|
+
"DB execute attempt %d failed: %s",
|
|
117
|
+
attempt,
|
|
118
|
+
exc,
|
|
119
|
+
)
|
|
120
|
+
if self._circuit_breaker is not None:
|
|
121
|
+
self._circuit_breaker._record_failure(exc)
|
|
122
|
+
if self._retry_config is not None and attempt < max_attempts:
|
|
123
|
+
delay = calculate_delay(attempt, self._retry_config)
|
|
124
|
+
await asyncio.sleep(min(delay, 3600.0))
|
|
125
|
+
return True
|
|
126
|
+
return False
|
|
127
|
+
|
|
98
128
|
async def _execute_loop(
|
|
99
129
|
self,
|
|
100
130
|
statement: object,
|
|
@@ -111,16 +141,7 @@ class ResilientDatabase:
|
|
|
111
141
|
return Ok(result)
|
|
112
142
|
except Exception as exc:
|
|
113
143
|
last_error = exc
|
|
114
|
-
|
|
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))
|
|
144
|
+
if await self._handle_attempt_failure(exc, attempt, max_attempts):
|
|
124
145
|
continue
|
|
125
146
|
break
|
|
126
147
|
|
|
@@ -12,7 +12,7 @@ import json
|
|
|
12
12
|
import logging
|
|
13
13
|
from collections.abc import Awaitable, Callable, MutableMapping
|
|
14
14
|
from dataclasses import dataclass
|
|
15
|
-
from typing import TypeVar
|
|
15
|
+
from typing import TypeAlias, TypeVar
|
|
16
16
|
|
|
17
17
|
from taipanstack.core.result import Err, Ok, Result
|
|
18
18
|
from taipanstack.utils.rate_limit import RateLimiter
|
|
@@ -22,10 +22,10 @@ logger = logging.getLogger("taipanstack.bridges.web")
|
|
|
22
22
|
T = TypeVar("T")
|
|
23
23
|
|
|
24
24
|
# ASGI type aliases
|
|
25
|
-
Scope = MutableMapping[str, object]
|
|
26
|
-
Receive = Callable[[], Awaitable[MutableMapping[str, object]]]
|
|
27
|
-
Send = Callable[[MutableMapping[str, object]], Awaitable[None]]
|
|
28
|
-
ASGIApp = Callable[[Scope, Receive, Send], Awaitable[None]]
|
|
25
|
+
Scope: TypeAlias = MutableMapping[str, object]
|
|
26
|
+
Receive: TypeAlias = Callable[[], Awaitable[MutableMapping[str, object]]]
|
|
27
|
+
Send: TypeAlias = Callable[[MutableMapping[str, object]], Awaitable[None]]
|
|
28
|
+
ASGIApp: TypeAlias = Callable[[Scope, Receive, Send], Awaitable[None]]
|
|
29
29
|
|
|
30
30
|
|
|
31
31
|
@dataclass(frozen=True)
|
|
@@ -254,6 +254,42 @@ class PythonFeatures:
|
|
|
254
254
|
}
|
|
255
255
|
|
|
256
256
|
|
|
257
|
+
def _get_version_tier() -> VersionTier:
|
|
258
|
+
"""Determine the version tier based on Python version."""
|
|
259
|
+
if PY314:
|
|
260
|
+
return VersionTier.CUTTING_EDGE
|
|
261
|
+
if PY313:
|
|
262
|
+
return VersionTier.MODERN
|
|
263
|
+
if PY312:
|
|
264
|
+
return VersionTier.ENHANCED
|
|
265
|
+
return VersionTier.STABLE
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _get_build_features(experimental: bool) -> dict[str, bool]:
|
|
269
|
+
"""Determine build features based on experimental flag."""
|
|
270
|
+
return {
|
|
271
|
+
"has_jit": _check_jit_available() if experimental else False,
|
|
272
|
+
"has_free_threading": _check_free_threading_available()
|
|
273
|
+
if experimental
|
|
274
|
+
else False,
|
|
275
|
+
"has_mimalloc": _check_mimalloc_available(),
|
|
276
|
+
"has_tail_call_interpreter": _check_tail_call_interpreter(),
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _get_language_features() -> dict[str, bool]:
|
|
281
|
+
"""Determine language features based on Python version."""
|
|
282
|
+
return {
|
|
283
|
+
"has_exception_groups": PY311,
|
|
284
|
+
"has_self_type": PY311,
|
|
285
|
+
"has_type_params": PY312,
|
|
286
|
+
"has_fstring_improvements": PY312,
|
|
287
|
+
"has_override_decorator": PY312,
|
|
288
|
+
"has_deprecated_decorator": PY313,
|
|
289
|
+
"has_deferred_annotations": PY314,
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
|
|
257
293
|
# =============================================================================
|
|
258
294
|
# Main Detection Functions
|
|
259
295
|
# =============================================================================
|
|
@@ -279,41 +315,17 @@ def get_features(*, force_refresh: bool = False) -> PythonFeatures:
|
|
|
279
315
|
if _cached_features is not None and not force_refresh:
|
|
280
316
|
return _cached_features
|
|
281
317
|
|
|
282
|
-
|
|
283
|
-
if PY314:
|
|
284
|
-
tier = VersionTier.CUTTING_EDGE
|
|
285
|
-
elif PY313:
|
|
286
|
-
tier = VersionTier.MODERN
|
|
287
|
-
elif PY312:
|
|
288
|
-
tier = VersionTier.ENHANCED
|
|
289
|
-
else:
|
|
290
|
-
tier = VersionTier.STABLE
|
|
291
|
-
|
|
318
|
+
tier = _get_version_tier()
|
|
292
319
|
experimental = is_experimental_enabled(force_refresh=force_refresh)
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
has_jit = _check_jit_available() if experimental else False
|
|
296
|
-
has_free_threading = _check_free_threading_available() if experimental else False
|
|
297
|
-
has_mimalloc = _check_mimalloc_available() # Safe to detect
|
|
320
|
+
build_feats = _get_build_features(experimental)
|
|
321
|
+
lang_feats = _get_language_features()
|
|
298
322
|
|
|
299
323
|
features = PythonFeatures(
|
|
300
324
|
version=(PY_VERSION.major, PY_VERSION.minor, PY_VERSION.micro),
|
|
301
325
|
version_string=f"{PY_VERSION.major}.{PY_VERSION.minor}.{PY_VERSION.micro}",
|
|
302
326
|
tier=tier,
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
has_free_threading=has_free_threading,
|
|
306
|
-
has_mimalloc=has_mimalloc,
|
|
307
|
-
has_tail_call_interpreter=_check_tail_call_interpreter(),
|
|
308
|
-
# Language features
|
|
309
|
-
has_exception_groups=PY311,
|
|
310
|
-
has_self_type=PY311,
|
|
311
|
-
has_type_params=PY312,
|
|
312
|
-
has_fstring_improvements=PY312,
|
|
313
|
-
has_override_decorator=PY312,
|
|
314
|
-
has_deprecated_decorator=PY313,
|
|
315
|
-
has_deferred_annotations=PY314,
|
|
316
|
-
# Experimental
|
|
327
|
+
**build_feats,
|
|
328
|
+
**lang_feats,
|
|
317
329
|
experimental_enabled=experimental,
|
|
318
330
|
)
|
|
319
331
|
|
|
@@ -208,6 +208,10 @@ class ResilienceOrchestrator(Generic[T]):
|
|
|
208
208
|
)
|
|
209
209
|
)
|
|
210
210
|
)
|
|
211
|
+
except (RuntimeError, OSError, MemoryError) as e:
|
|
212
|
+
return self._apply_fallback(
|
|
213
|
+
Err(RuntimeError(f"Resource exhaustion: {e!s}"))
|
|
214
|
+
)
|
|
211
215
|
finally:
|
|
212
216
|
bh._queued -= 1
|
|
213
217
|
|
|
@@ -283,6 +287,19 @@ class ResilienceOrchestrator(Generic[T]):
|
|
|
283
287
|
)
|
|
284
288
|
return await self._execute_with_retries(max_attempts, fn, *args, **kwargs)
|
|
285
289
|
|
|
290
|
+
async def _handle_retry_failure(
|
|
291
|
+
self,
|
|
292
|
+
error: Exception,
|
|
293
|
+
attempt: int,
|
|
294
|
+
max_attempts: int,
|
|
295
|
+
) -> bool:
|
|
296
|
+
self._record_failure_outcome(error, attempt)
|
|
297
|
+
if self._retry_config is not None and attempt < max_attempts:
|
|
298
|
+
delay = self._calculate_retry_delay(attempt)
|
|
299
|
+
await asyncio.sleep(min(delay, 3600.0))
|
|
300
|
+
return True
|
|
301
|
+
return False
|
|
302
|
+
|
|
286
303
|
async def _execute_with_retries(
|
|
287
304
|
self,
|
|
288
305
|
max_attempts: int,
|
|
@@ -299,10 +316,7 @@ class ResilienceOrchestrator(Generic[T]):
|
|
|
299
316
|
return result
|
|
300
317
|
case Err(error):
|
|
301
318
|
last_error = error
|
|
302
|
-
self.
|
|
303
|
-
if self._retry_config is not None and attempt < max_attempts:
|
|
304
|
-
delay = self._calculate_retry_delay(attempt)
|
|
305
|
-
await asyncio.sleep(min(delay, 3600.0))
|
|
319
|
+
if await self._handle_retry_failure(error, attempt, max_attempts):
|
|
306
320
|
continue
|
|
307
321
|
break
|
|
308
322
|
|
|
@@ -126,6 +126,17 @@ class CircuitBreaker:
|
|
|
126
126
|
|
|
127
127
|
"""
|
|
128
128
|
|
|
129
|
+
@staticmethod
|
|
130
|
+
def _validate_thresholds(
|
|
131
|
+
timeout: float, failure_threshold: int, success_threshold: int
|
|
132
|
+
) -> None:
|
|
133
|
+
if not math.isfinite(timeout) or timeout < 0:
|
|
134
|
+
raise ValueError("timeout must be a finite non-negative number")
|
|
135
|
+
if not math.isfinite(failure_threshold) or failure_threshold < 1:
|
|
136
|
+
raise ValueError("failure_threshold must be a finite number >= 1")
|
|
137
|
+
if not math.isfinite(success_threshold) or success_threshold < 1:
|
|
138
|
+
raise ValueError("success_threshold must be a finite number >= 1")
|
|
139
|
+
|
|
129
140
|
def __init__(
|
|
130
141
|
self,
|
|
131
142
|
*,
|
|
@@ -150,12 +161,9 @@ class CircuitBreaker:
|
|
|
150
161
|
with (old_state, new_state). Useful for custom monitoring.
|
|
151
162
|
|
|
152
163
|
"""
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
raise ValueError("failure_threshold must be a finite number >= 1")
|
|
157
|
-
if not math.isfinite(success_threshold) or success_threshold < 1:
|
|
158
|
-
raise ValueError("success_threshold must be a finite number >= 1")
|
|
164
|
+
CircuitBreaker._validate_thresholds(
|
|
165
|
+
timeout, failure_threshold, success_threshold
|
|
166
|
+
)
|
|
159
167
|
|
|
160
168
|
self.config = CircuitBreakerConfig(
|
|
161
169
|
failure_threshold=failure_threshold,
|
|
@@ -178,6 +186,27 @@ class CircuitBreaker:
|
|
|
178
186
|
"""Get current failure count."""
|
|
179
187
|
return self._state.failure_count
|
|
180
188
|
|
|
189
|
+
def _log_callback_failure(
|
|
190
|
+
self,
|
|
191
|
+
old_state: CircuitState,
|
|
192
|
+
new_state: CircuitState,
|
|
193
|
+
e: Exception,
|
|
194
|
+
) -> None:
|
|
195
|
+
if _HAS_STRUCTLOG and _structlog_logger is not None:
|
|
196
|
+
_structlog_logger.error(
|
|
197
|
+
"circuit_state_change_callback_failed",
|
|
198
|
+
circuit=self.name,
|
|
199
|
+
old_state=old_state.value,
|
|
200
|
+
new_state=new_state.value,
|
|
201
|
+
error=str(e),
|
|
202
|
+
)
|
|
203
|
+
else:
|
|
204
|
+
logger.error(
|
|
205
|
+
"Circuit %s state change callback failed: %s",
|
|
206
|
+
self.name,
|
|
207
|
+
str(e),
|
|
208
|
+
)
|
|
209
|
+
|
|
181
210
|
def _notify_state_change(
|
|
182
211
|
self,
|
|
183
212
|
old_state: CircuitState,
|
|
@@ -192,20 +221,7 @@ class CircuitBreaker:
|
|
|
192
221
|
try:
|
|
193
222
|
self._on_state_change(old_state, new_state)
|
|
194
223
|
except Exception as e:
|
|
195
|
-
|
|
196
|
-
_structlog_logger.error(
|
|
197
|
-
"circuit_state_change_callback_failed",
|
|
198
|
-
circuit=self.name,
|
|
199
|
-
old_state=old_state.value,
|
|
200
|
-
new_state=new_state.value,
|
|
201
|
-
error=str(e),
|
|
202
|
-
)
|
|
203
|
-
else:
|
|
204
|
-
logger.error(
|
|
205
|
-
"Circuit %s state change callback failed: %s",
|
|
206
|
-
self.name,
|
|
207
|
-
str(e),
|
|
208
|
-
)
|
|
224
|
+
self._log_callback_failure(old_state, new_state, e)
|
|
209
225
|
elif _HAS_STRUCTLOG and _structlog_logger is not None: # pragma: no branch
|
|
210
226
|
_structlog_logger.warning(
|
|
211
227
|
"circuit_state_changed",
|
|
@@ -248,6 +264,14 @@ class CircuitBreaker:
|
|
|
248
264
|
return True
|
|
249
265
|
return False
|
|
250
266
|
|
|
267
|
+
def _handle_attempt_half_open(self) -> bool:
|
|
268
|
+
if not math.isfinite(self._state.half_open_attempts):
|
|
269
|
+
return False
|
|
270
|
+
if self._state.half_open_attempts < self.config.success_threshold:
|
|
271
|
+
self._state.half_open_attempts += 1
|
|
272
|
+
return True
|
|
273
|
+
return False
|
|
274
|
+
|
|
251
275
|
def _should_attempt(self) -> bool:
|
|
252
276
|
"""Check if a call should be attempted."""
|
|
253
277
|
with self._state.lock:
|
|
@@ -259,42 +283,35 @@ class CircuitBreaker:
|
|
|
259
283
|
return self._handle_open_state()
|
|
260
284
|
|
|
261
285
|
case CircuitState.HALF_OPEN:
|
|
262
|
-
|
|
263
|
-
if not math.isfinite(self._state.half_open_attempts):
|
|
264
|
-
# Block attempt to prevent thundering herd when corrupted
|
|
265
|
-
return False
|
|
266
|
-
|
|
267
|
-
# Allow limited attempts to prevent thundering herd
|
|
268
|
-
if self._state.half_open_attempts < self.config.success_threshold:
|
|
269
|
-
self._state.half_open_attempts += 1
|
|
270
|
-
return True
|
|
271
|
-
return False
|
|
286
|
+
return self._handle_attempt_half_open()
|
|
272
287
|
|
|
273
288
|
return False
|
|
274
289
|
|
|
290
|
+
def _handle_success_half_open(self) -> None:
|
|
291
|
+
if not math.isfinite(self._state.success_count):
|
|
292
|
+
self._state.success_count = 0
|
|
293
|
+
self._state.success_count += 1
|
|
294
|
+
|
|
295
|
+
if self._state.success_count >= self.config.success_threshold:
|
|
296
|
+
self._state.state = CircuitState.CLOSED
|
|
297
|
+
self._state.failure_count = 0
|
|
298
|
+
self._state.half_open_attempts = 0
|
|
299
|
+
logger.info(
|
|
300
|
+
"Circuit %s closed after recovery (%d consecutive successes)",
|
|
301
|
+
self.name,
|
|
302
|
+
self._state.success_count,
|
|
303
|
+
)
|
|
304
|
+
self._notify_state_change(
|
|
305
|
+
CircuitState.HALF_OPEN,
|
|
306
|
+
CircuitState.CLOSED,
|
|
307
|
+
)
|
|
308
|
+
|
|
275
309
|
def _record_success(self) -> None:
|
|
276
310
|
"""Record a successful call."""
|
|
277
311
|
with self._state.lock:
|
|
278
312
|
match self._state.state:
|
|
279
313
|
case CircuitState.HALF_OPEN:
|
|
280
|
-
|
|
281
|
-
self._state.success_count = 0
|
|
282
|
-
self._state.success_count += 1
|
|
283
|
-
|
|
284
|
-
if self._state.success_count >= self.config.success_threshold:
|
|
285
|
-
self._state.state = CircuitState.CLOSED
|
|
286
|
-
self._state.failure_count = 0
|
|
287
|
-
self._state.half_open_attempts = 0
|
|
288
|
-
logger.info(
|
|
289
|
-
"Circuit %s closed after recovery "
|
|
290
|
-
"(%d consecutive successes)",
|
|
291
|
-
self.name,
|
|
292
|
-
self._state.success_count,
|
|
293
|
-
)
|
|
294
|
-
self._notify_state_change(
|
|
295
|
-
CircuitState.HALF_OPEN,
|
|
296
|
-
CircuitState.CLOSED,
|
|
297
|
-
)
|
|
314
|
+
self._handle_success_half_open()
|
|
298
315
|
|
|
299
316
|
case CircuitState.CLOSED:
|
|
300
317
|
# Reset failure count on success
|
|
@@ -344,6 +361,13 @@ class CircuitBreaker:
|
|
|
344
361
|
CircuitState.OPEN,
|
|
345
362
|
)
|
|
346
363
|
|
|
364
|
+
def _update_failure_metrics(self) -> None:
|
|
365
|
+
if math.isfinite(self._state.failure_count):
|
|
366
|
+
self._state.failure_count += 1
|
|
367
|
+
now = time.monotonic()
|
|
368
|
+
if math.isfinite(now):
|
|
369
|
+
self._state.last_failure_time = now
|
|
370
|
+
|
|
347
371
|
def _record_failure(self, exc: Exception) -> None:
|
|
348
372
|
"""Record a failed call."""
|
|
349
373
|
# Check if exception should be excluded
|
|
@@ -351,16 +375,7 @@ class CircuitBreaker:
|
|
|
351
375
|
return
|
|
352
376
|
|
|
353
377
|
with self._state.lock:
|
|
354
|
-
|
|
355
|
-
if not math.isfinite(self._state.failure_count):
|
|
356
|
-
# `_handle_failure_closed` will open it
|
|
357
|
-
pass
|
|
358
|
-
else:
|
|
359
|
-
self._state.failure_count += 1
|
|
360
|
-
|
|
361
|
-
now = time.monotonic()
|
|
362
|
-
if math.isfinite(now):
|
|
363
|
-
self._state.last_failure_time = now
|
|
378
|
+
self._update_failure_metrics()
|
|
364
379
|
|
|
365
380
|
match self._state.state:
|
|
366
381
|
case CircuitState.HALF_OPEN:
|
|
@@ -605,10 +605,10 @@ def _check_ip_safety(hostname: str) -> Result[None, SecurityError]:
|
|
|
605
605
|
"""Resolve hostname to IP addresses and check for SSRF risk."""
|
|
606
606
|
try:
|
|
607
607
|
addr_infos = socket.getaddrinfo(hostname, None)
|
|
608
|
-
except socket.gaierror:
|
|
608
|
+
except (socket.gaierror, UnicodeError):
|
|
609
609
|
return Err(
|
|
610
610
|
SecurityError(
|
|
611
|
-
"Hostname could not be resolved",
|
|
611
|
+
"Hostname could not be resolved or contains invalid characters",
|
|
612
612
|
guard_name="ssrf",
|
|
613
613
|
)
|
|
614
614
|
)
|
|
@@ -134,7 +134,7 @@ class SecureBaseModel(BaseModel):
|
|
|
134
134
|
self,
|
|
135
135
|
*,
|
|
136
136
|
indent: int | None = None,
|
|
137
|
-
ensure_ascii: bool = False,
|
|
137
|
+
ensure_ascii: bool = False,
|
|
138
138
|
include: IncEx | None = None,
|
|
139
139
|
exclude: IncEx | None = None,
|
|
140
140
|
context: dict[str, object] | None = None,
|
|
@@ -178,5 +178,5 @@ class SecureBaseModel(BaseModel):
|
|
|
178
178
|
# We need to respect Pydantic's indent/separators if possible,
|
|
179
179
|
# but json.dumps is the safest standard way.
|
|
180
180
|
if indent is not None:
|
|
181
|
-
return json.dumps(masked_dict, indent=indent)
|
|
182
|
-
return json.dumps(masked_dict)
|
|
181
|
+
return json.dumps(masked_dict, indent=indent, ensure_ascii=ensure_ascii)
|
|
182
|
+
return json.dumps(masked_dict, ensure_ascii=ensure_ascii)
|
|
@@ -303,12 +303,11 @@ def _check_url_basics(url: str) -> None:
|
|
|
303
303
|
raise ValueError(msg)
|
|
304
304
|
|
|
305
305
|
|
|
306
|
-
def
|
|
306
|
+
def _check_scheme(
|
|
307
307
|
parsed: urllib.parse.SplitResult,
|
|
308
308
|
allowed_schemes: tuple[str, ...],
|
|
309
|
-
require_tld: bool,
|
|
310
309
|
) -> None:
|
|
311
|
-
"""Validate URL scheme
|
|
310
|
+
"""Validate the URL scheme."""
|
|
312
311
|
if not parsed.scheme:
|
|
313
312
|
msg = "URL must have a scheme (e.g., https://)"
|
|
314
313
|
raise ValueError(msg)
|
|
@@ -317,18 +316,30 @@ def _check_url_domain(
|
|
|
317
316
|
msg = f"URL scheme '{parsed.scheme}' is not allowed. Allowed: {allowed_schemes}"
|
|
318
317
|
raise ValueError(msg)
|
|
319
318
|
|
|
319
|
+
|
|
320
|
+
def _check_tld(domain: str) -> None:
|
|
321
|
+
"""Validate that the domain has a TLD."""
|
|
322
|
+
has_no_tld = "." not in domain or domain.endswith(".")
|
|
323
|
+
is_localhost = domain.lower() in LOCALHOST_DOMAINS
|
|
324
|
+
if has_no_tld and not is_localhost:
|
|
325
|
+
msg = f"URL domain must have a TLD: {domain}"
|
|
326
|
+
raise ValueError(msg)
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def _check_url_domain(
|
|
330
|
+
parsed: urllib.parse.SplitResult,
|
|
331
|
+
allowed_schemes: tuple[str, ...],
|
|
332
|
+
require_tld: bool,
|
|
333
|
+
) -> None:
|
|
334
|
+
"""Validate URL scheme and domain."""
|
|
335
|
+
_check_scheme(parsed, allowed_schemes)
|
|
336
|
+
|
|
320
337
|
if not parsed.hostname:
|
|
321
338
|
msg = "URL must have a domain"
|
|
322
339
|
raise ValueError(msg)
|
|
323
340
|
|
|
324
341
|
if require_tld:
|
|
325
|
-
|
|
326
|
-
domain = parsed.hostname
|
|
327
|
-
has_no_tld = "." not in domain or domain.endswith(".")
|
|
328
|
-
is_localhost = domain.lower() in LOCALHOST_DOMAINS
|
|
329
|
-
if has_no_tld and not is_localhost:
|
|
330
|
-
msg = f"URL domain must have a TLD: {domain}"
|
|
331
|
-
raise ValueError(msg)
|
|
342
|
+
_check_tld(parsed.hostname)
|
|
332
343
|
|
|
333
344
|
|
|
334
345
|
def validate_url(
|
|
@@ -5,6 +5,7 @@ Provides secure wrappers around file operations with path validation,
|
|
|
5
5
|
atomic writes, and proper error handling using Result types.
|
|
6
6
|
"""
|
|
7
7
|
|
|
8
|
+
import contextlib
|
|
8
9
|
import os
|
|
9
10
|
import shutil
|
|
10
11
|
import tempfile
|
|
@@ -202,10 +203,11 @@ def _perform_atomic_write(path: Path, content: str, opts: WriteOptions) -> None:
|
|
|
202
203
|
suffix=".tmp",
|
|
203
204
|
)
|
|
204
205
|
try:
|
|
205
|
-
#
|
|
206
|
-
os.
|
|
206
|
+
# Write directly to the returned file descriptor to prevent TOCTOU
|
|
207
|
+
with os.fdopen(_fd, "w", encoding=opts.encoding) as f:
|
|
208
|
+
f.write(content)
|
|
209
|
+
|
|
207
210
|
temp_file = Path(temp_path)
|
|
208
|
-
temp_file.write_text(content, encoding=opts.encoding)
|
|
209
211
|
# Preserve permissions if original exists
|
|
210
212
|
if path.exists():
|
|
211
213
|
shutil.copymode(path, temp_file)
|
|
@@ -214,7 +216,9 @@ def _perform_atomic_write(path: Path, content: str, opts: WriteOptions) -> None:
|
|
|
214
216
|
path.unlink()
|
|
215
217
|
temp_file.rename(path)
|
|
216
218
|
except Exception:
|
|
217
|
-
# Clean up temp file on error
|
|
219
|
+
# Clean up descriptor and temp file on error
|
|
220
|
+
with contextlib.suppress(OSError):
|
|
221
|
+
os.close(_fd)
|
|
218
222
|
Path(temp_path).unlink(missing_ok=True)
|
|
219
223
|
raise
|
|
220
224
|
|
|
@@ -57,6 +57,12 @@ class RateLimiter:
|
|
|
57
57
|
self.last_update: float = time.monotonic()
|
|
58
58
|
self._lock = threading.Lock()
|
|
59
59
|
|
|
60
|
+
def _is_valid_bucket_state(self) -> bool:
|
|
61
|
+
"""Check if the bucket's time window and capacity are in a valid state."""
|
|
62
|
+
if not math.isfinite(self.time_window) or self.time_window <= 0.0:
|
|
63
|
+
return False
|
|
64
|
+
return math.isfinite(self.capacity) and self.capacity > 0.0
|
|
65
|
+
|
|
60
66
|
def _add_tokens(self, now: float) -> bool:
|
|
61
67
|
"""Calculate and add new tokens to the bucket based on elapsed time.
|
|
62
68
|
|
|
@@ -71,10 +77,7 @@ class RateLimiter:
|
|
|
71
77
|
self.last_update = now
|
|
72
78
|
|
|
73
79
|
# Prevent state corruption from raising exceptions or poisoning state
|
|
74
|
-
if not
|
|
75
|
-
return False
|
|
76
|
-
|
|
77
|
-
if not math.isfinite(self.capacity) or self.capacity <= 0.0:
|
|
80
|
+
if not self._is_valid_bucket_state():
|
|
78
81
|
return False
|
|
79
82
|
|
|
80
83
|
# Prevent infinite or NaN tokens by checking elapsed time calculations
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/resilience/adaptive/adaptive_breaker.py
RENAMED
|
File without changes
|
{taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/resilience/adaptive/adaptive_retry.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/resilience/watchdogs/config_watcher.py
RENAMED
|
File without changes
|
{taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/resilience/watchdogs/health_pinger.py
RENAMED
|
File without changes
|
{taipanstack-0.4.6 → taipanstack-0.4.7}/src/taipanstack/resilience/watchdogs/resource_watcher.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|