taipanstack 0.4.0__tar.gz → 0.4.2__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 (56) hide show
  1. {taipanstack-0.4.0 → taipanstack-0.4.2}/PKG-INFO +11 -6
  2. {taipanstack-0.4.0 → taipanstack-0.4.2}/README.md +10 -5
  3. {taipanstack-0.4.0 → taipanstack-0.4.2}/pyproject.toml +2 -6
  4. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/__init__.py +1 -1
  5. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/bridges/http_bridge.py +107 -82
  6. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/config/generators.py +0 -104
  7. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/config/models.py +3 -0
  8. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/core/optimizations.py +0 -21
  9. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/core/result.py +30 -14
  10. taipanstack-0.4.2/src/taipanstack/resilience/adaptive/adaptive_breaker.py +209 -0
  11. taipanstack-0.4.2/src/taipanstack/resilience/adaptive/adaptive_timeout.py +177 -0
  12. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/resilience/adaptive/orchestrator.py +67 -54
  13. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/resilience/circuit_breaker.py +37 -1
  14. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/resilience/resilience.py +2 -2
  15. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/security/decorators.py +2 -2
  16. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/security/guards.py +3 -1
  17. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/security/jwt.py +7 -4
  18. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/security/password.py +15 -0
  19. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/security/sanitizers.py +127 -93
  20. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/utils/cache.py +16 -2
  21. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/utils/filesystem.py +32 -35
  22. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/utils/logging.py +4 -2
  23. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/utils/subprocess.py +23 -12
  24. taipanstack-0.4.0/src/taipanstack/resilience/adaptive/adaptive_breaker.py +0 -222
  25. taipanstack-0.4.0/src/taipanstack/utils/metrics.py +0 -289
  26. {taipanstack-0.4.0 → taipanstack-0.4.2}/LICENSE +0 -0
  27. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/bridges/__init__.py +0 -0
  28. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/bridges/_imports.py +0 -0
  29. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/bridges/db_bridge.py +0 -0
  30. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/bridges/web_bridge.py +0 -0
  31. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/config/__init__.py +0 -0
  32. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/config/version_config.py +0 -0
  33. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/core/__init__.py +0 -0
  34. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/core/compat.py +0 -0
  35. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/resilience/__init__.py +0 -0
  36. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/resilience/adaptive/__init__.py +0 -0
  37. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/resilience/adaptive/adaptive_retry.py +0 -0
  38. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/resilience/adaptive/bulkhead.py +0 -0
  39. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/resilience/retry.py +0 -0
  40. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/resilience/watchdogs/__init__.py +0 -0
  41. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/resilience/watchdogs/_base.py +0 -0
  42. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/resilience/watchdogs/config_watcher.py +0 -0
  43. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/resilience/watchdogs/health_pinger.py +0 -0
  44. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/resilience/watchdogs/resource_watcher.py +0 -0
  45. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/security/__init__.py +0 -0
  46. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/security/models.py +0 -0
  47. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/security/types.py +0 -0
  48. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/security/validators.py +0 -0
  49. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/utils/__init__.py +0 -0
  50. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/utils/circuit_breaker.py +0 -0
  51. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/utils/concurrency.py +0 -0
  52. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/utils/context.py +0 -0
  53. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/utils/rate_limit.py +0 -0
  54. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/utils/resilience.py +0 -0
  55. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/utils/retry.py +0 -0
  56. {taipanstack-0.4.0 → taipanstack-0.4.2}/src/taipanstack/utils/serialization.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: taipanstack
3
- Version: 0.4.0
3
+ Version: 0.4.2
4
4
  Summary: TaipanStack - Modular, secure, and scalable Python stack for robust development
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -87,6 +87,11 @@ Description-Content-Type: text/markdown
87
87
 
88
88
  TaipanStack is a battle-tested foundation for production-grade Python projects that combines **security**, **performance**, and **developer experience** into a single, cohesive toolkit.
89
89
 
90
+ ### ✨ What's New in v0.4.0
91
+ - **Taipan Bridges**: Native ASGI middleware integrations (Rate Limiting, Security Headers) out of the box.
92
+ - **Adaptive Resilience**: Self-healing with AI-style failure thresholds and dynamic timeout tracking.
93
+ - **Watchdogs**: Active CPU/Memory monitoring, background Health Checks, and Hot Reload of settings via Pydantic.
94
+
90
95
  <table>
91
96
  <tr>
92
97
  <td width="50%">
@@ -123,7 +128,7 @@ TaipanStack is a battle-tested foundation for production-grade Python projects t
123
128
 
124
129
  ### 🔧 Developer Experience
125
130
  - Pre-configured quality tools
126
- - **100% code coverage** (1164 tests)
131
+ - **100% code coverage** (1158 tests)
127
132
  - Architecture enforcement
128
133
  - Hardened Docker template
129
134
 
@@ -165,7 +170,7 @@ make all
165
170
  ### Verify Installation
166
171
 
167
172
  ```bash
168
- # Run tests with 100% coverage (1164 tests)
173
+ # Run tests with 100% coverage (1158 tests)
169
174
  make test
170
175
 
171
176
  # Check architecture contracts
@@ -220,7 +225,7 @@ TaipanStack/
220
225
  │ ├── config/ # ⚙️ Configuration models & generators
221
226
  │ ├── security/ # 🛡️ Guards, sanitizers, validators
222
227
  │ └── utils/ # 🔧 Logging, metrics, retry, filesystem
223
- ├── tests/ # ✅ 1164 tests, 100% coverage
228
+ ├── tests/ # ✅ 1158 tests, 100% coverage
224
229
  ├── .semgrep/ # 🔍 Custom SAST rules
225
230
  ├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
226
231
  ├── Dockerfile # 🐳 Hardened multi-stage container
@@ -363,7 +368,7 @@ profile = unwrap_or(fetch_user_profile("usr_456"), {"name": "Unknown"})
363
368
 
364
369
  ```python
365
370
  from taipanstack.core.result import Result, Ok, Err
366
- from taipanstack.resilience.adaptive import ResilienceOrchestrator, AdaptiveCircuitBreaker
371
+ from taipanstack.resilience.adaptive import ResilienceOrchestrator, AdaptiveCircuitBreaker, AdaptiveTimeout
367
372
  from taipanstack.resilience.retry import RetryConfig
368
373
 
369
374
  # Compose an intelligent pipeline: Bulkhead -> Breaker -> Retry -> Timeout -> Fallback
@@ -371,8 +376,8 @@ orch = (
371
376
  ResilienceOrchestrator("billing_api")
372
377
  .with_bulkhead(max_concurrent=10, max_queue=50) # Prevent resource exhaustion
373
378
  .with_circuit_breaker(AdaptiveCircuitBreaker("billing", target_error_rate=0.1)) # Auto-tunes thresholds
379
+ .with_timeout(AdaptiveTimeout(min_timeout=1.0, max_timeout=10.0))
374
380
  .with_retry(RetryConfig(max_attempts=3, initial_delay=0.1))
375
- .with_timeout(5.0)
376
381
  .with_fallback({"status": "unavailable"})
377
382
  )
378
383
 
@@ -31,6 +31,11 @@
31
31
 
32
32
  TaipanStack is a battle-tested foundation for production-grade Python projects that combines **security**, **performance**, and **developer experience** into a single, cohesive toolkit.
33
33
 
34
+ ### ✨ What's New in v0.4.0
35
+ - **Taipan Bridges**: Native ASGI middleware integrations (Rate Limiting, Security Headers) out of the box.
36
+ - **Adaptive Resilience**: Self-healing with AI-style failure thresholds and dynamic timeout tracking.
37
+ - **Watchdogs**: Active CPU/Memory monitoring, background Health Checks, and Hot Reload of settings via Pydantic.
38
+
34
39
  <table>
35
40
  <tr>
36
41
  <td width="50%">
@@ -67,7 +72,7 @@ TaipanStack is a battle-tested foundation for production-grade Python projects t
67
72
 
68
73
  ### 🔧 Developer Experience
69
74
  - Pre-configured quality tools
70
- - **100% code coverage** (1164 tests)
75
+ - **100% code coverage** (1158 tests)
71
76
  - Architecture enforcement
72
77
  - Hardened Docker template
73
78
 
@@ -109,7 +114,7 @@ make all
109
114
  ### Verify Installation
110
115
 
111
116
  ```bash
112
- # Run tests with 100% coverage (1164 tests)
117
+ # Run tests with 100% coverage (1158 tests)
113
118
  make test
114
119
 
115
120
  # Check architecture contracts
@@ -164,7 +169,7 @@ TaipanStack/
164
169
  │ ├── config/ # ⚙️ Configuration models & generators
165
170
  │ ├── security/ # 🛡️ Guards, sanitizers, validators
166
171
  │ └── utils/ # 🔧 Logging, metrics, retry, filesystem
167
- ├── tests/ # ✅ 1164 tests, 100% coverage
172
+ ├── tests/ # ✅ 1158 tests, 100% coverage
168
173
  ├── .semgrep/ # 🔍 Custom SAST rules
169
174
  ├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
170
175
  ├── Dockerfile # 🐳 Hardened multi-stage container
@@ -307,7 +312,7 @@ profile = unwrap_or(fetch_user_profile("usr_456"), {"name": "Unknown"})
307
312
 
308
313
  ```python
309
314
  from taipanstack.core.result import Result, Ok, Err
310
- from taipanstack.resilience.adaptive import ResilienceOrchestrator, AdaptiveCircuitBreaker
315
+ from taipanstack.resilience.adaptive import ResilienceOrchestrator, AdaptiveCircuitBreaker, AdaptiveTimeout
311
316
  from taipanstack.resilience.retry import RetryConfig
312
317
 
313
318
  # Compose an intelligent pipeline: Bulkhead -> Breaker -> Retry -> Timeout -> Fallback
@@ -315,8 +320,8 @@ orch = (
315
320
  ResilienceOrchestrator("billing_api")
316
321
  .with_bulkhead(max_concurrent=10, max_queue=50) # Prevent resource exhaustion
317
322
  .with_circuit_breaker(AdaptiveCircuitBreaker("billing", target_error_rate=0.1)) # Auto-tunes thresholds
323
+ .with_timeout(AdaptiveTimeout(min_timeout=1.0, max_timeout=10.0))
318
324
  .with_retry(RetryConfig(max_attempts=3, initial_delay=0.1))
319
- .with_timeout(5.0)
320
325
  .with_fallback({"status": "unavailable"})
321
326
  )
322
327
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "taipanstack"
3
- version = "0.4.0"
3
+ version = "0.4.2"
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"}
@@ -168,9 +168,6 @@ max-complexity = 10
168
168
  "src/taipanstack/security/sanitizers.py" = ["PLR0912"]
169
169
  # Decorators: allow inline imports for lazy loading, unused signal args, D401 imperative mood
170
170
  "src/taipanstack/security/decorators.py" = ["PLC0415", "ARG001", "D401"]
171
- # Circuit breaker and metrics: allow D401 for decorator docstrings
172
- "src/taipanstack/utils/circuit_breaker.py" = ["D401"]
173
- "src/taipanstack/utils/metrics.py" = ["D401"]
174
171
  # Core result: allow D401 for utility function docstrings
175
172
  "src/taipanstack/core/result.py" = ["D401"]
176
173
  # Resilience module: allow D401, too many args, random for jitter
@@ -215,7 +212,7 @@ warn_required_dynamic_aliases = true
215
212
 
216
213
  [tool.pytest.ini_options]
217
214
  testpaths = ["tests"]
218
- addopts = "-v --cov=src --cov-report=html --cov-report=term-missing --strict-markers --timeout=30"
215
+ addopts = "-v --strict-markers --timeout=30"
219
216
  asyncio_mode = "auto"
220
217
  markers = [
221
218
  "slow: marks tests as slow (deselect with '-m \"not slow\"')",
@@ -225,7 +222,6 @@ markers = [
225
222
  ]
226
223
  filterwarnings = [
227
224
 
228
- "ignore::ResourceWarning",
229
225
  "ignore::pytest.PytestUnraisableExceptionWarning",
230
226
  ]
231
227
 
@@ -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.0"
8
+ __version__ = "0.4.2"
9
9
 
10
10
  from taipanstack.config.version_config import (
11
11
  VersionRecommendations,
@@ -10,6 +10,7 @@ from __future__ import annotations
10
10
 
11
11
  import asyncio
12
12
  import logging
13
+ from collections.abc import Awaitable, Callable
13
14
  from typing import Any
14
15
 
15
16
  from taipanstack.core.result import Err, Ok, Result
@@ -56,54 +57,46 @@ def _check_circuit_breaker(
56
57
  return None
57
58
 
58
59
 
59
- async def safe_request(
60
- method: str,
61
- url: str,
62
- *,
63
- ssrf_protection: bool = True,
64
- retry_config: RetryConfig | None = None,
65
- circuit_breaker: CircuitBreaker | None = None,
66
- retryable_status_codes: frozenset[int] = _RETRYABLE_STATUS_CODES,
67
- **kwargs: Any,
60
+ def _check_ssrf(url: str, ssrf_protection: bool) -> Result[None, Exception]:
61
+ """Validate URL against SSRF if protection is enabled.
62
+
63
+ Args:
64
+ url: The URL to validate.
65
+ ssrf_protection: Whether SSRF protection is enabled.
66
+
67
+ Returns:
68
+ ``Ok(None)`` if valid or protection disabled, ``Err(Exception)`` otherwise.
69
+
70
+ """
71
+ if not ssrf_protection:
72
+ return Ok(None)
73
+
74
+ ssrf_result = guard_ssrf(url)
75
+ match ssrf_result:
76
+ case Err(security_err):
77
+ return Err(security_err)
78
+ case Ok(): # pragma: no branch
79
+ return Ok(None)
80
+
81
+
82
+ async def _execute_with_retries(
83
+ request_func: Callable[[], Awaitable[Any]],
84
+ retry_config: RetryConfig | None,
85
+ circuit_breaker: CircuitBreaker | None,
86
+ retryable_status_codes: frozenset[int],
68
87
  ) -> Result[Any, Exception]:
69
- """Perform a one-shot HTTP request with safety features.
88
+ """Execute a request function with optional retries and circuit breaker.
70
89
 
71
90
  Args:
72
- method: HTTP method (GET, POST, etc.).
73
- url: Target URL.
74
- ssrf_protection: Validate URL against SSRF.
91
+ request_func: Async callable that performs the request.
75
92
  retry_config: Optional retry configuration.
76
93
  circuit_breaker: Optional circuit breaker.
77
- retryable_status_codes: Status codes that trigger retries.
78
- **kwargs: Passed to ``httpx.AsyncClient.request``.
94
+ retryable_status_codes: Status codes to retry on.
79
95
 
80
96
  Returns:
81
97
  ``Ok(Response)`` on success, ``Err`` on failure.
82
98
 
83
99
  """
84
- if not _HAS_HTTPX:
85
- return Err(
86
- ImportError(
87
- "httpx is required for HTTP bridge. "
88
- "Install with: pip install taipanstack[bridges-http]"
89
- )
90
- )
91
-
92
- # SSRF check
93
- if ssrf_protection:
94
- ssrf_result = guard_ssrf(url)
95
- match ssrf_result:
96
- case Err(security_err):
97
- return Err(security_err)
98
- case Ok(): # pragma: no branch
99
- pass
100
-
101
- # Circuit breaker gate
102
- if circuit_breaker is not None:
103
- cb_err = _check_circuit_breaker(circuit_breaker)
104
- if cb_err is not None:
105
- return Err(cb_err)
106
-
107
100
  max_attempts = 1
108
101
  if retry_config is not None:
109
102
  max_attempts = retry_config.max_attempts
@@ -112,8 +105,7 @@ async def safe_request(
112
105
 
113
106
  for attempt in range(1, max_attempts + 1):
114
107
  try:
115
- async with httpx.AsyncClient() as client:
116
- response = await client.request(method, url, **kwargs)
108
+ response = await request_func()
117
109
 
118
110
  # Check if we should retry on status code
119
111
  if (
@@ -140,6 +132,64 @@ async def safe_request(
140
132
  return Err(last_error or RuntimeError("Request failed"))
141
133
 
142
134
 
135
+ async def safe_request(
136
+ method: str,
137
+ url: str,
138
+ *,
139
+ ssrf_protection: bool = True,
140
+ retry_config: RetryConfig | None = None,
141
+ circuit_breaker: CircuitBreaker | None = None,
142
+ retryable_status_codes: frozenset[int] = _RETRYABLE_STATUS_CODES,
143
+ timeout: float | None = 10.0,
144
+ **kwargs: Any,
145
+ ) -> Result[Any, Exception]:
146
+ """Perform a one-shot HTTP request with safety features.
147
+
148
+ Args:
149
+ method: HTTP method (GET, POST, etc.).
150
+ url: Target URL.
151
+ ssrf_protection: Validate URL against SSRF.
152
+ retry_config: Optional retry configuration.
153
+ circuit_breaker: Optional circuit breaker.
154
+ retryable_status_codes: Status codes that trigger retries.
155
+ timeout: Explicit timeout in seconds (default: 10.0).
156
+ **kwargs: Passed to ``httpx.AsyncClient.request``.
157
+
158
+ Returns:
159
+ ``Ok(Response)`` on success, ``Err`` on failure.
160
+
161
+ """
162
+ if not _HAS_HTTPX:
163
+ return Err(
164
+ ImportError(
165
+ "httpx is required for HTTP bridge. "
166
+ "Install with: pip install taipanstack[bridges-http]"
167
+ )
168
+ )
169
+
170
+ # SSRF check
171
+ ssrf_check = _check_ssrf(url, ssrf_protection)
172
+ if isinstance(ssrf_check, Err):
173
+ return ssrf_check
174
+
175
+ # Circuit breaker gate
176
+ if circuit_breaker is not None:
177
+ cb_err = _check_circuit_breaker(circuit_breaker)
178
+ if cb_err is not None:
179
+ return Err(cb_err)
180
+
181
+ async def _do_request() -> Any:
182
+ async with httpx.AsyncClient(timeout=timeout) as client:
183
+ return await client.request(method, url, **kwargs)
184
+
185
+ return await _execute_with_retries(
186
+ _do_request,
187
+ retry_config,
188
+ circuit_breaker,
189
+ retryable_status_codes,
190
+ )
191
+
192
+
143
193
  class SafeHttpClient:
144
194
  """Async context manager wrapping httpx with TaipanStack safety.
145
195
 
@@ -176,6 +226,7 @@ class SafeHttpClient:
176
226
  circuit_breaker: Circuit breaker instance.
177
227
  retryable_status_codes: Status codes to retry.
178
228
  **client_kwargs: Keyword args for httpx.AsyncClient.
229
+ Default timeout is 10.0 seconds if not provided.
179
230
 
180
231
  """
181
232
  self._ssrf_protection = ssrf_protection
@@ -183,6 +234,7 @@ class SafeHttpClient:
183
234
  self._circuit_breaker = circuit_breaker
184
235
  self._retryable_status_codes = retryable_status_codes
185
236
  self._client_kwargs = client_kwargs
237
+ self._client_kwargs.setdefault("timeout", 10.0)
186
238
  self._client: Any = None
187
239
 
188
240
  async def __aenter__(self) -> SafeHttpClient:
@@ -198,9 +250,9 @@ class SafeHttpClient:
198
250
 
199
251
  async def __aexit__(
200
252
  self,
201
- exc_type: type[BaseException] | None,
202
- exc_val: BaseException | None,
203
- exc_tb: Any,
253
+ _exc_type: type[BaseException] | None,
254
+ _exc_val: BaseException | None,
255
+ _exc_tb: Any,
204
256
  ) -> None:
205
257
  """Exit the async context manager."""
206
258
  if self._client is not None:
@@ -228,13 +280,9 @@ class SafeHttpClient:
228
280
  return Err(RuntimeError("Client not initialised. Use 'async with'."))
229
281
 
230
282
  # SSRF check
231
- if self._ssrf_protection:
232
- ssrf_result = guard_ssrf(url)
233
- match ssrf_result:
234
- case Err(security_err):
235
- return Err(security_err)
236
- case Ok(): # pragma: no branch
237
- pass
283
+ ssrf_check = _check_ssrf(url, self._ssrf_protection)
284
+ if isinstance(ssrf_check, Err):
285
+ return ssrf_check
238
286
 
239
287
  # Circuit breaker gate
240
288
  if self._circuit_breaker is not None:
@@ -242,38 +290,15 @@ class SafeHttpClient:
242
290
  if cb_err is not None:
243
291
  return Err(cb_err)
244
292
 
245
- max_attempts = 1
246
- if self._retry_config is not None:
247
- max_attempts = self._retry_config.max_attempts
248
-
249
- last_error: Exception | None = None
250
-
251
- for attempt in range(1, max_attempts + 1):
252
- try:
253
- response = await self._client.request(method, url, **kwargs)
254
-
255
- if (
256
- self._retry_config is not None
257
- and response.status_code in self._retryable_status_codes
258
- and attempt < max_attempts
259
- ):
260
- delay = calculate_delay(attempt, self._retry_config)
261
- await asyncio.sleep(delay)
262
- continue
263
-
264
- return Ok(response)
265
-
266
- except Exception as exc:
267
- last_error = exc
268
- if self._circuit_breaker is not None:
269
- self._circuit_breaker._record_failure(exc)
270
- if self._retry_config is not None and attempt < max_attempts:
271
- delay = calculate_delay(attempt, self._retry_config)
272
- await asyncio.sleep(delay)
273
- continue
274
- break
275
-
276
- return Err(last_error or RuntimeError("Request failed"))
293
+ async def _do_request() -> Any:
294
+ return await self._client.request(method, url, **kwargs)
295
+
296
+ return await _execute_with_retries(
297
+ _do_request,
298
+ self._retry_config,
299
+ self._circuit_breaker,
300
+ self._retryable_status_codes,
301
+ )
277
302
 
278
303
  async def get(self, url: str, **kw: Any) -> Result[Any, Exception]:
279
304
  """Send a GET request."""
@@ -5,8 +5,6 @@ This module generates configuration files (pyproject.toml, pre-commit, etc.)
5
5
  with proper validation and templating.
6
6
  """
7
7
 
8
- from pathlib import Path
9
-
10
8
  from taipanstack.config.models import StackConfig
11
9
 
12
10
 
@@ -303,52 +301,6 @@ repos:
303
301
  {"".join(security_hooks)}"""
304
302
 
305
303
 
306
- def generate_dependabot_config() -> str:
307
- """Generate .github/dependabot.yml content.
308
-
309
- Returns:
310
- Dependabot configuration YAML string.
311
-
312
- """
313
- return """# Stack v2.0 Dependabot Configuration
314
- version: 2
315
- updates:
316
- - package-ecosystem: "pip"
317
- directory: "/"
318
- schedule:
319
- interval: "daily"
320
- open-pull-requests-limit: 10
321
- groups:
322
- dev-dependencies:
323
- patterns:
324
- - "ruff"
325
- - "mypy"
326
- - "bandit"
327
- - "safety"
328
- - "pytest*"
329
- - "pre-commit"
330
- - "semgrep"
331
- - "py-spy"
332
- security-tools:
333
- patterns:
334
- - "bandit"
335
- - "safety"
336
- - "semgrep"
337
- - "pip-audit"
338
- reviewers:
339
- - "gabrielima7"
340
-
341
- - package-ecosystem: "github-actions"
342
- directory: "/"
343
- schedule:
344
- interval: "weekly"
345
- groups:
346
- actions:
347
- patterns:
348
- - "*"
349
- """
350
-
351
-
352
304
  def generate_security_policy() -> str:
353
305
  """Generate SECURITY.md content.
354
306
 
@@ -394,59 +346,3 @@ This project includes multiple layers of security:
394
346
  - **Initial Assessment**: Within 1 week
395
347
  - **Fix Release**: Depends on severity (critical: ASAP, others: next release)
396
348
  """
397
-
398
-
399
- def generate_editorconfig() -> str:
400
- """Generate .editorconfig content.
401
-
402
- Returns:
403
- EditorConfig content string.
404
-
405
- """
406
- return """# Stack v2.0 EditorConfig
407
- root = true
408
-
409
- [*]
410
- end_of_line = lf
411
- insert_final_newline = true
412
- trim_trailing_whitespace = true
413
- charset = utf-8
414
- indent_style = space
415
- indent_size = 4
416
-
417
- [*.py]
418
- max_line_length = 88
419
-
420
- [*.{yml,yaml,toml,json}]
421
- indent_size = 2
422
-
423
- [Makefile]
424
- indent_style = tab
425
- """
426
-
427
-
428
- def write_config_file(
429
- path: Path,
430
- content: str,
431
- config: StackConfig,
432
- ) -> bool:
433
- """Write configuration file with backup support.
434
-
435
- Args:
436
- path: Path to write the file.
437
- content: Content to write.
438
- config: Stack configuration.
439
-
440
- Returns:
441
- True if file was written, False if in dry-run mode.
442
-
443
- """
444
- if config.dry_run:
445
- return False
446
-
447
- if path.exists() and not config.force:
448
- backup_path = path.with_suffix(f"{path.suffix}.bak")
449
- path.rename(backup_path)
450
-
451
- path.write_text(content, encoding="utf-8")
452
- return True
@@ -209,6 +209,7 @@ class StackConfig(BaseModel):
209
209
  ValueError: If project name contains invalid characters.
210
210
 
211
211
  """
212
+ _ = cls
212
213
  pattern = r"^[a-zA-Z][a-zA-Z0-9_-]*\Z"
213
214
  if not re.match(pattern, value):
214
215
  msg = (
@@ -234,6 +235,7 @@ class StackConfig(BaseModel):
234
235
  ValueError: If version format is invalid.
235
236
 
236
237
  """
238
+ _ = cls
237
239
  pattern = r"^\d+\.\d+\Z"
238
240
  if not re.match(pattern, value):
239
241
  msg = (
@@ -269,6 +271,7 @@ class StackConfig(BaseModel):
269
271
  ValueError: If path is unsafe or contains traversal.
270
272
 
271
273
  """
274
+ _ = cls
272
275
  resolved = value.resolve()
273
276
 
274
277
  # Check for path traversal attempts
@@ -38,7 +38,6 @@ logger = logging.getLogger(__name__)
38
38
 
39
39
  # Optimization Levels
40
40
  OPT_LEVEL_NONE = 0
41
- OPT_LEVEL_SAFE = 1
42
41
  OPT_LEVEL_AGGRESSIVE = 2
43
42
 
44
43
 
@@ -382,23 +381,3 @@ def get_recommended_thread_pool_size(*, force_refresh: bool = False) -> int:
382
381
 
383
382
  size = int(cpu_count * profile.thread_pool_multiplier)
384
383
  return min(size, profile.max_thread_pool_size)
385
-
386
-
387
- def should_use_slots() -> bool:
388
- """Check if __slots__ should be used for new classes.
389
-
390
- Returns:
391
- True if slots are recommended for current version.
392
-
393
- """
394
- return get_optimization_profile().prefer_slots
395
-
396
-
397
- def should_use_frozen_dataclass() -> bool:
398
- """Check if frozen=True should be used for dataclasses.
399
-
400
- Returns:
401
- True if frozen dataclasses are recommended.
402
-
403
- """
404
- return get_optimization_profile().use_frozen_dataclasses
@@ -194,13 +194,23 @@ def collect_results(
194
194
  Err("fail")
195
195
 
196
196
  """
197
+ if type(results) in (list, tuple):
198
+ try:
199
+ return Ok([r.ok_value for r in results]) # type: ignore[union-attr]
200
+ except AttributeError:
201
+ pass
202
+
197
203
  values: list[T] = []
198
204
  append = values.append
199
205
  for result in results:
200
- try:
201
- append(result.ok_value) # type: ignore[union-attr]
202
- except AttributeError:
203
- return result # type: ignore[return-value]
206
+ match result:
207
+ case Ok(val):
208
+ append(val)
209
+ case Err(e):
210
+ _ = e
211
+ return result
212
+ case _: # pragma: no cover
213
+ return result
204
214
  return Ok(values)
205
215
 
206
216
 
@@ -249,11 +259,14 @@ async def map_async(
249
259
  Err('fail')
250
260
 
251
261
  """
252
- try:
253
- val = result.ok_value # type: ignore[union-attr]
254
- except AttributeError:
255
- return result # type: ignore[return-value]
256
- return Ok(await func(val))
262
+ match result:
263
+ case Ok(val):
264
+ return Ok(await func(val))
265
+ case Err(e):
266
+ _ = e
267
+ return result
268
+ case _: # pragma: no cover
269
+ return result
257
270
 
258
271
 
259
272
  @overload
@@ -306,8 +319,11 @@ async def and_then_async(
306
319
  Err(ValueError('No DB'))
307
320
 
308
321
  """
309
- try:
310
- val = result.ok_value # type: ignore[union-attr]
311
- except AttributeError:
312
- return result # type: ignore[return-value]
313
- return await func(val)
322
+ match result:
323
+ case Ok(val):
324
+ return await func(val)
325
+ case Err(e):
326
+ _ = e
327
+ return result
328
+ case _: # pragma: no cover
329
+ return result