taipanstack 0.4.7__tar.gz → 0.4.9__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.
Files changed (53) hide show
  1. {taipanstack-0.4.7 → taipanstack-0.4.9}/PKG-INFO +10 -15
  2. {taipanstack-0.4.7 → taipanstack-0.4.9}/README.md +9 -14
  3. {taipanstack-0.4.7 → taipanstack-0.4.9}/pyproject.toml +4 -6
  4. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/__init__.py +1 -1
  5. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/bridges/http_bridge.py +50 -24
  6. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/bridges/web_bridge.py +54 -26
  7. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/core/optimizations.py +3 -3
  8. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/core/result.py +14 -4
  9. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/resilience/circuit_breaker.py +102 -63
  10. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/resilience/retry.py +79 -45
  11. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/resilience/watchdogs/_base.py +6 -2
  12. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/resilience/watchdogs/health_pinger.py +32 -21
  13. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/resilience/watchdogs/resource_watcher.py +16 -18
  14. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/security/decorators.py +6 -6
  15. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/security/guards.py +1 -1
  16. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/security/models.py +5 -7
  17. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/security/password.py +12 -16
  18. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/security/sanitizers.py +24 -21
  19. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/security/types.py +0 -42
  20. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/security/validators.py +32 -20
  21. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/utils/filesystem.py +4 -0
  22. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/utils/logging.py +85 -27
  23. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/utils/rate_limit.py +49 -39
  24. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/utils/serialization.py +7 -9
  25. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/utils/subprocess.py +50 -21
  26. {taipanstack-0.4.7 → taipanstack-0.4.9}/LICENSE +0 -0
  27. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/bridges/__init__.py +0 -0
  28. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/bridges/_imports.py +0 -0
  29. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/bridges/db_bridge.py +0 -0
  30. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/config/__init__.py +0 -0
  31. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/config/generators.py +0 -0
  32. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/config/models.py +0 -0
  33. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/config/version_config.py +0 -0
  34. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/core/__init__.py +0 -0
  35. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/core/compat.py +0 -0
  36. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/resilience/__init__.py +0 -0
  37. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/resilience/adaptive/__init__.py +0 -0
  38. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/resilience/adaptive/adaptive_breaker.py +0 -0
  39. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/resilience/adaptive/adaptive_retry.py +0 -0
  40. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/resilience/adaptive/bulkhead.py +0 -0
  41. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/resilience/adaptive/orchestrator.py +0 -0
  42. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/resilience/resilience.py +0 -0
  43. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/resilience/watchdogs/__init__.py +0 -0
  44. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/resilience/watchdogs/config_watcher.py +0 -0
  45. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/security/__init__.py +0 -0
  46. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/security/jwt.py +0 -0
  47. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/utils/__init__.py +0 -0
  48. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/utils/cache.py +0 -0
  49. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/utils/circuit_breaker.py +0 -0
  50. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/utils/concurrency.py +0 -0
  51. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/utils/context.py +0 -0
  52. {taipanstack-0.4.7 → taipanstack-0.4.9}/src/taipanstack/utils/resilience.py +0 -0
  53. {taipanstack-0.4.7 → taipanstack-0.4.9}/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.7
3
+ Version: 0.4.9
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.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.
90
+ ### ✨ What's New in v0.4.9
91
+ - **100% REAL Coverage**: Achieved true **100% genuine branch coverage** across the entire core without artificial gaps (PR #738, #724).
92
+ - **Security Hardening**: Remedied error handling information leakage and fixed nested dictionary redaction in logging (PR #739, #730).
93
+ - **Resilience**: Eliminated circuit breaker lock deadlock vector and hardened retry type mutation handling (PR #726, #719).
94
+ - **Chaos Testing**: Introduced daily micro-chaos tests for resilience components to ensure state integrity (PR #714, #711, #710).
95
+ - **Total Stack Quality**: Expanded to **1,331 passing tests** with 100% verified genuine coverage across all modules.
96
96
 
97
97
  <table>
98
98
  <tr>
@@ -112,7 +112,6 @@ Taipan Stack is a battle-tested foundation for production-grade Python projects
112
112
  - `uvloop` async event loop
113
113
  - `orjson` fast JSON serialization
114
114
  - `Pydantic v2` validation
115
- - Performance benchmarks with regression detection
116
115
 
117
116
  </td>
118
117
  </tr>
@@ -130,7 +129,7 @@ Taipan Stack is a battle-tested foundation for production-grade Python projects
130
129
 
131
130
  ### 🔧 Developer Experience
132
131
  - Pre-configured quality tools
133
- - **100% code coverage** (1299 tests)
132
+ - **100% code coverage** (1,331 tests)
134
133
  - Architecture enforcement
135
134
  - Hardened Docker template
136
135
 
@@ -172,7 +171,7 @@ make all
172
171
  ### Verify Installation
173
172
 
174
173
  ```bash
175
- # Run tests with 100% coverage (1299 tests)
174
+ # Run tests with 100% coverage (1,331 tests)
176
175
  make test
177
176
 
178
177
  # Check architecture contracts
@@ -184,8 +183,6 @@ make security
184
183
  # Run property-based fuzzing
185
184
  make property-test
186
185
 
187
- # Run performance benchmarks
188
- make benchmark
189
186
  ```
190
187
 
191
188
  ---
@@ -227,7 +224,7 @@ TaipanStack/
227
224
  │ ├── config/ # ⚙️ Configuration models & generators
228
225
  │ ├── security/ # 🛡️ Guards, sanitizers, validators
229
226
  │ └── utils/ # 🔧 Logging, metrics, retry, filesystem
230
- ├── tests/ # ✅ 1299 tests, 100% coverage
227
+ ├── tests/ # ✅ 1,331 tests, 100% coverage
231
228
  ├── .semgrep/ # 🔍 Custom SAST rules
232
229
  ├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
233
230
  ├── Dockerfile # 🐳 Hardened multi-stage container
@@ -250,7 +247,6 @@ Taipan Stack integrates security and quality at every level:
250
247
  | **Lint** | Ruff | Lightning-fast linting & formatting |
251
248
  | **Arch** | Import Linter | Dependency rule enforcement |
252
249
  | **Test** | Pytest, Hypothesis, mutmut | Property-based & mutation testing |
253
- | **Perf** | pytest-benchmark | Performance regression detection |
254
250
  | **Containers** | Docker (Alpine, rootless) | Hardened-by-default images |
255
251
 
256
252
  ### CI Pipeline
@@ -451,7 +447,6 @@ Security features: multi-stage build, Alpine base (<50MB), non-root `appuser` (U
451
447
  - Bandit
452
448
  - Pytest + Hypothesis
453
449
  - mutmut
454
- - pytest-benchmark
455
450
 
456
451
  </td>
457
452
  <td>
@@ -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.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.
33
+ ### ✨ What's New in v0.4.9
34
+ - **100% REAL Coverage**: Achieved true **100% genuine branch coverage** across the entire core without artificial gaps (PR #738, #724).
35
+ - **Security Hardening**: Remedied error handling information leakage and fixed nested dictionary redaction in logging (PR #739, #730).
36
+ - **Resilience**: Eliminated circuit breaker lock deadlock vector and hardened retry type mutation handling (PR #726, #719).
37
+ - **Chaos Testing**: Introduced daily micro-chaos tests for resilience components to ensure state integrity (PR #714, #711, #710).
38
+ - **Total Stack Quality**: Expanded to **1,331 passing tests** with 100% verified genuine coverage across all modules.
39
39
 
40
40
  <table>
41
41
  <tr>
@@ -55,7 +55,6 @@ Taipan Stack is a battle-tested foundation for production-grade Python projects
55
55
  - `uvloop` async event loop
56
56
  - `orjson` fast JSON serialization
57
57
  - `Pydantic v2` validation
58
- - Performance benchmarks with regression detection
59
58
 
60
59
  </td>
61
60
  </tr>
@@ -73,7 +72,7 @@ Taipan Stack is a battle-tested foundation for production-grade Python projects
73
72
 
74
73
  ### 🔧 Developer Experience
75
74
  - Pre-configured quality tools
76
- - **100% code coverage** (1299 tests)
75
+ - **100% code coverage** (1,331 tests)
77
76
  - Architecture enforcement
78
77
  - Hardened Docker template
79
78
 
@@ -115,7 +114,7 @@ make all
115
114
  ### Verify Installation
116
115
 
117
116
  ```bash
118
- # Run tests with 100% coverage (1299 tests)
117
+ # Run tests with 100% coverage (1,331 tests)
119
118
  make test
120
119
 
121
120
  # Check architecture contracts
@@ -127,8 +126,6 @@ make security
127
126
  # Run property-based fuzzing
128
127
  make property-test
129
128
 
130
- # Run performance benchmarks
131
- make benchmark
132
129
  ```
133
130
 
134
131
  ---
@@ -170,7 +167,7 @@ TaipanStack/
170
167
  │ ├── config/ # ⚙️ Configuration models & generators
171
168
  │ ├── security/ # 🛡️ Guards, sanitizers, validators
172
169
  │ └── utils/ # 🔧 Logging, metrics, retry, filesystem
173
- ├── tests/ # ✅ 1299 tests, 100% coverage
170
+ ├── tests/ # ✅ 1,331 tests, 100% coverage
174
171
  ├── .semgrep/ # 🔍 Custom SAST rules
175
172
  ├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
176
173
  ├── Dockerfile # 🐳 Hardened multi-stage container
@@ -193,7 +190,6 @@ Taipan Stack integrates security and quality at every level:
193
190
  | **Lint** | Ruff | Lightning-fast linting & formatting |
194
191
  | **Arch** | Import Linter | Dependency rule enforcement |
195
192
  | **Test** | Pytest, Hypothesis, mutmut | Property-based & mutation testing |
196
- | **Perf** | pytest-benchmark | Performance regression detection |
197
193
  | **Containers** | Docker (Alpine, rootless) | Hardened-by-default images |
198
194
 
199
195
  ### CI Pipeline
@@ -394,7 +390,6 @@ Security features: multi-stage build, Alpine base (<50MB), non-root `appuser` (U
394
390
  - Bandit
395
391
  - Pytest + Hypothesis
396
392
  - mutmut
397
- - pytest-benchmark
398
393
 
399
394
  </td>
400
395
  <td>
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "taipanstack"
3
- version = "0.4.7"
3
+ version = "0.4.9"
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"}
@@ -94,7 +94,6 @@ dev = [
94
94
  "structlog (>=25.5.0,<26.0.0)",
95
95
  "import-linter (>=2.1)",
96
96
  "gitingest (>=0.1.0)",
97
- "pytest-benchmark (>=5.0.0)",
98
97
  "pytest-asyncio (>=0.23.0)",
99
98
  "radon (>=6.0.1,<7.0.0)",
100
99
  "pip-audit (>=2.10.0,<3.0.0)",
@@ -107,7 +106,7 @@ dev = [
107
106
  "pygments (>=2.19.2)",
108
107
  "hypothesis (>=6.151.12,<7.0.0)",
109
108
  "authlib (>=1.6.11,<2.0.0)",
110
- "cryptography (>=46.0.7,<48.0.0)",
109
+ "cryptography (>=46.0.7,<49.0.0)",
111
110
  "nltk (>=3.9.4,<4.0.0)",
112
111
  "mutmut (>=3.0.0,<4.0.0)",
113
112
  "pip (>=26.1,<27.0)",
@@ -223,7 +222,6 @@ markers = [
223
222
  "slow: marks tests as slow (deselect with '-m \"not slow\"')",
224
223
  "security: marks tests as security-related",
225
224
  "integration: marks tests as integration tests",
226
- "benchmark: marks tests as performance benchmarks",
227
225
  ]
228
226
  filterwarnings = [
229
227
 
@@ -237,7 +235,7 @@ omit = ["*/tests/*", "*/__pycache__/*", "*/conftest.py"]
237
235
 
238
236
  [tool.coverage.report]
239
237
  exclude_lines = [
240
- "pragma: no cover",
238
+
241
239
  "def __repr__",
242
240
  "raise NotImplementedError",
243
241
  "if TYPE_CHECKING:",
@@ -247,7 +245,7 @@ exclude_lines = [
247
245
  "def __call__\\(.*\\) -> .*:\\s*(?:\"\"\".*?\"\"\"\\s*)?\\.\\.\\.",
248
246
  ]
249
247
  partial_branches = [
250
- "pragma: no branch",
248
+
251
249
  "case Err\\(",
252
250
  "case Ok\\(",
253
251
  ]
@@ -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.7"
8
+ __version__ = "0.4.9"
9
9
 
10
10
  from taipanstack.config.version_config import (
11
11
  VersionRecommendations,
@@ -129,7 +129,7 @@ def _check_ssrf(url: str, ssrf_protection: bool) -> Result[None, Exception]:
129
129
  match ssrf_result:
130
130
  case Err(security_err):
131
131
  return Err(security_err)
132
- case Ok(): # pragma: no branch
132
+ case Ok():
133
133
  return Ok(None)
134
134
 
135
135
 
@@ -156,7 +156,7 @@ async def _handle_http_exception(
156
156
  circuit_breaker: CircuitBreaker | None,
157
157
  ) -> bool:
158
158
  """Handle exception and return True if we should retry, False otherwise."""
159
- if circuit_breaker is not None: # pragma: no branch
159
+ if circuit_breaker is not None:
160
160
  circuit_breaker._record_failure(exc)
161
161
  if retry_config is not None and attempt < max_attempts:
162
162
  delay = calculate_delay(attempt, retry_config)
@@ -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
- try:
191
- response = await request_func()
192
- if _should_retry_status(
193
- response,
194
- retry_config,
195
- retryable_status_codes,
196
- attempt,
197
- max_attempts,
198
- ):
199
- # Config is not None if we reach here
200
- delay = calculate_delay(attempt, cast(RetryConfig, retry_config))
201
- await asyncio.sleep(min(delay, 3600.0))
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
 
@@ -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,39 +247,17 @@ class TaipanMiddleware:
197
247
  return
198
248
 
199
249
  # Rate limiting
200
- if self._rate_limiter is not None and not self._rate_limiter.consume():
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
- if self._security_headers:
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:
230
258
  await self._app(scope, receive, send)
231
- except Exception:
232
- logger.exception("Unhandled exception in ASGI app")
259
+ except Exception as exc:
260
+ logger.exception("Unhandled exception in ASGI app", exc_info=exc)
233
261
  await _send_json_response(
234
262
  send,
235
263
  status=500,
@@ -292,9 +292,9 @@ def _apply_experimental(
292
292
  """Check and log experimental features."""
293
293
  if profile.enable_experimental:
294
294
  features = get_features()
295
- if features.has_jit: # pragma: no branch
295
+ if features.has_jit:
296
296
  applied.append("jit: available")
297
- if features.has_free_threading: # pragma: no branch
297
+ if features.has_free_threading:
298
298
  applied.append("free_threading: available")
299
299
  logger.warning(
300
300
  "EXPERIMENTAL FEATURES ENABLED: Stability and security may be affected."
@@ -354,7 +354,7 @@ def apply_optimizations(
354
354
  success = len(errors) == 0
355
355
  if applied:
356
356
  logger.debug("Applied optimizations: %s", ", ".join(applied))
357
- if skipped: # pragma: no branch
357
+ if skipped:
358
358
  logger.debug("Skipped optimizations: %s", ", ".join(skipped))
359
359
  if errors:
360
360
  logger.warning("Optimization errors: %s", ", ".join(errors))
@@ -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
- try:
208
- return Ok([r.ok_value for r in results])
209
- except AttributeError:
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