taipanstack 0.4.6__tar.gz → 0.4.8__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.8}/PKG-INFO +10 -10
- {taipanstack-0.4.6 → taipanstack-0.4.8}/README.md +9 -9
- {taipanstack-0.4.6 → taipanstack-0.4.8}/pyproject.toml +2 -2
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/__init__.py +1 -1
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/bridges/db_bridge.py +31 -10
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/bridges/http_bridge.py +48 -22
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/bridges/web_bridge.py +57 -29
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/core/compat.py +41 -29
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/core/result.py +14 -4
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/resilience/adaptive/bulkhead.py +2 -0
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/resilience/adaptive/orchestrator.py +18 -4
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/resilience/circuit_breaker.py +116 -61
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/resilience/retry.py +38 -21
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/resilience/watchdogs/health_pinger.py +22 -18
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/resilience/watchdogs/resource_watcher.py +16 -18
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/security/guards.py +2 -2
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/security/models.py +8 -10
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/security/password.py +13 -16
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/security/validators.py +50 -26
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/utils/filesystem.py +12 -4
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/utils/logging.py +34 -25
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/utils/rate_limit.py +35 -34
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/utils/serialization.py +7 -9
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/utils/subprocess.py +50 -21
- {taipanstack-0.4.6 → taipanstack-0.4.8}/LICENSE +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/bridges/__init__.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/bridges/_imports.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/config/__init__.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/config/generators.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/config/models.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/config/version_config.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/core/__init__.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/core/optimizations.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/resilience/__init__.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/resilience/adaptive/__init__.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/resilience/adaptive/adaptive_breaker.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/resilience/adaptive/adaptive_retry.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/resilience/resilience.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/resilience/watchdogs/__init__.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/resilience/watchdogs/_base.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/resilience/watchdogs/config_watcher.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/security/__init__.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/security/decorators.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/security/jwt.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/security/sanitizers.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/security/types.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/utils/__init__.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/utils/cache.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/utils/circuit_breaker.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/utils/concurrency.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/utils/context.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/utils/resilience.py +0 -0
- {taipanstack-0.4.6 → taipanstack-0.4.8}/src/taipanstack/utils/retry.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.8
|
|
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
|
-
- **
|
|
92
|
-
- **
|
|
93
|
-
- **
|
|
94
|
-
- **
|
|
95
|
-
- **Total Stack Coverage**: Reached **1,
|
|
90
|
+
### ✨ What's New in v0.4.8
|
|
91
|
+
- **Hardening Resilience**: Hardened `RateLimiter` and `CircuitBreaker` against state corruption and type mutations via chaos testing (PR #689, #684).
|
|
92
|
+
- **Complexity Reduction**: Major reduction of cyclomatic complexity across core modules, subprocess utilities, and web bridges (PR #706, #692).
|
|
93
|
+
- **Security Hardening**: Restored missing type guard for password verification and enhanced durability of atomic writes (Commit f83b6745, PR #688).
|
|
94
|
+
- **Performance**: Implemented concurrent execution for async health checks in `HealthPinger` (PR #694).
|
|
95
|
+
- **Total Stack Coverage**: Reached **1,315 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** (1315 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 (1315 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/ # ✅ 1315 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
|
-
- **
|
|
35
|
-
- **
|
|
36
|
-
- **
|
|
37
|
-
- **
|
|
38
|
-
- **Total Stack Coverage**: Reached **1,
|
|
33
|
+
### ✨ What's New in v0.4.8
|
|
34
|
+
- **Hardening Resilience**: Hardened `RateLimiter` and `CircuitBreaker` against state corruption and type mutations via chaos testing (PR #689, #684).
|
|
35
|
+
- **Complexity Reduction**: Major reduction of cyclomatic complexity across core modules, subprocess utilities, and web bridges (PR #706, #692).
|
|
36
|
+
- **Security Hardening**: Restored missing type guard for password verification and enhanced durability of atomic writes (Commit f83b6745, PR #688).
|
|
37
|
+
- **Performance**: Implemented concurrent execution for async health checks in `HealthPinger` (PR #694).
|
|
38
|
+
- **Total Stack Coverage**: Reached **1,315 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** (1315 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 (1315 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/ # ✅ 1315 tests, 100% coverage
|
|
174
174
|
├── .semgrep/ # 🔍 Custom SAST rules
|
|
175
175
|
├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
|
|
176
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.8"
|
|
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"}
|
|
@@ -107,7 +107,7 @@ dev = [
|
|
|
107
107
|
"pygments (>=2.19.2)",
|
|
108
108
|
"hypothesis (>=6.151.12,<7.0.0)",
|
|
109
109
|
"authlib (>=1.6.11,<2.0.0)",
|
|
110
|
-
"cryptography (>=46.0.7,<
|
|
110
|
+
"cryptography (>=46.0.7,<49.0.0)",
|
|
111
111
|
"nltk (>=3.9.4,<4.0.0)",
|
|
112
112
|
"mutmut (>=3.0.0,<4.0.0)",
|
|
113
113
|
"pip (>=26.1,<27.0)",
|
|
@@ -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.8"
|
|
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
|
|
|
@@ -165,6 +165,42 @@ async def _handle_http_exception(
|
|
|
165
165
|
return False
|
|
166
166
|
|
|
167
167
|
|
|
168
|
+
async def _execute_single_attempt(
|
|
169
|
+
request_func: Callable[[], Awaitable[httpx.Response]],
|
|
170
|
+
retry_config: RetryConfig | None,
|
|
171
|
+
circuit_breaker: CircuitBreaker | None,
|
|
172
|
+
retryable_status_codes: frozenset[int],
|
|
173
|
+
attempt: int,
|
|
174
|
+
max_attempts: int,
|
|
175
|
+
) -> Result[httpx.Response, Exception] | Exception | bool:
|
|
176
|
+
"""Execute a single HTTP attempt.
|
|
177
|
+
|
|
178
|
+
Returns Result on success/final failure, Exception if it failed and we
|
|
179
|
+
should record it, or True if we should just retry because of status code.
|
|
180
|
+
"""
|
|
181
|
+
try:
|
|
182
|
+
response = await request_func()
|
|
183
|
+
if _should_retry_status(
|
|
184
|
+
response,
|
|
185
|
+
retry_config,
|
|
186
|
+
retryable_status_codes,
|
|
187
|
+
attempt,
|
|
188
|
+
max_attempts,
|
|
189
|
+
):
|
|
190
|
+
# Config is not None if we reach here
|
|
191
|
+
delay = calculate_delay(attempt, cast(RetryConfig, retry_config))
|
|
192
|
+
await asyncio.sleep(min(delay, 3600.0))
|
|
193
|
+
return True
|
|
194
|
+
return Ok(response)
|
|
195
|
+
except Exception as exc:
|
|
196
|
+
should_retry = await _handle_http_exception(
|
|
197
|
+
exc, attempt, max_attempts, retry_config, circuit_breaker
|
|
198
|
+
)
|
|
199
|
+
if should_retry:
|
|
200
|
+
return exc
|
|
201
|
+
return Err(exc)
|
|
202
|
+
|
|
203
|
+
|
|
168
204
|
async def _execute_with_retries(
|
|
169
205
|
request_func: Callable[[], Awaitable[httpx.Response]],
|
|
170
206
|
retry_config: RetryConfig | None,
|
|
@@ -187,28 +223,18 @@ async def _execute_with_retries(
|
|
|
187
223
|
last_error: Exception | None = None
|
|
188
224
|
|
|
189
225
|
for attempt in range(1, max_attempts + 1):
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
continue
|
|
203
|
-
return Ok(response)
|
|
204
|
-
except Exception as exc:
|
|
205
|
-
last_error = exc
|
|
206
|
-
should_retry = await _handle_http_exception(
|
|
207
|
-
exc, attempt, max_attempts, retry_config, circuit_breaker
|
|
208
|
-
)
|
|
209
|
-
if should_retry:
|
|
210
|
-
continue
|
|
211
|
-
break
|
|
226
|
+
outcome = await _execute_single_attempt(
|
|
227
|
+
request_func,
|
|
228
|
+
retry_config,
|
|
229
|
+
circuit_breaker,
|
|
230
|
+
retryable_status_codes,
|
|
231
|
+
attempt,
|
|
232
|
+
max_attempts,
|
|
233
|
+
)
|
|
234
|
+
if isinstance(outcome, (Ok, Err)):
|
|
235
|
+
return outcome
|
|
236
|
+
if isinstance(outcome, Exception):
|
|
237
|
+
last_error = outcome
|
|
212
238
|
|
|
213
239
|
return Err(last_error or RuntimeError("Request failed"))
|
|
214
240
|
|
|
@@ -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)
|
|
@@ -177,6 +177,56 @@ class TaipanMiddleware:
|
|
|
177
177
|
self._security_headers = security_headers
|
|
178
178
|
self._headers_config = headers_config or SecurityHeadersConfig()
|
|
179
179
|
|
|
180
|
+
def _wrap_send_with_security_headers(self, send: Send) -> Send:
|
|
181
|
+
"""Wrap the send callable to inject security headers if enabled.
|
|
182
|
+
|
|
183
|
+
Args:
|
|
184
|
+
send: The original ASGI send callable.
|
|
185
|
+
|
|
186
|
+
Returns:
|
|
187
|
+
The wrapped ASGI send callable.
|
|
188
|
+
|
|
189
|
+
"""
|
|
190
|
+
if not self._security_headers:
|
|
191
|
+
return send
|
|
192
|
+
|
|
193
|
+
extra_headers = self._headers_config.to_headers()
|
|
194
|
+
|
|
195
|
+
async def send_with_headers(message: MutableMapping[str, object]) -> None:
|
|
196
|
+
if message.get("type") == "http.response.start":
|
|
197
|
+
headers = message.get("headers")
|
|
198
|
+
existing = list(headers) if isinstance(headers, list) else []
|
|
199
|
+
existing.extend(extra_headers)
|
|
200
|
+
message["headers"] = existing
|
|
201
|
+
await send(message)
|
|
202
|
+
|
|
203
|
+
return send_with_headers
|
|
204
|
+
|
|
205
|
+
async def _handle_rate_limit(self, send: Send) -> bool:
|
|
206
|
+
"""Apply rate limiting and send response if exceeded.
|
|
207
|
+
|
|
208
|
+
Args:
|
|
209
|
+
send: ASGI send callable.
|
|
210
|
+
|
|
211
|
+
Returns:
|
|
212
|
+
True if rate limit was exceeded, False otherwise.
|
|
213
|
+
|
|
214
|
+
"""
|
|
215
|
+
if self._rate_limiter is None or self._rate_limiter.consume():
|
|
216
|
+
return False
|
|
217
|
+
|
|
218
|
+
logger.warning("Rate limit exceeded for request")
|
|
219
|
+
security_hdrs = (
|
|
220
|
+
self._headers_config.to_headers() if self._security_headers else None
|
|
221
|
+
)
|
|
222
|
+
await _send_json_response(
|
|
223
|
+
send,
|
|
224
|
+
status=429,
|
|
225
|
+
body={"error": "Rate limit exceeded", "retry_after": 1},
|
|
226
|
+
extra_headers=security_hdrs,
|
|
227
|
+
)
|
|
228
|
+
return True
|
|
229
|
+
|
|
180
230
|
async def __call__(
|
|
181
231
|
self,
|
|
182
232
|
scope: Scope,
|
|
@@ -197,33 +247,11 @@ class TaipanMiddleware:
|
|
|
197
247
|
return
|
|
198
248
|
|
|
199
249
|
# Rate limiting
|
|
200
|
-
if
|
|
201
|
-
logger.warning("Rate limit exceeded for request")
|
|
202
|
-
security_hdrs = (
|
|
203
|
-
self._headers_config.to_headers() if self._security_headers else None
|
|
204
|
-
)
|
|
205
|
-
await _send_json_response(
|
|
206
|
-
send,
|
|
207
|
-
status=429,
|
|
208
|
-
body={"error": "Rate limit exceeded", "retry_after": 1},
|
|
209
|
-
extra_headers=security_hdrs,
|
|
210
|
-
)
|
|
250
|
+
if await self._handle_rate_limit(send):
|
|
211
251
|
return
|
|
212
252
|
|
|
213
253
|
# Wrap send to inject security headers
|
|
214
|
-
|
|
215
|
-
original_send = send
|
|
216
|
-
extra_headers = self._headers_config.to_headers()
|
|
217
|
-
|
|
218
|
-
async def send_with_headers(message: MutableMapping[str, object]) -> None:
|
|
219
|
-
if message.get("type") == "http.response.start":
|
|
220
|
-
headers = message.get("headers")
|
|
221
|
-
existing = list(headers) if isinstance(headers, list) else []
|
|
222
|
-
existing.extend(extra_headers)
|
|
223
|
-
message["headers"] = existing
|
|
224
|
-
await original_send(message)
|
|
225
|
-
|
|
226
|
-
send = send_with_headers
|
|
254
|
+
send = self._wrap_send_with_security_headers(send)
|
|
227
255
|
|
|
228
256
|
# Call the actual application
|
|
229
257
|
try:
|
|
@@ -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
|
|
|
@@ -182,6 +182,17 @@ def safe_from(
|
|
|
182
182
|
return cast(SafeFromDecorator[E], decorator)
|
|
183
183
|
|
|
184
184
|
|
|
185
|
+
def _collect_list(
|
|
186
|
+
results: list[Result[T, E]] | tuple[Result[T, E], ...],
|
|
187
|
+
) -> Result[list[T], E] | None:
|
|
188
|
+
try:
|
|
189
|
+
# We use a runtime # type: ignore to bypass mypy's strict check
|
|
190
|
+
# on the AttributeError strategy for extreme performance on the hot path
|
|
191
|
+
return Ok([r.ok_value for r in results]) # type: ignore[union-attr]
|
|
192
|
+
except AttributeError:
|
|
193
|
+
return None
|
|
194
|
+
|
|
195
|
+
|
|
185
196
|
def collect_results(
|
|
186
197
|
results: Iterable[Result[T, E]],
|
|
187
198
|
) -> Result[list[T], E]:
|
|
@@ -204,10 +215,9 @@ def collect_results(
|
|
|
204
215
|
|
|
205
216
|
"""
|
|
206
217
|
if isinstance(results, (list, tuple)):
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
pass
|
|
218
|
+
optimized_res = _collect_list(results)
|
|
219
|
+
if optimized_res is not None:
|
|
220
|
+
return optimized_res
|
|
211
221
|
|
|
212
222
|
ok_cls = Ok
|
|
213
223
|
err_cls = Err
|
|
@@ -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
|
|