taipanstack 0.4.4__tar.gz → 0.4.5__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.4 → taipanstack-0.4.5}/PKG-INFO +10 -8
- {taipanstack-0.4.4 → taipanstack-0.4.5}/README.md +9 -7
- {taipanstack-0.4.4 → taipanstack-0.4.5}/pyproject.toml +2 -1
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/__init__.py +1 -1
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/bridges/db_bridge.py +6 -6
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/bridges/http_bridge.py +11 -5
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/core/compat.py +2 -2
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/core/result.py +19 -10
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/resilience/circuit_breaker.py +81 -39
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/resilience/resilience.py +6 -10
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/resilience/retry.py +35 -16
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/resilience/watchdogs/_base.py +1 -1
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/resilience/watchdogs/config_watcher.py +1 -1
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/security/decorators.py +2 -2
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/security/guards.py +68 -36
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/security/jwt.py +6 -17
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/security/models.py +0 -6
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/security/sanitizers.py +7 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/utils/cache.py +2 -2
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/utils/concurrency.py +2 -2
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/utils/logging.py +1 -1
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/utils/rate_limit.py +33 -8
- {taipanstack-0.4.4 → taipanstack-0.4.5}/LICENSE +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/bridges/__init__.py +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/bridges/_imports.py +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/bridges/web_bridge.py +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/config/__init__.py +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/config/generators.py +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/config/models.py +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/config/version_config.py +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/core/__init__.py +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/core/optimizations.py +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/resilience/__init__.py +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/resilience/adaptive/__init__.py +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/resilience/adaptive/adaptive_breaker.py +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/resilience/adaptive/adaptive_retry.py +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/resilience/adaptive/bulkhead.py +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/resilience/adaptive/orchestrator.py +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/resilience/watchdogs/__init__.py +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/resilience/watchdogs/health_pinger.py +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/resilience/watchdogs/resource_watcher.py +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/security/__init__.py +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/security/password.py +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/security/types.py +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/security/validators.py +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/utils/__init__.py +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/utils/circuit_breaker.py +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/utils/context.py +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/utils/filesystem.py +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/utils/resilience.py +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/utils/retry.py +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/utils/serialization.py +0 -0
- {taipanstack-0.4.4 → taipanstack-0.4.5}/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.5
|
|
4
4
|
Summary: TaipanStack - Modular, secure, and scalable Python stack for robust development
|
|
5
5
|
License-Expression: MIT
|
|
6
6
|
License-File: LICENSE
|
|
@@ -86,10 +86,12 @@ Description-Content-Type: text/markdown
|
|
|
86
86
|
|
|
87
87
|
Taipan Stack is a battle-tested foundation for production-grade Python projects that combines **security**, **performance**, and **developer experience** into a single, cohesive toolkit.
|
|
88
88
|
|
|
89
|
-
### ✨ What's New in v0.4.
|
|
90
|
-
- **
|
|
91
|
-
- **
|
|
92
|
-
- **
|
|
89
|
+
### ✨ What's New in v0.4.5
|
|
90
|
+
- **100% Genuine Coverage**: Achieved the milestone of **true 100% code coverage** without a single `pragma: no cover` bypass (PR #636).
|
|
91
|
+
- **Security Hardening**: Reinforced `RateLimiter` and `CircuitBreaker` against state corruption and `NaN` poisoning (PR #622, #630).
|
|
92
|
+
- **Strict Typing**: Eliminated remaining `Any` usage and resolved all `type: ignore` directives for a pure strictly-typed codebase (PR #624).
|
|
93
|
+
- **Refactoring**: Significantly reduced cyclomatic complexity across core security and resilience modules.
|
|
94
|
+
- **Total Stack Coverage**: Reached **1,249 passing tests** with true 100% coverage across all core and bridge components.
|
|
93
95
|
|
|
94
96
|
<table>
|
|
95
97
|
<tr>
|
|
@@ -127,7 +129,7 @@ Taipan Stack is a battle-tested foundation for production-grade Python projects
|
|
|
127
129
|
|
|
128
130
|
### 🔧 Developer Experience
|
|
129
131
|
- Pre-configured quality tools
|
|
130
|
-
- **100% code coverage** (
|
|
132
|
+
- **100% code coverage** (1249 tests)
|
|
131
133
|
- Architecture enforcement
|
|
132
134
|
- Hardened Docker template
|
|
133
135
|
|
|
@@ -169,7 +171,7 @@ make all
|
|
|
169
171
|
### Verify Installation
|
|
170
172
|
|
|
171
173
|
```bash
|
|
172
|
-
# Run tests with 100% coverage (
|
|
174
|
+
# Run tests with 100% coverage (1249 tests)
|
|
173
175
|
make test
|
|
174
176
|
|
|
175
177
|
# Check architecture contracts
|
|
@@ -224,7 +226,7 @@ TaipanStack/
|
|
|
224
226
|
│ ├── config/ # ⚙️ Configuration models & generators
|
|
225
227
|
│ ├── security/ # 🛡️ Guards, sanitizers, validators
|
|
226
228
|
│ └── utils/ # 🔧 Logging, metrics, retry, filesystem
|
|
227
|
-
├── tests/ # ✅
|
|
229
|
+
├── tests/ # ✅ 1249 tests, 100% coverage
|
|
228
230
|
├── .semgrep/ # 🔍 Custom SAST rules
|
|
229
231
|
├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
|
|
230
232
|
├── Dockerfile # 🐳 Hardened multi-stage container
|
|
@@ -30,10 +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
|
-
- **
|
|
35
|
-
- **
|
|
36
|
-
- **
|
|
33
|
+
### ✨ What's New in v0.4.5
|
|
34
|
+
- **100% Genuine Coverage**: Achieved the milestone of **true 100% code coverage** without a single `pragma: no cover` bypass (PR #636).
|
|
35
|
+
- **Security Hardening**: Reinforced `RateLimiter` and `CircuitBreaker` against state corruption and `NaN` poisoning (PR #622, #630).
|
|
36
|
+
- **Strict Typing**: Eliminated remaining `Any` usage and resolved all `type: ignore` directives for a pure strictly-typed codebase (PR #624).
|
|
37
|
+
- **Refactoring**: Significantly reduced cyclomatic complexity across core security and resilience modules.
|
|
38
|
+
- **Total Stack Coverage**: Reached **1,249 passing tests** with true 100% coverage across all core and bridge components.
|
|
37
39
|
|
|
38
40
|
<table>
|
|
39
41
|
<tr>
|
|
@@ -71,7 +73,7 @@ Taipan Stack is a battle-tested foundation for production-grade Python projects
|
|
|
71
73
|
|
|
72
74
|
### 🔧 Developer Experience
|
|
73
75
|
- Pre-configured quality tools
|
|
74
|
-
- **100% code coverage** (
|
|
76
|
+
- **100% code coverage** (1249 tests)
|
|
75
77
|
- Architecture enforcement
|
|
76
78
|
- Hardened Docker template
|
|
77
79
|
|
|
@@ -113,7 +115,7 @@ make all
|
|
|
113
115
|
### Verify Installation
|
|
114
116
|
|
|
115
117
|
```bash
|
|
116
|
-
# Run tests with 100% coverage (
|
|
118
|
+
# Run tests with 100% coverage (1249 tests)
|
|
117
119
|
make test
|
|
118
120
|
|
|
119
121
|
# Check architecture contracts
|
|
@@ -168,7 +170,7 @@ TaipanStack/
|
|
|
168
170
|
│ ├── config/ # ⚙️ Configuration models & generators
|
|
169
171
|
│ ├── security/ # 🛡️ Guards, sanitizers, validators
|
|
170
172
|
│ └── utils/ # 🔧 Logging, metrics, retry, filesystem
|
|
171
|
-
├── tests/ # ✅
|
|
173
|
+
├── tests/ # ✅ 1249 tests, 100% coverage
|
|
172
174
|
├── .semgrep/ # 🔍 Custom SAST rules
|
|
173
175
|
├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
|
|
174
176
|
├── Dockerfile # 🐳 Hardened multi-stage container
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "taipanstack"
|
|
3
|
-
version = "0.4.
|
|
3
|
+
version = "0.4.5"
|
|
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"}
|
|
@@ -119,6 +119,7 @@ dev = [
|
|
|
119
119
|
"cryptography (>=46.0.7,<47.0.0)",
|
|
120
120
|
"nltk (>=3.9.4,<4.0.0)",
|
|
121
121
|
"mutmut (>=3.0.0,<4.0.0)",
|
|
122
|
+
"pip (>=26.1,<27.0)",
|
|
122
123
|
]
|
|
123
124
|
|
|
124
125
|
|
|
@@ -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.5"
|
|
9
9
|
|
|
10
10
|
from taipanstack.config.version_config import (
|
|
11
11
|
VersionRecommendations,
|
|
@@ -25,18 +25,18 @@ logger = logging.getLogger("taipanstack.bridges.db")
|
|
|
25
25
|
|
|
26
26
|
try:
|
|
27
27
|
import sqlalchemy # noqa: F401
|
|
28
|
-
from sqlalchemy import text as sa_text
|
|
29
|
-
from sqlalchemy.ext.asyncio import AsyncSession
|
|
28
|
+
from sqlalchemy import text as sa_text
|
|
29
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
30
30
|
|
|
31
|
-
_HAS_SQLALCHEMY = True
|
|
32
|
-
except ImportError:
|
|
31
|
+
_HAS_SQLALCHEMY = True
|
|
32
|
+
except ImportError:
|
|
33
33
|
_HAS_SQLALCHEMY = False
|
|
34
34
|
|
|
35
35
|
try:
|
|
36
36
|
import redis.asyncio as aioredis
|
|
37
37
|
|
|
38
|
-
_HAS_REDIS = True
|
|
39
|
-
except ImportError:
|
|
38
|
+
_HAS_REDIS = True
|
|
39
|
+
except ImportError:
|
|
40
40
|
_HAS_REDIS = False
|
|
41
41
|
|
|
42
42
|
if TYPE_CHECKING:
|
|
@@ -11,7 +11,7 @@ from __future__ import annotations
|
|
|
11
11
|
import asyncio
|
|
12
12
|
import logging
|
|
13
13
|
from collections.abc import Awaitable, Callable, Mapping, Sequence
|
|
14
|
-
from typing import TYPE_CHECKING,
|
|
14
|
+
from typing import TYPE_CHECKING, cast
|
|
15
15
|
|
|
16
16
|
from typing_extensions import TypedDict, Unpack
|
|
17
17
|
|
|
@@ -80,8 +80,8 @@ class HttpClientKwargs(TypedDict, total=False):
|
|
|
80
80
|
try:
|
|
81
81
|
import httpx
|
|
82
82
|
|
|
83
|
-
_HAS_HTTPX = True
|
|
84
|
-
except ImportError:
|
|
83
|
+
_HAS_HTTPX = True
|
|
84
|
+
except ImportError:
|
|
85
85
|
_HAS_HTTPX = False
|
|
86
86
|
|
|
87
87
|
if TYPE_CHECKING:
|
|
@@ -261,7 +261,10 @@ async def safe_request(
|
|
|
261
261
|
|
|
262
262
|
async def _do_request() -> httpx.Response:
|
|
263
263
|
async with httpx.AsyncClient(timeout=timeout) as client: # nosemgrep
|
|
264
|
-
|
|
264
|
+
request_func = cast(
|
|
265
|
+
Callable[..., Awaitable[httpx.Response]], client.request
|
|
266
|
+
)
|
|
267
|
+
response = await request_func(method, url, **kwargs)
|
|
265
268
|
return response
|
|
266
269
|
|
|
267
270
|
return await _execute_with_retries(
|
|
@@ -379,7 +382,10 @@ class SafeHttpClient:
|
|
|
379
382
|
async def _do_request() -> httpx.Response:
|
|
380
383
|
# We explicitly verified client is not None above
|
|
381
384
|
client: httpx.AsyncClient = cast(httpx.AsyncClient, self._client)
|
|
382
|
-
|
|
385
|
+
request_func = cast(
|
|
386
|
+
Callable[..., Awaitable[httpx.Response]], client.request
|
|
387
|
+
)
|
|
388
|
+
response = await request_func(method, url, **kwargs)
|
|
383
389
|
return response
|
|
384
390
|
|
|
385
391
|
return await _execute_with_retries(
|
|
@@ -80,7 +80,7 @@ def _check_jit_available() -> bool:
|
|
|
80
80
|
|
|
81
81
|
JIT is available in Python 3.13+ when built with --enable-experimental-jit.
|
|
82
82
|
"""
|
|
83
|
-
if not PY313:
|
|
83
|
+
if not PY313:
|
|
84
84
|
return False
|
|
85
85
|
|
|
86
86
|
try:
|
|
@@ -96,7 +96,7 @@ def _check_free_threading_available() -> bool:
|
|
|
96
96
|
|
|
97
97
|
Free-threading is available in Python 3.13+ experimental builds.
|
|
98
98
|
"""
|
|
99
|
-
if not PY313:
|
|
99
|
+
if not PY313:
|
|
100
100
|
return False
|
|
101
101
|
|
|
102
102
|
try:
|
|
@@ -85,7 +85,13 @@ def safe(
|
|
|
85
85
|
Err(ValueError("invalid literal for int()..."))
|
|
86
86
|
|
|
87
87
|
"""
|
|
88
|
+
# Pre-cache constructors for minor speedup in tight loops
|
|
89
|
+
# (LOAD_DEREF is faster than LOAD_GLOBAL)
|
|
90
|
+
ok_cls = Ok
|
|
91
|
+
err_cls = Err
|
|
92
|
+
|
|
88
93
|
if inspect.iscoroutinefunction(func):
|
|
94
|
+
# Cast once here to satisfy mypy inside the closure
|
|
89
95
|
func_coro = cast(Callable[P, Awaitable[T]], func)
|
|
90
96
|
|
|
91
97
|
@functools.wraps(func)
|
|
@@ -94,20 +100,21 @@ def safe(
|
|
|
94
100
|
**kwargs: P.kwargs,
|
|
95
101
|
) -> Result[T, Exception]:
|
|
96
102
|
try:
|
|
97
|
-
return
|
|
103
|
+
return ok_cls(await func_coro(*args, **kwargs))
|
|
98
104
|
except Exception as e:
|
|
99
|
-
return
|
|
105
|
+
return err_cls(e)
|
|
100
106
|
|
|
101
107
|
return cast(Callable[P, Awaitable[Result[T, Exception]]], async_wrapper)
|
|
102
108
|
|
|
109
|
+
# Cast once here to satisfy mypy inside the closure
|
|
103
110
|
func_sync = cast(Callable[P, T], func)
|
|
104
111
|
|
|
105
112
|
@functools.wraps(func)
|
|
106
113
|
def wrapper(*args: P.args, **kwargs: P.kwargs) -> Result[T, Exception]:
|
|
107
114
|
try:
|
|
108
|
-
return
|
|
115
|
+
return ok_cls(func_sync(*args, **kwargs))
|
|
109
116
|
except Exception as e:
|
|
110
|
-
return
|
|
117
|
+
return err_cls(e)
|
|
111
118
|
|
|
112
119
|
return cast(Callable[P, Result[T, Exception]], wrapper)
|
|
113
120
|
|
|
@@ -202,19 +209,21 @@ def collect_results(
|
|
|
202
209
|
except AttributeError:
|
|
203
210
|
pass
|
|
204
211
|
|
|
212
|
+
ok_cls = Ok
|
|
213
|
+
err_cls = Err
|
|
205
214
|
values: list[T] = []
|
|
206
215
|
append = values.append
|
|
207
216
|
for result in results:
|
|
208
|
-
# We
|
|
209
|
-
#
|
|
210
|
-
|
|
211
|
-
if isinstance(result, Ok):
|
|
217
|
+
# We use explicit type checks (isinstance) but pre-cache the constructors.
|
|
218
|
+
# type(result) is ok_cls would be even faster but breaks subclassing.
|
|
219
|
+
if isinstance(result, ok_cls):
|
|
212
220
|
append(result.ok_value)
|
|
213
|
-
elif isinstance(result,
|
|
221
|
+
elif isinstance(result, err_cls):
|
|
214
222
|
return result
|
|
215
223
|
else:
|
|
224
|
+
# Fallback for structural compatibility
|
|
216
225
|
return result
|
|
217
|
-
return
|
|
226
|
+
return ok_cls(values)
|
|
218
227
|
|
|
219
228
|
|
|
220
229
|
@overload
|
|
@@ -27,12 +27,12 @@ class CircuitBreakerDecorator(Protocol):
|
|
|
27
27
|
"""Protocol for the circuit breaker decorator."""
|
|
28
28
|
|
|
29
29
|
@overload
|
|
30
|
-
def __call__(self, func: Callable[P, R]) -> Callable[P, R]: ...
|
|
30
|
+
def __call__(self, func: Callable[P, R]) -> Callable[P, R]: ...
|
|
31
31
|
|
|
32
32
|
@overload
|
|
33
33
|
def __call__(
|
|
34
34
|
self, func: Callable[P, Awaitable[R]]
|
|
35
|
-
) -> Callable[P, Awaitable[R]]: ...
|
|
35
|
+
) -> Callable[P, Awaitable[R]]: ...
|
|
36
36
|
|
|
37
37
|
|
|
38
38
|
logger = logging.getLogger("taipanstack.resilience.circuit_breaker")
|
|
@@ -42,7 +42,7 @@ try:
|
|
|
42
42
|
|
|
43
43
|
_structlog_logger = _structlog.get_logger("taipanstack.resilience.circuit_breaker")
|
|
44
44
|
_HAS_STRUCTLOG = True
|
|
45
|
-
except ImportError:
|
|
45
|
+
except ImportError:
|
|
46
46
|
_structlog_logger = None
|
|
47
47
|
_HAS_STRUCTLOG = False
|
|
48
48
|
|
|
@@ -89,6 +89,15 @@ class CircuitBreakerConfig:
|
|
|
89
89
|
excluded_exceptions: tuple[type[Exception], ...] = ()
|
|
90
90
|
failure_exceptions: tuple[type[Exception], ...] = (Exception,)
|
|
91
91
|
|
|
92
|
+
def __post_init__(self) -> None:
|
|
93
|
+
"""Validate configuration values."""
|
|
94
|
+
if not math.isfinite(self.failure_threshold):
|
|
95
|
+
raise ValueError("failure_threshold must be finite")
|
|
96
|
+
if not math.isfinite(self.success_threshold):
|
|
97
|
+
raise ValueError("success_threshold must be finite")
|
|
98
|
+
if not math.isfinite(self.timeout):
|
|
99
|
+
raise ValueError("timeout must be finite")
|
|
100
|
+
|
|
92
101
|
|
|
93
102
|
@dataclass
|
|
94
103
|
class CircuitBreakerState:
|
|
@@ -250,20 +259,28 @@ class CircuitBreaker:
|
|
|
250
259
|
return self._handle_open_state()
|
|
251
260
|
|
|
252
261
|
case CircuitState.HALF_OPEN:
|
|
262
|
+
# Protect against NaN/Inf state corruption
|
|
263
|
+
if not math.isfinite(self._state.half_open_attempts):
|
|
264
|
+
# Block attempt to prevent thundering herd when corrupted
|
|
265
|
+
return False
|
|
266
|
+
|
|
253
267
|
# Allow limited attempts to prevent thundering herd
|
|
254
268
|
if self._state.half_open_attempts < self.config.success_threshold:
|
|
255
269
|
self._state.half_open_attempts += 1
|
|
256
270
|
return True
|
|
257
271
|
return False
|
|
258
272
|
|
|
259
|
-
return False
|
|
273
|
+
return False
|
|
260
274
|
|
|
261
275
|
def _record_success(self) -> None:
|
|
262
276
|
"""Record a successful call."""
|
|
263
277
|
with self._state.lock:
|
|
264
278
|
match self._state.state:
|
|
265
279
|
case CircuitState.HALF_OPEN:
|
|
280
|
+
if not math.isfinite(self._state.success_count):
|
|
281
|
+
self._state.success_count = 0
|
|
266
282
|
self._state.success_count += 1
|
|
283
|
+
|
|
267
284
|
if self._state.success_count >= self.config.success_threshold:
|
|
268
285
|
self._state.state = CircuitState.CLOSED
|
|
269
286
|
self._state.failure_count = 0
|
|
@@ -291,9 +308,8 @@ class CircuitBreaker:
|
|
|
291
308
|
self._state.state = CircuitState.OPEN
|
|
292
309
|
self._state.half_open_attempts = 0
|
|
293
310
|
logger.warning(
|
|
294
|
-
"Circuit %s reopened after failure in half-open
|
|
311
|
+
"Circuit %s reopened after failure in half-open",
|
|
295
312
|
self.name,
|
|
296
|
-
self._state.failure_count,
|
|
297
313
|
)
|
|
298
314
|
self._notify_state_change(
|
|
299
315
|
CircuitState.HALF_OPEN,
|
|
@@ -302,6 +318,19 @@ class CircuitBreaker:
|
|
|
302
318
|
|
|
303
319
|
def _handle_failure_closed(self) -> None:
|
|
304
320
|
"""Handle failure when in CLOSED state."""
|
|
321
|
+
# Check against corrupted NaN/Inf failure_count
|
|
322
|
+
if not math.isfinite(self._state.failure_count):
|
|
323
|
+
self._state.state = CircuitState.OPEN
|
|
324
|
+
logger.warning(
|
|
325
|
+
"Circuit %s opened due to state corruption (NaN/Inf failures)",
|
|
326
|
+
self.name,
|
|
327
|
+
)
|
|
328
|
+
self._notify_state_change(
|
|
329
|
+
CircuitState.CLOSED,
|
|
330
|
+
CircuitState.OPEN,
|
|
331
|
+
)
|
|
332
|
+
return
|
|
333
|
+
|
|
305
334
|
if self._state.failure_count >= self.config.failure_threshold:
|
|
306
335
|
self._state.state = CircuitState.OPEN
|
|
307
336
|
logger.warning(
|
|
@@ -322,7 +351,13 @@ class CircuitBreaker:
|
|
|
322
351
|
return
|
|
323
352
|
|
|
324
353
|
with self._state.lock:
|
|
325
|
-
|
|
354
|
+
# First handle corruption
|
|
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
|
+
|
|
326
361
|
now = time.monotonic()
|
|
327
362
|
if math.isfinite(now):
|
|
328
363
|
self._state.last_failure_time = now
|
|
@@ -346,6 +381,41 @@ class CircuitBreaker:
|
|
|
346
381
|
self._state.half_open_attempts = 0
|
|
347
382
|
logger.info("Circuit %s manually reset", self.name)
|
|
348
383
|
|
|
384
|
+
def _process_result(self, result: R) -> R:
|
|
385
|
+
"""Process Result outcome and record success/failure.
|
|
386
|
+
|
|
387
|
+
Args:
|
|
388
|
+
result: The result to process.
|
|
389
|
+
|
|
390
|
+
Returns:
|
|
391
|
+
The original result.
|
|
392
|
+
|
|
393
|
+
"""
|
|
394
|
+
if isinstance(result, Err):
|
|
395
|
+
err_val = result.unwrap_err()
|
|
396
|
+
if isinstance(err_val, self.config.failure_exceptions):
|
|
397
|
+
self._record_failure(err_val)
|
|
398
|
+
return result
|
|
399
|
+
# Ignored exception in Result monad
|
|
400
|
+
return result
|
|
401
|
+
self._record_success()
|
|
402
|
+
return result
|
|
403
|
+
|
|
404
|
+
def _decrement_half_open(self, is_half_open: bool) -> None:
|
|
405
|
+
"""Decrement half-open attempt count if applicable.
|
|
406
|
+
|
|
407
|
+
Args:
|
|
408
|
+
is_half_open: Whether the circuit was half-open before attempt.
|
|
409
|
+
|
|
410
|
+
"""
|
|
411
|
+
if is_half_open:
|
|
412
|
+
with self._state.lock:
|
|
413
|
+
if (
|
|
414
|
+
self._state.state == CircuitState.HALF_OPEN
|
|
415
|
+
and self._state.half_open_attempts > 0
|
|
416
|
+
):
|
|
417
|
+
self._state.half_open_attempts -= 1
|
|
418
|
+
|
|
349
419
|
def __call__(
|
|
350
420
|
self, func: Callable[P, R] | Callable[P, Awaitable[R]]
|
|
351
421
|
) -> Callable[P, R] | Callable[P, Awaitable[R]]:
|
|
@@ -365,26 +435,12 @@ class CircuitBreaker:
|
|
|
365
435
|
|
|
366
436
|
try:
|
|
367
437
|
result = await func_coro(*args, **kwargs)
|
|
368
|
-
|
|
369
|
-
err_val = result.unwrap_err()
|
|
370
|
-
if isinstance(err_val, self.config.failure_exceptions):
|
|
371
|
-
self._record_failure(err_val)
|
|
372
|
-
return result
|
|
373
|
-
# Ignored exception in Result monad
|
|
374
|
-
return result
|
|
375
|
-
self._record_success()
|
|
376
|
-
return result
|
|
438
|
+
return self._process_result(result)
|
|
377
439
|
except self.config.failure_exceptions as e:
|
|
378
440
|
self._record_failure(e)
|
|
379
441
|
raise
|
|
380
442
|
finally:
|
|
381
|
-
|
|
382
|
-
with self._state.lock:
|
|
383
|
-
if (
|
|
384
|
-
self._state.state == CircuitState.HALF_OPEN
|
|
385
|
-
and self._state.half_open_attempts > 0
|
|
386
|
-
):
|
|
387
|
-
self._state.half_open_attempts -= 1
|
|
443
|
+
self._decrement_half_open(is_half_open)
|
|
388
444
|
|
|
389
445
|
return async_wrapper
|
|
390
446
|
|
|
@@ -402,26 +458,12 @@ class CircuitBreaker:
|
|
|
402
458
|
|
|
403
459
|
try:
|
|
404
460
|
result = func_sync(*args, **kwargs)
|
|
405
|
-
|
|
406
|
-
err_val = result.unwrap_err()
|
|
407
|
-
if isinstance(err_val, self.config.failure_exceptions):
|
|
408
|
-
self._record_failure(err_val)
|
|
409
|
-
return result
|
|
410
|
-
# Ignored exception in Result monad
|
|
411
|
-
return result
|
|
412
|
-
self._record_success()
|
|
413
|
-
return result
|
|
461
|
+
return self._process_result(result)
|
|
414
462
|
except self.config.failure_exceptions as e:
|
|
415
463
|
self._record_failure(e)
|
|
416
464
|
raise
|
|
417
465
|
finally:
|
|
418
|
-
|
|
419
|
-
with self._state.lock:
|
|
420
|
-
if (
|
|
421
|
-
self._state.state == CircuitState.HALF_OPEN
|
|
422
|
-
and self._state.half_open_attempts > 0
|
|
423
|
-
):
|
|
424
|
-
self._state.half_open_attempts -= 1
|
|
466
|
+
self._decrement_half_open(is_half_open)
|
|
425
467
|
|
|
426
468
|
return wrapper
|
|
427
469
|
|
|
@@ -26,14 +26,10 @@ class FallbackDecorator(Protocol):
|
|
|
26
26
|
"""Protocol for the fallback decorator."""
|
|
27
27
|
|
|
28
28
|
@overload
|
|
29
|
-
def __call__(
|
|
30
|
-
self, func: ResultFunc[P, T, E]
|
|
31
|
-
) -> ResultFunc[P, T, E]: ... # pragma: no cover
|
|
29
|
+
def __call__(self, func: ResultFunc[P, T, E]) -> ResultFunc[P, T, E]: ...
|
|
32
30
|
|
|
33
31
|
@overload
|
|
34
|
-
def __call__(
|
|
35
|
-
self, func: AsyncResultFunc[P, T, E]
|
|
36
|
-
) -> AsyncResultFunc[P, T, E]: ... # pragma: no cover
|
|
32
|
+
def __call__(self, func: AsyncResultFunc[P, T, E]) -> AsyncResultFunc[P, T, E]: ...
|
|
37
33
|
|
|
38
34
|
|
|
39
35
|
def fallback(
|
|
@@ -72,7 +68,7 @@ def fallback(
|
|
|
72
68
|
return result
|
|
73
69
|
except exceptions:
|
|
74
70
|
return Ok(fallback_value)
|
|
75
|
-
return Err(cast(E, RuntimeError("Unreachable")))
|
|
71
|
+
return Err(cast(E, RuntimeError("Unreachable")))
|
|
76
72
|
|
|
77
73
|
return async_wrapper
|
|
78
74
|
|
|
@@ -89,7 +85,7 @@ def fallback(
|
|
|
89
85
|
return result
|
|
90
86
|
except exceptions:
|
|
91
87
|
return Ok(fallback_value)
|
|
92
|
-
return Err(cast(E, RuntimeError("Unreachable")))
|
|
88
|
+
return Err(cast(E, RuntimeError("Unreachable")))
|
|
93
89
|
|
|
94
90
|
return sync_wrapper
|
|
95
91
|
|
|
@@ -102,12 +98,12 @@ class TimeoutDecorator(Protocol):
|
|
|
102
98
|
@overload
|
|
103
99
|
def __call__(
|
|
104
100
|
self, func: ResultFunc[P, T, E]
|
|
105
|
-
) -> Callable[P, Result[T, TimeoutError | E]]: ...
|
|
101
|
+
) -> Callable[P, Result[T, TimeoutError | E]]: ...
|
|
106
102
|
|
|
107
103
|
@overload
|
|
108
104
|
def __call__(
|
|
109
105
|
self, func: AsyncResultFunc[P, T, E]
|
|
110
|
-
) -> Callable[P, Awaitable[Result[T, TimeoutError | E]]]: ...
|
|
106
|
+
) -> Callable[P, Awaitable[Result[T, TimeoutError | E]]]: ...
|
|
111
107
|
|
|
112
108
|
|
|
113
109
|
def timeout(seconds: float) -> TimeoutDecorator:
|
|
@@ -28,12 +28,12 @@ class RetryDecorator(Protocol):
|
|
|
28
28
|
"""Protocol for the retry decorator."""
|
|
29
29
|
|
|
30
30
|
@overload
|
|
31
|
-
def __call__(self, func: Callable[P, R]) -> Callable[P, R]: ...
|
|
31
|
+
def __call__(self, func: Callable[P, R]) -> Callable[P, R]: ...
|
|
32
32
|
|
|
33
33
|
@overload
|
|
34
34
|
def __call__(
|
|
35
35
|
self, func: Callable[P, Awaitable[R]]
|
|
36
|
-
) -> Callable[P, Awaitable[R]]: ...
|
|
36
|
+
) -> Callable[P, Awaitable[R]]: ...
|
|
37
37
|
|
|
38
38
|
|
|
39
39
|
logger = logging.getLogger("taipanstack.resilience.retry")
|
|
@@ -43,7 +43,7 @@ try:
|
|
|
43
43
|
|
|
44
44
|
_structlog_logger = _structlog.get_logger("taipanstack.resilience.retry")
|
|
45
45
|
_HAS_STRUCTLOG = True
|
|
46
|
-
except ImportError:
|
|
46
|
+
except ImportError:
|
|
47
47
|
_structlog_logger = None
|
|
48
48
|
_HAS_STRUCTLOG = False
|
|
49
49
|
|
|
@@ -163,14 +163,14 @@ def calculate_delay(
|
|
|
163
163
|
return delay
|
|
164
164
|
|
|
165
165
|
|
|
166
|
-
def
|
|
166
|
+
def _invoke_retry_callback(
|
|
167
167
|
func_name: str,
|
|
168
168
|
attempt: int,
|
|
169
169
|
exc: Exception,
|
|
170
170
|
delay: float,
|
|
171
171
|
config: RetryConfig,
|
|
172
172
|
) -> None:
|
|
173
|
-
"""
|
|
173
|
+
"""Invoke the retry callback if set, or emit structured log.
|
|
174
174
|
|
|
175
175
|
Args:
|
|
176
176
|
func_name: Name of the retried function.
|
|
@@ -180,17 +180,6 @@ def _log_retry_attempt(
|
|
|
180
180
|
config: Retry configuration.
|
|
181
181
|
|
|
182
182
|
"""
|
|
183
|
-
if config.log_retries:
|
|
184
|
-
logger.info(
|
|
185
|
-
"Attempt %d/%d failed for %s: %s. Retrying in %.2f seconds...",
|
|
186
|
-
attempt,
|
|
187
|
-
config.max_attempts,
|
|
188
|
-
func_name,
|
|
189
|
-
str(exc),
|
|
190
|
-
delay,
|
|
191
|
-
)
|
|
192
|
-
|
|
193
|
-
# Invoke callback or emit structured log if no callback set
|
|
194
183
|
if config.on_retry is not None:
|
|
195
184
|
try:
|
|
196
185
|
config.on_retry(attempt, config.max_attempts, exc, delay)
|
|
@@ -218,6 +207,36 @@ def _log_retry_attempt(
|
|
|
218
207
|
)
|
|
219
208
|
|
|
220
209
|
|
|
210
|
+
def _log_retry_attempt(
|
|
211
|
+
func_name: str,
|
|
212
|
+
attempt: int,
|
|
213
|
+
exc: Exception,
|
|
214
|
+
delay: float,
|
|
215
|
+
config: RetryConfig,
|
|
216
|
+
) -> None:
|
|
217
|
+
"""Log a retry attempt via callback, structlog, or stdlib logger.
|
|
218
|
+
|
|
219
|
+
Args:
|
|
220
|
+
func_name: Name of the retried function.
|
|
221
|
+
attempt: Current attempt number.
|
|
222
|
+
exc: The exception that triggered the retry.
|
|
223
|
+
delay: Delay in seconds before the next attempt.
|
|
224
|
+
config: Retry configuration.
|
|
225
|
+
|
|
226
|
+
"""
|
|
227
|
+
if config.log_retries:
|
|
228
|
+
logger.info(
|
|
229
|
+
"Attempt %d/%d failed for %s: %s. Retrying in %.2f seconds...",
|
|
230
|
+
attempt,
|
|
231
|
+
config.max_attempts,
|
|
232
|
+
func_name,
|
|
233
|
+
str(exc),
|
|
234
|
+
delay,
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
_invoke_retry_callback(func_name, attempt, exc, delay, config)
|
|
238
|
+
|
|
239
|
+
|
|
221
240
|
def _log_all_failed(
|
|
222
241
|
func_name: str,
|
|
223
242
|
exc: Exception,
|
|
@@ -233,7 +233,7 @@ def timeout(
|
|
|
233
233
|
and threading.current_thread() is threading.main_thread()
|
|
234
234
|
)
|
|
235
235
|
|
|
236
|
-
if can_use_signal:
|
|
236
|
+
if can_use_signal:
|
|
237
237
|
return _timeout_with_signal(
|
|
238
238
|
func,
|
|
239
239
|
seconds,
|
|
@@ -252,7 +252,7 @@ def timeout(
|
|
|
252
252
|
return decorator
|
|
253
253
|
|
|
254
254
|
|
|
255
|
-
def _timeout_with_signal(
|
|
255
|
+
def _timeout_with_signal(
|
|
256
256
|
func: Callable[..., R],
|
|
257
257
|
seconds: float,
|
|
258
258
|
args: tuple[object, ...],
|
|
@@ -321,27 +321,7 @@ def guard_command_injection(
|
|
|
321
321
|
return cmd_list
|
|
322
322
|
|
|
323
323
|
|
|
324
|
-
def
|
|
325
|
-
filename: str | Path,
|
|
326
|
-
*,
|
|
327
|
-
allowed_extensions: Sequence[str] | None = None,
|
|
328
|
-
denied_extensions: Sequence[str] | None = None,
|
|
329
|
-
) -> Path:
|
|
330
|
-
"""Validate file extension against allow/deny lists.
|
|
331
|
-
|
|
332
|
-
Args:
|
|
333
|
-
filename: The filename to check.
|
|
334
|
-
allowed_extensions: Extensions to allow (with or without dot).
|
|
335
|
-
denied_extensions: Extensions to deny (with or without dot).
|
|
336
|
-
|
|
337
|
-
Returns:
|
|
338
|
-
The filename as a Path.
|
|
339
|
-
|
|
340
|
-
Raises:
|
|
341
|
-
SecurityError: If extension is not allowed or is denied.
|
|
342
|
-
|
|
343
|
-
"""
|
|
344
|
-
filename_str = str(filename)
|
|
324
|
+
def _check_filename_null_bytes(filename_str: str) -> None:
|
|
345
325
|
if "\x00" in filename_str:
|
|
346
326
|
raise SecurityError(
|
|
347
327
|
"Filename contains null bytes",
|
|
@@ -349,8 +329,8 @@ def guard_file_extension(
|
|
|
349
329
|
value=filename_str,
|
|
350
330
|
)
|
|
351
331
|
|
|
352
|
-
|
|
353
|
-
|
|
332
|
+
|
|
333
|
+
def _clean_filename_end(clean_name: str) -> str:
|
|
354
334
|
while clean_name:
|
|
355
335
|
char = clean_name[-1]
|
|
356
336
|
if (
|
|
@@ -361,15 +341,18 @@ def guard_file_extension(
|
|
|
361
341
|
clean_name = clean_name[:-1]
|
|
362
342
|
else:
|
|
363
343
|
break
|
|
344
|
+
return clean_name
|
|
364
345
|
|
|
365
|
-
ext = "" if not clean_name else Path(clean_name).suffix.lower().lstrip(".")
|
|
366
346
|
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
347
|
+
def _normalize_ext(e: str) -> str:
|
|
348
|
+
return e.lower().lstrip(".")
|
|
349
|
+
|
|
370
350
|
|
|
351
|
+
def _check_denied_extension(
|
|
352
|
+
ext: str, original_name: str, denied_extensions: Sequence[str] | None
|
|
353
|
+
) -> None:
|
|
371
354
|
if denied_extensions is not None:
|
|
372
|
-
denied = frozenset(
|
|
355
|
+
denied = frozenset(_normalize_ext(e) for e in denied_extensions)
|
|
373
356
|
else:
|
|
374
357
|
denied = _DEFAULT_DENIED_EXTENSIONS
|
|
375
358
|
|
|
@@ -377,18 +360,54 @@ def guard_file_extension(
|
|
|
377
360
|
raise SecurityError(
|
|
378
361
|
f"File extension '{ext}' is not allowed",
|
|
379
362
|
guard_name="file_extension",
|
|
380
|
-
value=
|
|
363
|
+
value=original_name,
|
|
381
364
|
)
|
|
382
365
|
|
|
366
|
+
|
|
367
|
+
def _check_allowed_extension(
|
|
368
|
+
ext: str, original_name: str, allowed_extensions: Sequence[str] | None
|
|
369
|
+
) -> None:
|
|
383
370
|
if allowed_extensions is not None: # pragma: no branch
|
|
384
|
-
allowed = {
|
|
371
|
+
allowed = {_normalize_ext(e) for e in allowed_extensions}
|
|
385
372
|
if ext not in allowed:
|
|
386
373
|
raise SecurityError(
|
|
387
374
|
f"File extension '{ext}' is not in allowed list",
|
|
388
375
|
guard_name="file_extension",
|
|
389
|
-
value=
|
|
376
|
+
value=original_name,
|
|
390
377
|
)
|
|
391
378
|
|
|
379
|
+
|
|
380
|
+
def guard_file_extension(
|
|
381
|
+
filename: str | Path,
|
|
382
|
+
*,
|
|
383
|
+
allowed_extensions: Sequence[str] | None = None,
|
|
384
|
+
denied_extensions: Sequence[str] | None = None,
|
|
385
|
+
) -> Path:
|
|
386
|
+
"""Validate file extension against allow/deny lists.
|
|
387
|
+
|
|
388
|
+
Args:
|
|
389
|
+
filename: The filename to check.
|
|
390
|
+
allowed_extensions: Extensions to allow (with or without dot).
|
|
391
|
+
denied_extensions: Extensions to deny (with or without dot).
|
|
392
|
+
|
|
393
|
+
Returns:
|
|
394
|
+
The filename as a Path.
|
|
395
|
+
|
|
396
|
+
Raises:
|
|
397
|
+
SecurityError: If extension is not allowed or is denied.
|
|
398
|
+
|
|
399
|
+
"""
|
|
400
|
+
filename_str = str(filename)
|
|
401
|
+
_check_filename_null_bytes(filename_str)
|
|
402
|
+
|
|
403
|
+
path = Path(filename)
|
|
404
|
+
clean_name = _clean_filename_end(path.name)
|
|
405
|
+
|
|
406
|
+
ext = "" if not clean_name else Path(clean_name).suffix.lower().lstrip(".")
|
|
407
|
+
|
|
408
|
+
_check_denied_extension(ext, str(path.name), denied_extensions)
|
|
409
|
+
_check_allowed_extension(ext, str(path.name), allowed_extensions)
|
|
410
|
+
|
|
392
411
|
return path
|
|
393
412
|
|
|
394
413
|
|
|
@@ -491,11 +510,7 @@ def guard_env_variable(
|
|
|
491
510
|
_ALLOWED_SSRF_SCHEMES: frozenset[str] = frozenset({"http", "https"})
|
|
492
511
|
|
|
493
512
|
|
|
494
|
-
def
|
|
495
|
-
url: str,
|
|
496
|
-
allowed_schemes: frozenset[str],
|
|
497
|
-
) -> Result[str, SecurityError]:
|
|
498
|
-
"""Validate the URL format, scheme, and presence of hostname."""
|
|
513
|
+
def _validate_ssrf_url_type_and_length(url: str) -> Result[str, SecurityError]:
|
|
499
514
|
if not isinstance(url, str):
|
|
500
515
|
return Err(
|
|
501
516
|
SecurityError(
|
|
@@ -515,7 +530,12 @@ def _validate_ssrf_url( # noqa: PLR0911
|
|
|
515
530
|
value=url[:80],
|
|
516
531
|
)
|
|
517
532
|
)
|
|
533
|
+
return Ok(url)
|
|
534
|
+
|
|
518
535
|
|
|
536
|
+
def _validate_ssrf_url_parse(
|
|
537
|
+
url: str, allowed_schemes: frozenset[str]
|
|
538
|
+
) -> Result[str, SecurityError]:
|
|
519
539
|
try:
|
|
520
540
|
parsed = urlsplit(url)
|
|
521
541
|
except ValueError as exc:
|
|
@@ -549,6 +569,18 @@ def _validate_ssrf_url( # noqa: PLR0911
|
|
|
549
569
|
return Ok(hostname)
|
|
550
570
|
|
|
551
571
|
|
|
572
|
+
def _validate_ssrf_url(
|
|
573
|
+
url: str,
|
|
574
|
+
allowed_schemes: frozenset[str],
|
|
575
|
+
) -> Result[str, SecurityError]:
|
|
576
|
+
"""Validate the URL format, scheme, and presence of hostname."""
|
|
577
|
+
type_len_res = _validate_ssrf_url_type_and_length(url)
|
|
578
|
+
if not isinstance(type_len_res, Ok):
|
|
579
|
+
return type_len_res
|
|
580
|
+
|
|
581
|
+
return _validate_ssrf_url_parse(url, allowed_schemes)
|
|
582
|
+
|
|
583
|
+
|
|
552
584
|
@functools.lru_cache(maxsize=1024)
|
|
553
585
|
def _is_ip_safe(raw_ip: str) -> bool:
|
|
554
586
|
"""Check if a single IP address is safe (not private/loopback/reserved)."""
|
|
@@ -10,8 +10,6 @@ import secrets
|
|
|
10
10
|
from collections.abc import Iterable
|
|
11
11
|
from typing import TYPE_CHECKING, TypeAlias
|
|
12
12
|
|
|
13
|
-
from typing_extensions import TypedDict
|
|
14
|
-
|
|
15
13
|
if TYPE_CHECKING:
|
|
16
14
|
import jwt
|
|
17
15
|
|
|
@@ -85,24 +83,15 @@ def decode_jwt(
|
|
|
85
83
|
):
|
|
86
84
|
raise ValueError('Algorithm "none" is explicitly disallowed for decoding.')
|
|
87
85
|
|
|
88
|
-
class JWTOptions(TypedDict, total=False):
|
|
89
|
-
require: list[str]
|
|
90
|
-
verify_signature: bool
|
|
91
|
-
verify_exp: bool
|
|
92
|
-
verify_aud: bool
|
|
93
|
-
|
|
94
|
-
# We enforce 'exp' and 'aud' through PyJWT's options parameter
|
|
95
|
-
options: JWTOptions = {
|
|
96
|
-
"require": ["exp", "aud"],
|
|
97
|
-
"verify_signature": True,
|
|
98
|
-
"verify_exp": True,
|
|
99
|
-
"verify_aud": True,
|
|
100
|
-
}
|
|
101
|
-
|
|
102
86
|
return jwt.decode(
|
|
103
87
|
token,
|
|
104
88
|
secret_key,
|
|
105
89
|
algorithms=algorithms,
|
|
106
90
|
audience=audience,
|
|
107
|
-
options=
|
|
91
|
+
options={
|
|
92
|
+
"require": ["exp", "aud"],
|
|
93
|
+
"verify_signature": True,
|
|
94
|
+
"verify_exp": True,
|
|
95
|
+
"verify_aud": True,
|
|
96
|
+
},
|
|
108
97
|
)
|
|
@@ -104,9 +104,6 @@ class SecureBaseModel(BaseModel):
|
|
|
104
104
|
) -> dict[str, object]:
|
|
105
105
|
"""Dump the model to a dictionary, redacting sensitive fields.
|
|
106
106
|
|
|
107
|
-
Args:
|
|
108
|
-
**kwargs: Arguments to pass to Pydantic's model_dump.
|
|
109
|
-
|
|
110
107
|
Returns:
|
|
111
108
|
The redacting dictionary representation of the model.
|
|
112
109
|
|
|
@@ -150,9 +147,6 @@ class SecureBaseModel(BaseModel):
|
|
|
150
147
|
) -> str:
|
|
151
148
|
"""Dump the model to a JSON string, redacting sensitive fields.
|
|
152
149
|
|
|
153
|
-
Args:
|
|
154
|
-
**kwargs: Arguments to pass to Pydantic's model_dump.
|
|
155
|
-
|
|
156
150
|
Returns:
|
|
157
151
|
The redacted JSON string representation of the model.
|
|
158
152
|
|
|
@@ -10,6 +10,7 @@ from pathlib import Path
|
|
|
10
10
|
|
|
11
11
|
# Constants to avoid magic values (PLR2004)
|
|
12
12
|
MAX_SQL_IDENTIFIER_LENGTH = 128 # pragma: no mutate
|
|
13
|
+
MAX_PATH_LENGTH = 4096 # pragma: no mutate
|
|
13
14
|
|
|
14
15
|
# Pre-compiled regex and sets for Performance Benchmarks
|
|
15
16
|
_INVALID_FILENAME_CHARS_RE = re.compile(r'[<>:"/\\|?*\x00-\x1f]') # pragma: no mutate
|
|
@@ -348,10 +349,16 @@ def sanitize_path(
|
|
|
348
349
|
|
|
349
350
|
"""
|
|
350
351
|
if isinstance(path, str):
|
|
352
|
+
if len(path) > MAX_PATH_LENGTH:
|
|
353
|
+
msg = "Path length exceeds maximum allowed"
|
|
354
|
+
raise ValueError(msg)
|
|
351
355
|
if "\x00" in path: # pragma: no branch
|
|
352
356
|
path = path.replace("\x00", "")
|
|
353
357
|
path = Path(path)
|
|
354
358
|
else: # pragma: no branch
|
|
359
|
+
if len(str(path)) > MAX_PATH_LENGTH:
|
|
360
|
+
msg = "Path length exceeds maximum allowed"
|
|
361
|
+
raise ValueError(msg)
|
|
355
362
|
path = Path(path)
|
|
356
363
|
|
|
357
364
|
# Clean components
|
|
@@ -29,12 +29,12 @@ class CacheDecorator(Protocol):
|
|
|
29
29
|
@overload
|
|
30
30
|
def __call__(
|
|
31
31
|
self, func: Callable[P, Result[T, E]]
|
|
32
|
-
) -> Callable[P, Result[T, E]]: ...
|
|
32
|
+
) -> Callable[P, Result[T, E]]: ...
|
|
33
33
|
|
|
34
34
|
@overload
|
|
35
35
|
def __call__(
|
|
36
36
|
self, func: Callable[P, Awaitable[Result[T, E]]]
|
|
37
|
-
) -> Callable[P, Awaitable[Result[T, E]]]: ...
|
|
37
|
+
) -> Callable[P, Awaitable[Result[T, E]]]: ...
|
|
38
38
|
|
|
39
39
|
|
|
40
40
|
def cached(ttl: float) -> CacheDecorator: # noqa: PLR0915
|
|
@@ -41,12 +41,12 @@ class ConcurrencyLimitDecorator(Protocol):
|
|
|
41
41
|
@overload
|
|
42
42
|
def __call__(
|
|
43
43
|
self, func: Callable[P, T]
|
|
44
|
-
) -> Callable[P, Result[T, OverloadError]]: ...
|
|
44
|
+
) -> Callable[P, Result[T, OverloadError]]: ...
|
|
45
45
|
|
|
46
46
|
@overload
|
|
47
47
|
def __call__(
|
|
48
48
|
self, func: Callable[P, Awaitable[T]]
|
|
49
|
-
) -> Callable[P, Awaitable[Result[T, OverloadError]]]: ...
|
|
49
|
+
) -> Callable[P, Awaitable[Result[T, OverloadError]]]: ...
|
|
50
50
|
|
|
51
51
|
|
|
52
52
|
def _handle_async_concurrency(
|
|
@@ -57,6 +57,35 @@ class RateLimiter:
|
|
|
57
57
|
self.last_update: float = time.monotonic()
|
|
58
58
|
self._lock = threading.Lock()
|
|
59
59
|
|
|
60
|
+
def _add_tokens(self, now: float) -> bool:
|
|
61
|
+
"""Calculate and add new tokens to the bucket based on elapsed time.
|
|
62
|
+
|
|
63
|
+
Args:
|
|
64
|
+
now: Current monotonic time.
|
|
65
|
+
|
|
66
|
+
Returns:
|
|
67
|
+
True if token update succeeds, False if state corruption is detected.
|
|
68
|
+
|
|
69
|
+
"""
|
|
70
|
+
elapsed = max(0.0, now - self.last_update)
|
|
71
|
+
self.last_update = now
|
|
72
|
+
|
|
73
|
+
# Prevent state corruption from raising exceptions or poisoning state
|
|
74
|
+
if not math.isfinite(self.time_window) or self.time_window <= 0.0:
|
|
75
|
+
return False
|
|
76
|
+
|
|
77
|
+
if not math.isfinite(self.capacity) or self.capacity <= 0.0:
|
|
78
|
+
return False
|
|
79
|
+
|
|
80
|
+
# Add tokens for elapsed time based on fill rate
|
|
81
|
+
self.tokens += elapsed * (self.capacity / self.time_window)
|
|
82
|
+
|
|
83
|
+
if not math.isfinite(self.tokens):
|
|
84
|
+
return False
|
|
85
|
+
|
|
86
|
+
self.tokens = min(self.tokens, self.capacity)
|
|
87
|
+
return True
|
|
88
|
+
|
|
60
89
|
def consume(self, tokens: float = 1.0) -> bool:
|
|
61
90
|
"""Try to consume tokens.
|
|
62
91
|
|
|
@@ -82,12 +111,8 @@ class RateLimiter:
|
|
|
82
111
|
return True
|
|
83
112
|
return False
|
|
84
113
|
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
# Add tokens for elapsed time based on fill rate
|
|
89
|
-
self.tokens += elapsed * (self.capacity / self.time_window)
|
|
90
|
-
self.tokens = min(self.tokens, self.capacity)
|
|
114
|
+
if not self._add_tokens(now):
|
|
115
|
+
return False
|
|
91
116
|
|
|
92
117
|
if self.tokens >= tokens:
|
|
93
118
|
self.tokens -= tokens
|
|
@@ -101,12 +126,12 @@ class RateLimitDecorator(Protocol):
|
|
|
101
126
|
@overload
|
|
102
127
|
def __call__(
|
|
103
128
|
self, func: Callable[P, T]
|
|
104
|
-
) -> Callable[P, Result[T, RateLimitError]]: ...
|
|
129
|
+
) -> Callable[P, Result[T, RateLimitError]]: ...
|
|
105
130
|
|
|
106
131
|
@overload
|
|
107
132
|
def __call__(
|
|
108
133
|
self, func: Callable[P, Awaitable[T]]
|
|
109
|
-
) -> Callable[P, Awaitable[Result[T, RateLimitError]]]: ...
|
|
134
|
+
) -> Callable[P, Awaitable[Result[T, RateLimitError]]]: ...
|
|
110
135
|
|
|
111
136
|
|
|
112
137
|
def rate_limit(
|
|
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.4 → taipanstack-0.4.5}/src/taipanstack/resilience/adaptive/adaptive_breaker.py
RENAMED
|
File without changes
|
{taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/resilience/adaptive/adaptive_retry.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{taipanstack-0.4.4 → taipanstack-0.4.5}/src/taipanstack/resilience/watchdogs/health_pinger.py
RENAMED
|
File without changes
|
{taipanstack-0.4.4 → taipanstack-0.4.5}/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
|