taipanstack 0.3.11__tar.gz → 0.4.0__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 (54) hide show
  1. {taipanstack-0.3.11 → taipanstack-0.4.0}/PKG-INFO +45 -4
  2. {taipanstack-0.3.11 → taipanstack-0.4.0}/README.md +25 -3
  3. {taipanstack-0.3.11 → taipanstack-0.4.0}/pyproject.toml +43 -2
  4. {taipanstack-0.3.11 → taipanstack-0.4.0}/src/taipanstack/__init__.py +1 -1
  5. taipanstack-0.4.0/src/taipanstack/bridges/__init__.py +31 -0
  6. taipanstack-0.4.0/src/taipanstack/bridges/_imports.py +68 -0
  7. taipanstack-0.4.0/src/taipanstack/bridges/db_bridge.py +253 -0
  8. taipanstack-0.4.0/src/taipanstack/bridges/http_bridge.py +296 -0
  9. taipanstack-0.4.0/src/taipanstack/bridges/web_bridge.py +234 -0
  10. {taipanstack-0.3.11 → taipanstack-0.4.0}/src/taipanstack/core/result.py +24 -29
  11. taipanstack-0.4.0/src/taipanstack/resilience/__init__.py +71 -0
  12. taipanstack-0.4.0/src/taipanstack/resilience/adaptive/__init__.py +32 -0
  13. taipanstack-0.4.0/src/taipanstack/resilience/adaptive/adaptive_breaker.py +222 -0
  14. taipanstack-0.4.0/src/taipanstack/resilience/adaptive/adaptive_retry.py +186 -0
  15. taipanstack-0.4.0/src/taipanstack/resilience/adaptive/bulkhead.py +160 -0
  16. taipanstack-0.4.0/src/taipanstack/resilience/adaptive/orchestrator.py +358 -0
  17. {taipanstack-0.3.11/src/taipanstack/utils → taipanstack-0.4.0/src/taipanstack/resilience}/circuit_breaker.py +2 -2
  18. {taipanstack-0.3.11/src/taipanstack/utils → taipanstack-0.4.0/src/taipanstack/resilience}/retry.py +2 -4
  19. taipanstack-0.4.0/src/taipanstack/resilience/watchdogs/__init__.py +36 -0
  20. taipanstack-0.4.0/src/taipanstack/resilience/watchdogs/_base.py +110 -0
  21. taipanstack-0.4.0/src/taipanstack/resilience/watchdogs/config_watcher.py +249 -0
  22. taipanstack-0.4.0/src/taipanstack/resilience/watchdogs/health_pinger.py +184 -0
  23. taipanstack-0.4.0/src/taipanstack/resilience/watchdogs/resource_watcher.py +155 -0
  24. {taipanstack-0.3.11 → taipanstack-0.4.0}/src/taipanstack/security/guards.py +13 -1
  25. {taipanstack-0.3.11 → taipanstack-0.4.0}/src/taipanstack/security/password.py +1 -1
  26. {taipanstack-0.3.11 → taipanstack-0.4.0}/src/taipanstack/security/sanitizers.py +31 -20
  27. {taipanstack-0.3.11 → taipanstack-0.4.0}/src/taipanstack/utils/cache.py +6 -8
  28. taipanstack-0.4.0/src/taipanstack/utils/circuit_breaker.py +30 -0
  29. {taipanstack-0.3.11 → taipanstack-0.4.0}/src/taipanstack/utils/concurrency.py +8 -10
  30. {taipanstack-0.3.11 → taipanstack-0.4.0}/src/taipanstack/utils/rate_limit.py +6 -8
  31. taipanstack-0.4.0/src/taipanstack/utils/resilience.py +27 -0
  32. taipanstack-0.4.0/src/taipanstack/utils/retry.py +29 -0
  33. {taipanstack-0.3.11 → taipanstack-0.4.0}/LICENSE +0 -0
  34. {taipanstack-0.3.11 → taipanstack-0.4.0}/src/taipanstack/config/__init__.py +0 -0
  35. {taipanstack-0.3.11 → taipanstack-0.4.0}/src/taipanstack/config/generators.py +0 -0
  36. {taipanstack-0.3.11 → taipanstack-0.4.0}/src/taipanstack/config/models.py +0 -0
  37. {taipanstack-0.3.11 → taipanstack-0.4.0}/src/taipanstack/config/version_config.py +0 -0
  38. {taipanstack-0.3.11 → taipanstack-0.4.0}/src/taipanstack/core/__init__.py +0 -0
  39. {taipanstack-0.3.11 → taipanstack-0.4.0}/src/taipanstack/core/compat.py +0 -0
  40. {taipanstack-0.3.11 → taipanstack-0.4.0}/src/taipanstack/core/optimizations.py +0 -0
  41. {taipanstack-0.3.11/src/taipanstack/utils → taipanstack-0.4.0/src/taipanstack/resilience}/resilience.py +0 -0
  42. {taipanstack-0.3.11 → taipanstack-0.4.0}/src/taipanstack/security/__init__.py +0 -0
  43. {taipanstack-0.3.11 → taipanstack-0.4.0}/src/taipanstack/security/decorators.py +0 -0
  44. {taipanstack-0.3.11 → taipanstack-0.4.0}/src/taipanstack/security/jwt.py +0 -0
  45. {taipanstack-0.3.11 → taipanstack-0.4.0}/src/taipanstack/security/models.py +0 -0
  46. {taipanstack-0.3.11 → taipanstack-0.4.0}/src/taipanstack/security/types.py +0 -0
  47. {taipanstack-0.3.11 → taipanstack-0.4.0}/src/taipanstack/security/validators.py +0 -0
  48. {taipanstack-0.3.11 → taipanstack-0.4.0}/src/taipanstack/utils/__init__.py +0 -0
  49. {taipanstack-0.3.11 → taipanstack-0.4.0}/src/taipanstack/utils/context.py +0 -0
  50. {taipanstack-0.3.11 → taipanstack-0.4.0}/src/taipanstack/utils/filesystem.py +0 -0
  51. {taipanstack-0.3.11 → taipanstack-0.4.0}/src/taipanstack/utils/logging.py +0 -0
  52. {taipanstack-0.3.11 → taipanstack-0.4.0}/src/taipanstack/utils/metrics.py +0 -0
  53. {taipanstack-0.3.11 → taipanstack-0.4.0}/src/taipanstack/utils/serialization.py +0 -0
  54. {taipanstack-0.3.11 → taipanstack-0.4.0}/src/taipanstack/utils/subprocess.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: taipanstack
3
- Version: 0.3.11
3
+ Version: 0.4.0
4
4
  Summary: TaipanStack - Modular, secure, and scalable Python stack for robust development
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -18,15 +18,34 @@ Classifier: Programming Language :: Python :: 3.14
18
18
  Classifier: Topic :: Software Development :: Quality Assurance
19
19
  Classifier: Topic :: Security
20
20
  Classifier: Typing :: Typed
21
+ Provides-Extra: all
22
+ Provides-Extra: bridges-db
23
+ Provides-Extra: bridges-http
24
+ Provides-Extra: bridges-web
25
+ Provides-Extra: resilience
21
26
  Provides-Extra: runtime
22
27
  Requires-Dist: argon2-cffi (>=25.1.0,<26.0.0)
23
28
  Requires-Dist: email-validator (>=2.0.0)
29
+ Requires-Dist: fastapi (>=0.100.0) ; extra == "all"
30
+ Requires-Dist: fastapi (>=0.100.0) ; extra == "bridges-web"
31
+ Requires-Dist: httpx (>=0.24.0) ; extra == "all"
32
+ Requires-Dist: httpx (>=0.24.0) ; extra == "bridges-http"
33
+ Requires-Dist: litestar (>=2.0.0) ; extra == "all"
34
+ Requires-Dist: litestar (>=2.0.0) ; extra == "bridges-web"
24
35
  Requires-Dist: orjson (>=3.9.0)
36
+ Requires-Dist: psutil (>=5.9.0) ; extra == "all"
37
+ Requires-Dist: psutil (>=5.9.0) ; extra == "resilience"
25
38
  Requires-Dist: pydantic (>=2.0)
26
39
  Requires-Dist: pydantic-settings (>=2.0.0)
27
40
  Requires-Dist: pyjwt (>=2.11.0,<3.0.0)
41
+ Requires-Dist: redis (>=5.0.0) ; extra == "all"
42
+ Requires-Dist: redis (>=5.0.0) ; extra == "bridges-db"
28
43
  Requires-Dist: result (>=0.17.0)
44
+ Requires-Dist: sqlalchemy (>=2.0.0) ; extra == "all"
45
+ Requires-Dist: sqlalchemy (>=2.0.0) ; extra == "bridges-db"
46
+ Requires-Dist: structlog (>=23.0.0) ; extra == "all"
29
47
  Requires-Dist: structlog (>=23.0.0) ; extra == "runtime"
48
+ Requires-Dist: uvloop (>=0.19.0) ; (sys_platform != "win32") and (extra == "all")
30
49
  Requires-Dist: uvloop (>=0.19.0) ; (sys_platform != "win32") and (extra == "runtime")
31
50
  Project-URL: Changelog, https://github.com/gabrielima7/TaipanStack/blob/main/CHANGELOG.md
32
51
  Project-URL: Documentation, https://gabrielima7.github.io/TaipanStack/
@@ -104,7 +123,7 @@ TaipanStack is a battle-tested foundation for production-grade Python projects t
104
123
 
105
124
  ### 🔧 Developer Experience
106
125
  - Pre-configured quality tools
107
- - **100% code coverage** (1006 tests)
126
+ - **100% code coverage** (1164 tests)
108
127
  - Architecture enforcement
109
128
  - Hardened Docker template
110
129
 
@@ -146,7 +165,7 @@ make all
146
165
  ### Verify Installation
147
166
 
148
167
  ```bash
149
- # Run tests with 100% coverage (1006 tests)
168
+ # Run tests with 100% coverage (1164 tests)
150
169
  make test
151
170
 
152
171
  # Check architecture contracts
@@ -201,7 +220,7 @@ TaipanStack/
201
220
  │ ├── config/ # ⚙️ Configuration models & generators
202
221
  │ ├── security/ # 🛡️ Guards, sanitizers, validators
203
222
  │ └── utils/ # 🔧 Logging, metrics, retry, filesystem
204
- ├── tests/ # ✅ 1006 tests, 100% coverage
223
+ ├── tests/ # ✅ 1164 tests, 100% coverage
205
224
  ├── .semgrep/ # 🔍 Custom SAST rules
206
225
  ├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
207
226
  ├── Dockerfile # 🐳 Hardened multi-stage container
@@ -340,6 +359,28 @@ def fetch_user_profile(user_id: str) -> dict:
340
359
  profile = unwrap_or(fetch_user_profile("usr_456"), {"name": "Unknown"})
341
360
  ```
342
361
 
362
+ ### 🔗 Adaptive Resilience Pipeline
363
+
364
+ ```python
365
+ from taipanstack.core.result import Result, Ok, Err
366
+ from taipanstack.resilience.adaptive import ResilienceOrchestrator, AdaptiveCircuitBreaker
367
+ from taipanstack.resilience.retry import RetryConfig
368
+
369
+ # Compose an intelligent pipeline: Bulkhead -> Breaker -> Retry -> Timeout -> Fallback
370
+ orch = (
371
+ ResilienceOrchestrator("billing_api")
372
+ .with_bulkhead(max_concurrent=10, max_queue=50) # Prevent resource exhaustion
373
+ .with_circuit_breaker(AdaptiveCircuitBreaker("billing", target_error_rate=0.1)) # Auto-tunes thresholds
374
+ .with_retry(RetryConfig(max_attempts=3, initial_delay=0.1))
375
+ .with_timeout(5.0)
376
+ .with_fallback({"status": "unavailable"})
377
+ )
378
+
379
+ async def process_billing() -> Result[dict, Exception]:
380
+ # The orchestrator handles all concurrency, retry, circuit breaking, and fallbacks
381
+ return await orch.execute(stripe_gateway.charge)
382
+ ```
383
+
343
384
  ### Intelligent Caching
344
385
 
345
386
  ```python
@@ -67,7 +67,7 @@ TaipanStack is a battle-tested foundation for production-grade Python projects t
67
67
 
68
68
  ### 🔧 Developer Experience
69
69
  - Pre-configured quality tools
70
- - **100% code coverage** (1006 tests)
70
+ - **100% code coverage** (1164 tests)
71
71
  - Architecture enforcement
72
72
  - Hardened Docker template
73
73
 
@@ -109,7 +109,7 @@ make all
109
109
  ### Verify Installation
110
110
 
111
111
  ```bash
112
- # Run tests with 100% coverage (1006 tests)
112
+ # Run tests with 100% coverage (1164 tests)
113
113
  make test
114
114
 
115
115
  # Check architecture contracts
@@ -164,7 +164,7 @@ TaipanStack/
164
164
  │ ├── config/ # ⚙️ Configuration models & generators
165
165
  │ ├── security/ # 🛡️ Guards, sanitizers, validators
166
166
  │ └── utils/ # 🔧 Logging, metrics, retry, filesystem
167
- ├── tests/ # ✅ 1006 tests, 100% coverage
167
+ ├── tests/ # ✅ 1164 tests, 100% coverage
168
168
  ├── .semgrep/ # 🔍 Custom SAST rules
169
169
  ├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
170
170
  ├── Dockerfile # 🐳 Hardened multi-stage container
@@ -303,6 +303,28 @@ def fetch_user_profile(user_id: str) -> dict:
303
303
  profile = unwrap_or(fetch_user_profile("usr_456"), {"name": "Unknown"})
304
304
  ```
305
305
 
306
+ ### 🔗 Adaptive Resilience Pipeline
307
+
308
+ ```python
309
+ from taipanstack.core.result import Result, Ok, Err
310
+ from taipanstack.resilience.adaptive import ResilienceOrchestrator, AdaptiveCircuitBreaker
311
+ from taipanstack.resilience.retry import RetryConfig
312
+
313
+ # Compose an intelligent pipeline: Bulkhead -> Breaker -> Retry -> Timeout -> Fallback
314
+ orch = (
315
+ ResilienceOrchestrator("billing_api")
316
+ .with_bulkhead(max_concurrent=10, max_queue=50) # Prevent resource exhaustion
317
+ .with_circuit_breaker(AdaptiveCircuitBreaker("billing", target_error_rate=0.1)) # Auto-tunes thresholds
318
+ .with_retry(RetryConfig(max_attempts=3, initial_delay=0.1))
319
+ .with_timeout(5.0)
320
+ .with_fallback({"status": "unavailable"})
321
+ )
322
+
323
+ async def process_billing() -> Result[dict, Exception]:
324
+ # The orchestrator handles all concurrency, retry, circuit breaking, and fallbacks
325
+ return await orch.execute(stripe_gateway.charge)
326
+ ```
327
+
306
328
  ### Intelligent Caching
307
329
 
308
330
  ```python
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "taipanstack"
3
- version = "0.3.11"
3
+ version = "0.4.0"
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"}
@@ -44,6 +44,35 @@ runtime = [
44
44
  "uvloop (>=0.19.0); sys_platform != 'win32'",
45
45
  "structlog (>=23.0.0)",
46
46
  ]
47
+ bridges-web = [
48
+ "fastapi (>=0.100.0)",
49
+ "litestar (>=2.0.0)",
50
+ ]
51
+ bridges-http = [
52
+ "httpx (>=0.24.0)",
53
+ ]
54
+ bridges-db = [
55
+ "sqlalchemy (>=2.0.0)",
56
+ "redis (>=5.0.0)",
57
+ ]
58
+ resilience = [
59
+ "psutil (>=5.9.0)",
60
+ ]
61
+ all = [
62
+ # runtime
63
+ "uvloop (>=0.19.0); sys_platform != 'win32'",
64
+ "structlog (>=23.0.0)",
65
+ # bridges-web
66
+ "fastapi (>=0.100.0)",
67
+ "litestar (>=2.0.0)",
68
+ # bridges-http
69
+ "httpx (>=0.24.0)",
70
+ # bridges-db
71
+ "sqlalchemy (>=2.0.0)",
72
+ "redis (>=5.0.0)",
73
+ # resilience
74
+ "psutil (>=5.9.0)",
75
+ ]
47
76
 
48
77
  [build-system]
49
78
  requires = ["poetry-core>=2.0.0,<3.0.0"]
@@ -71,6 +100,13 @@ dev = [
71
100
  "pytest-asyncio (>=0.23.0)",
72
101
  "radon (>=6.0.1,<7.0.0)",
73
102
  "pip-audit (>=2.10.0,<3.0.0)",
103
+ # Security: CVE fix - requests <2.33.0 has insecure temp file reuse (CWE-377)
104
+ # Dependabot alert #17 - CVSS 4.4/10 Moderate
105
+ "requests (>=2.33.0)",
106
+ # Security note: Pygments <=2.19.2 has ReDoS via AdILexer (Dependabot alert #16)
107
+ # CVSS 1.9/10 Low - local attack vector only, no upstream patch available yet
108
+ # Pinned to latest available; monitor for upstream fix in pygments >2.19.2
109
+ "pygments (>=2.19.2)",
74
110
  ]
75
111
 
76
112
 
@@ -137,6 +173,11 @@ max-complexity = 10
137
173
  "src/taipanstack/utils/metrics.py" = ["D401"]
138
174
  # Core result: allow D401 for utility function docstrings
139
175
  "src/taipanstack/core/result.py" = ["D401"]
176
+ # Resilience module: allow D401, too many args, random for jitter
177
+ "src/taipanstack/resilience/*.py" = ["PLR0913", "D401", "S311", "TRY300", "TRY400"]
178
+ "src/taipanstack/resilience/watchdogs/*.py" = ["PLR0913", "D401", "TRY300", "TRY400"]
179
+ "src/taipanstack/resilience/adaptive/*.py" = ["PLR0913", "PLR0912", "D401", "TRY300", "TRY400"]
180
+ "src/taipanstack/bridges/*.py" = ["PLR0913", "D401", "TRY300", "TRY400"]
140
181
 
141
182
  [tool.ruff.format]
142
183
  quote-style = "double"
@@ -229,7 +270,7 @@ fail-under = 80
229
270
  verbose = 1
230
271
 
231
272
  [tool.mutmut]
232
- paths_to_mutate = "src/taipanstack/security/sanitizers.py,src/taipanstack/security/validators.py,src/taipanstack/security/guards.py,src/taipanstack/utils/retry.py,src/taipanstack/utils/circuit_breaker.py"
273
+ paths_to_mutate = "src/taipanstack/security/sanitizers.py,src/taipanstack/security/validators.py,src/taipanstack/security/guards.py,src/taipanstack/resilience/retry.py,src/taipanstack/resilience/circuit_breaker.py"
233
274
  tests_dir = "tests/test_property_sanitizers.py,tests/test_security_validators.py,tests/test_security_guards.py,tests/test_security_ssrf.py,tests/test_utils_retry.py,tests/test_utils_circuit_breaker.py"
234
275
  runner = "python -m pytest -x -q --tb=no --timeout=10 --no-cov"
235
276
  dict_synonyms = "Struct, NamedStruct"
@@ -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.3.11"
8
+ __version__ = "0.4.0"
9
9
 
10
10
  from taipanstack.config.version_config import (
11
11
  VersionRecommendations,
@@ -0,0 +1,31 @@
1
+ """Taipan Bridges — universal integration layer.
2
+
3
+ Provides adapters connecting TaipanStack's security, resilience,
4
+ and error handling with popular Python libraries.
5
+
6
+ Sub-modules:
7
+ http_bridge: Safe httpx client with SSRF protection.
8
+ web_bridge: ASGI middleware for rate limiting / security headers.
9
+ db_bridge: Resilient SQLAlchemy / Redis wrappers.
10
+ """
11
+
12
+ from taipanstack.bridges._imports import get_attr_or_err, require_dependency
13
+ from taipanstack.bridges.db_bridge import ResilientDatabase, ResilientRedis
14
+ from taipanstack.bridges.http_bridge import SafeHttpClient, safe_request
15
+ from taipanstack.bridges.web_bridge import (
16
+ SecurityHeadersConfig,
17
+ TaipanMiddleware,
18
+ result_to_response,
19
+ )
20
+
21
+ __all__ = (
22
+ "ResilientDatabase",
23
+ "ResilientRedis",
24
+ "SafeHttpClient",
25
+ "SecurityHeadersConfig",
26
+ "TaipanMiddleware",
27
+ "get_attr_or_err",
28
+ "require_dependency",
29
+ "result_to_response",
30
+ "safe_request",
31
+ )
@@ -0,0 +1,68 @@
1
+ """
2
+ Lazy optional import helpers for Taipan Bridges.
3
+
4
+ Provides a centralised mechanism to handle optional dependencies
5
+ that may or may not be installed at runtime.
6
+ """
7
+
8
+ import importlib
9
+ import types
10
+ from typing import Any
11
+
12
+ from taipanstack.core.result import Err, Ok, Result
13
+
14
+
15
+ def require_dependency(
16
+ module_name: str,
17
+ *,
18
+ pip_extra: str = "",
19
+ ) -> Result[types.ModuleType, ImportError]:
20
+ """Attempt to import *module_name* and return a ``Result``.
21
+
22
+ Args:
23
+ module_name: Dotted module path (e.g. ``"httpx"``).
24
+ pip_extra: Optional pip extra name for the error message.
25
+
26
+ Returns:
27
+ ``Ok(module)`` if available, ``Err(ImportError)`` otherwise.
28
+
29
+ Example:
30
+ >>> require_dependency("httpx", pip_extra="bridges-http")
31
+ Ok(<module 'httpx' ...>)
32
+
33
+ """
34
+ try:
35
+ mod = importlib.import_module(module_name)
36
+ return Ok(mod)
37
+ except ImportError:
38
+ install_hint = (
39
+ f"pip install taipanstack[{pip_extra}]"
40
+ if pip_extra
41
+ else f"pip install {module_name}"
42
+ )
43
+ return Err(
44
+ ImportError(
45
+ f"'{module_name}' is required but not installed. "
46
+ f"Install with: {install_hint}"
47
+ )
48
+ )
49
+
50
+
51
+ def get_attr_or_err(
52
+ module: types.ModuleType,
53
+ name: str,
54
+ ) -> Result[Any, AttributeError]:
55
+ """Safely access an attribute from a module.
56
+
57
+ Args:
58
+ module: The imported module.
59
+ name: Attribute name to retrieve.
60
+
61
+ Returns:
62
+ ``Ok(attr)`` if found, ``Err(AttributeError)`` otherwise.
63
+
64
+ """
65
+ try:
66
+ return Ok(getattr(module, name))
67
+ except AttributeError as exc:
68
+ return Err(exc)
@@ -0,0 +1,253 @@
1
+ """
2
+ DB Bridge — resilient database wrappers.
3
+
4
+ Wraps SQLAlchemy async engine and Redis async client with
5
+ TaipanStack's circuit breaker and retry patterns.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import logging
12
+ from typing import Any
13
+
14
+ from taipanstack.core.result import Err, Ok, Result
15
+ from taipanstack.resilience.circuit_breaker import (
16
+ CircuitBreaker,
17
+ CircuitBreakerError,
18
+ CircuitState,
19
+ )
20
+ from taipanstack.resilience.retry import RetryConfig, calculate_delay
21
+
22
+ logger = logging.getLogger("taipanstack.bridges.db")
23
+
24
+ # --- optional imports ------------------------------------------------------
25
+
26
+ try:
27
+ import sqlalchemy # noqa: F401
28
+ from sqlalchemy import text as sa_text # pragma: no cover
29
+ from sqlalchemy.ext.asyncio import AsyncSession # pragma: no cover
30
+
31
+ _HAS_SQLALCHEMY = True # pragma: no cover
32
+ except ImportError: # pragma: no cover
33
+ _HAS_SQLALCHEMY = False
34
+
35
+ try:
36
+ import redis.asyncio as aioredis # noqa: F401
37
+
38
+ _HAS_REDIS = True # pragma: no cover
39
+ except ImportError: # pragma: no cover
40
+ _HAS_REDIS = False
41
+
42
+
43
+ def _breaker_is_open(cb: CircuitBreaker) -> CircuitBreakerError | None:
44
+ """Return a ``CircuitBreakerError`` if the breaker is OPEN.
45
+
46
+ Args:
47
+ cb: The circuit breaker to check.
48
+
49
+ Returns:
50
+ Error if open, ``None`` otherwise.
51
+
52
+ """
53
+ if cb.state == CircuitState.OPEN:
54
+ return CircuitBreakerError(
55
+ f"Circuit breaker '{cb.name}' is OPEN",
56
+ state=cb.state,
57
+ )
58
+ return None
59
+
60
+
61
+ class ResilientDatabase:
62
+ """Wraps a SQLAlchemy async engine with resilience patterns.
63
+
64
+ Args:
65
+ engine: SQLAlchemy ``AsyncEngine`` instance.
66
+ circuit_breaker: Optional circuit breaker.
67
+ retry_config: Optional retry configuration.
68
+
69
+ Example:
70
+ >>> db = ResilientDatabase(engine, circuit_breaker=breaker)
71
+ >>> result = await db.execute(text("SELECT 1"))
72
+
73
+ """
74
+
75
+ def __init__(
76
+ self,
77
+ engine: Any,
78
+ *,
79
+ circuit_breaker: CircuitBreaker | None = None,
80
+ retry_config: RetryConfig | None = None,
81
+ ) -> None:
82
+ """Initialize the resilient database wrapper.
83
+
84
+ Args:
85
+ engine: SQLAlchemy AsyncEngine.
86
+ circuit_breaker: Optional circuit breaker.
87
+ retry_config: Optional retry config.
88
+
89
+ """
90
+ self._engine = engine
91
+ self._circuit_breaker = circuit_breaker
92
+ self._retry_config = retry_config
93
+
94
+ async def execute(
95
+ self,
96
+ statement: Any,
97
+ **kwargs: Any,
98
+ ) -> Result[Any, Exception]:
99
+ """Execute a SQL statement with resilience.
100
+
101
+ Args:
102
+ statement: SQLAlchemy statement to execute.
103
+ **kwargs: Passed to ``session.execute``.
104
+
105
+ Returns:
106
+ ``Ok(result)`` on success, ``Err`` on failure.
107
+
108
+ """
109
+ if not _HAS_SQLALCHEMY:
110
+ return Err(
111
+ ImportError(
112
+ "sqlalchemy is required for ResilientDatabase. "
113
+ "Install with: pip install taipanstack[bridges-db]"
114
+ )
115
+ )
116
+
117
+ # Circuit breaker gate
118
+ if self._circuit_breaker is not None:
119
+ cb_err = _breaker_is_open(self._circuit_breaker)
120
+ if cb_err is not None:
121
+ return Err(cb_err)
122
+
123
+ max_attempts = 1
124
+ if self._retry_config is not None:
125
+ max_attempts = self._retry_config.max_attempts
126
+
127
+ last_error: Exception | None = None
128
+
129
+ for attempt in range(1, max_attempts + 1):
130
+ try:
131
+ async with AsyncSession(self._engine) as session:
132
+ result = await session.execute(statement, **kwargs)
133
+ return Ok(result)
134
+ except Exception as exc:
135
+ last_error = exc
136
+ logger.warning(
137
+ "DB execute attempt %d failed: %s",
138
+ attempt,
139
+ exc,
140
+ )
141
+ if self._circuit_breaker is not None:
142
+ self._circuit_breaker._record_failure(exc)
143
+ if self._retry_config is not None and attempt < max_attempts:
144
+ delay = calculate_delay(attempt, self._retry_config)
145
+ await asyncio.sleep(delay)
146
+ continue
147
+ break
148
+
149
+ return Err(last_error or RuntimeError("Database execute failed"))
150
+
151
+ async def health_check(self) -> Result[bool, Exception]:
152
+ """Check database connectivity.
153
+
154
+ Executes ``SELECT 1`` to verify the connection is alive.
155
+
156
+ Returns:
157
+ ``Ok(True)`` if healthy, ``Err`` on failure.
158
+
159
+ """
160
+ if not _HAS_SQLALCHEMY:
161
+ return Err(ImportError("sqlalchemy is required for health check"))
162
+
163
+ try:
164
+ async with AsyncSession(self._engine) as session:
165
+ await session.execute(sa_text("SELECT 1"))
166
+ return Ok(True)
167
+ except Exception as exc:
168
+ return Err(exc)
169
+
170
+
171
+ class ResilientRedis:
172
+ """Wraps a Redis async client with resilience patterns.
173
+
174
+ Args:
175
+ client: ``redis.asyncio.Redis`` instance.
176
+ circuit_breaker: Optional circuit breaker.
177
+
178
+ Example:
179
+ >>> r = ResilientRedis(redis_client, circuit_breaker=breaker)
180
+ >>> result = await r.execute("GET", "my_key")
181
+
182
+ """
183
+
184
+ def __init__(
185
+ self,
186
+ client: Any,
187
+ *,
188
+ circuit_breaker: CircuitBreaker | None = None,
189
+ ) -> None:
190
+ """Initialize the resilient Redis wrapper.
191
+
192
+ Args:
193
+ client: Redis async client.
194
+ circuit_breaker: Optional circuit breaker.
195
+
196
+ """
197
+ self._client = client
198
+ self._circuit_breaker = circuit_breaker
199
+
200
+ async def execute(
201
+ self,
202
+ command: str,
203
+ *args: Any,
204
+ ) -> Result[Any, Exception]:
205
+ """Execute a Redis command with resilience.
206
+
207
+ Args:
208
+ command: Redis command name (e.g. ``"GET"``, ``"SET"``).
209
+ *args: Command arguments.
210
+
211
+ Returns:
212
+ ``Ok(result)`` on success, ``Err`` on failure.
213
+
214
+ """
215
+ if not _HAS_REDIS:
216
+ return Err(
217
+ ImportError(
218
+ "redis is required for ResilientRedis. "
219
+ "Install with: pip install taipanstack[bridges-db]"
220
+ )
221
+ )
222
+
223
+ # Circuit breaker gate
224
+ if self._circuit_breaker is not None:
225
+ cb_err = _breaker_is_open(self._circuit_breaker)
226
+ if cb_err is not None:
227
+ return Err(cb_err)
228
+
229
+ try:
230
+ fn = getattr(self._client, command.lower())
231
+ result = await fn(*args)
232
+ return Ok(result)
233
+ except Exception as exc:
234
+ logger.warning("Redis command '%s' failed: %s", command, exc)
235
+ if self._circuit_breaker is not None:
236
+ self._circuit_breaker._record_failure(exc)
237
+ return Err(exc)
238
+
239
+ async def health_check(self) -> Result[bool, Exception]:
240
+ """Check Redis connectivity via PING.
241
+
242
+ Returns:
243
+ ``Ok(True)`` if healthy, ``Err`` on failure.
244
+
245
+ """
246
+ if not _HAS_REDIS:
247
+ return Err(ImportError("redis is required for health check"))
248
+
249
+ try:
250
+ pong = await self._client.ping()
251
+ return Ok(bool(pong))
252
+ except Exception as exc:
253
+ return Err(exc)