taipanstack 0.5.3__tar.gz → 0.6.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 (53) hide show
  1. {taipanstack-0.5.3 → taipanstack-0.6.0}/PKG-INFO +30 -29
  2. {taipanstack-0.5.3 → taipanstack-0.6.0}/README.md +27 -27
  3. {taipanstack-0.5.3 → taipanstack-0.6.0}/pyproject.toml +6 -5
  4. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/__init__.py +1 -1
  5. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/bridges/db_bridge.py +84 -35
  6. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/bridges/http_bridge.py +37 -23
  7. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/bridges/web_bridge.py +18 -6
  8. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/config/generators.py +18 -3
  9. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/core/compat.py +2 -5
  10. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/core/result.py +22 -15
  11. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/resilience/adaptive/bulkhead.py +38 -15
  12. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/resilience/adaptive/orchestrator.py +35 -18
  13. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/resilience/circuit_breaker.py +126 -78
  14. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/resilience/resilience.py +9 -3
  15. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/resilience/retry.py +61 -51
  16. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/resilience/watchdogs/health_pinger.py +16 -2
  17. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/security/decorators.py +7 -13
  18. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/security/guards.py +90 -16
  19. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/security/jwt.py +16 -11
  20. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/security/models.py +15 -13
  21. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/security/password.py +2 -2
  22. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/security/sanitizers.py +78 -8
  23. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/security/validators.py +21 -6
  24. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/utils/cache.py +45 -37
  25. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/utils/concurrency.py +69 -28
  26. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/utils/filesystem.py +41 -25
  27. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/utils/logging.py +17 -12
  28. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/utils/rate_limit.py +19 -10
  29. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/utils/subprocess.py +5 -3
  30. {taipanstack-0.5.3 → taipanstack-0.6.0}/LICENSE +0 -0
  31. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/bridges/__init__.py +0 -0
  32. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/bridges/_imports.py +0 -0
  33. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/config/__init__.py +0 -0
  34. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/config/models.py +0 -0
  35. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/config/version_config.py +0 -0
  36. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/core/__init__.py +0 -0
  37. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/core/optimizations.py +0 -0
  38. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/resilience/__init__.py +0 -0
  39. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/resilience/adaptive/__init__.py +0 -0
  40. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/resilience/adaptive/adaptive_breaker.py +0 -0
  41. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/resilience/adaptive/adaptive_retry.py +0 -0
  42. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/resilience/watchdogs/__init__.py +0 -0
  43. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/resilience/watchdogs/_base.py +0 -0
  44. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/resilience/watchdogs/config_watcher.py +0 -0
  45. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/resilience/watchdogs/resource_watcher.py +0 -0
  46. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/security/__init__.py +0 -0
  47. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/security/types.py +0 -0
  48. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/utils/__init__.py +0 -0
  49. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/utils/circuit_breaker.py +0 -0
  50. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/utils/context.py +0 -0
  51. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/utils/resilience.py +0 -0
  52. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/utils/retry.py +0 -0
  53. {taipanstack-0.5.3 → taipanstack-0.6.0}/src/taipanstack/utils/serialization.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: taipanstack
3
- Version: 0.5.3
3
+ Version: 0.6.0
4
4
  Summary: TaipanStack - Modular, secure, and scalable Python stack for robust development
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -32,12 +32,13 @@ Requires-Dist: httpx (>=0.24.0) ; extra == "all"
32
32
  Requires-Dist: httpx (>=0.24.0) ; extra == "bridges-http"
33
33
  Requires-Dist: litestar (>=2.0.0) ; extra == "all"
34
34
  Requires-Dist: litestar (>=2.0.0) ; extra == "bridges-web"
35
+ Requires-Dist: msgpack (>=1.2.1,<2.0.0)
35
36
  Requires-Dist: orjson (>=3.9.0)
36
37
  Requires-Dist: pip (>=26.1,<27.0)
37
38
  Requires-Dist: psutil (>=5.9.0) ; extra == "all"
38
39
  Requires-Dist: psutil (>=5.9.0) ; extra == "resilience"
39
40
  Requires-Dist: pydantic (>=2.0)
40
- Requires-Dist: pydantic-settings (>=2.0.0)
41
+ Requires-Dist: pydantic-settings (>=2.14.2,<3.0.0)
41
42
  Requires-Dist: pyjwt (>=2.11.0,<3.0.0)
42
43
  Requires-Dist: redis (>=5.0.0) ; extra == "all"
43
44
  Requires-Dist: redis (>=5.0.0) ; extra == "bridges-db"
@@ -88,11 +89,11 @@ Description-Content-Type: text/markdown
88
89
 
89
90
  Taipan Stack is a battle-tested foundation for production-grade Python projects that combines **security**, **performance**, and **developer experience** into a single, cohesive toolkit.
90
91
 
91
- ### ✨ What's New in v0.5.3
92
- - **Security Fixes & Hardening**: Fixed file descriptor leaks in `safe_write` on `BaseException` (PR #838). Hardened retry, fallback, and circuit breaker decorators/classes against runtime type mutations, clock jumps, and NaN state poisoning under chaos injection (PR #852, #853, #842, #856, #839, #864).
93
- - **Complexity Refactor**: Reduced cyclomatic and cognitive complexity in orchestrators, circuit breakers, and logging/retry utils (PR #862, #844, #866).
94
- - **QA & Test Count**: Standardized test naming conventions (PR #847), expanded test coverage to 100% genuine code and branch coverage across core components, verifying **1,344 passing tests** (PR #843, #857, #850).
95
- - **Documentation & CI/CD**: Cleaned up dead references and links (PR #854, #851), updated watchdogs code examples (PR #867), and synchronized CI badges (PR #863).
92
+ ### ✨ What's New in v0.6.0
93
+ - **Security & Hardening**: Hardened path sanitization, file extension checking, SSRF protections, and URL smugglers with bounds checks and strict type validation (PR #871, #900, #903, #908, #924, #951, #955, #957, #959).
94
+ - **Resilience and Concurrency**: Fixed concurrency permit leaks, potential infinite loops in health watchdogs, and stabilized timeout structures under cancellation and arithmetic overflow scenarios (PR #932, #937, #940, #948).
95
+ - **Typing & Clean Code**: Refactored hot paths to drastically reduce cyclomatic and cognitive complexity, and enhanced static typing with explicit `TypeAlias`, `Literal`, and `TypeGuard` mapping (PR #887, #901, #918, #964).
96
+ - **QA and Standardized Testing**: Consolidated and fully standardized the naming conventions across the entire testing suite, verifying **1,430 passing tests** with 100% genuine branch coverage and no bypasses (PR #882, #886, #891, #894, #909, #912, #926, #930, #944, #954).
96
97
 
97
98
  <table>
98
99
  <tr>
@@ -129,7 +130,7 @@ Taipan Stack is a battle-tested foundation for production-grade Python projects
129
130
 
130
131
  ### 🔧 Developer Experience
131
132
  - Pre-configured quality tools
132
- - **100% code coverage** (1,344 tests)
133
+ - **100% code coverage** (1,430 tests)
133
134
  - Architecture enforcement
134
135
  - Hardened Docker template
135
136
 
@@ -171,7 +172,7 @@ make all
171
172
  ### Verify Installation
172
173
 
173
174
  ```bash
174
- # Run tests with 100% coverage (1,344 tests)
175
+ # Run tests with 100% coverage (1,430 tests)
175
176
  make test
176
177
 
177
178
  # Check architecture contracts
@@ -192,25 +193,25 @@ make property-test
192
193
  Taipan Stack follows a clean, layered architecture with strict dependency rules enforced by **Import Linter**.
193
194
 
194
195
  ```
195
- ┌─────────────────────────────────────┐
196
- │ Application │
197
- │ (src/app/main.py) │
198
- └─────────────────┬───────────────────┘
199
- │
200
- ┌───────────────────────────┼───────────────────────────┐
201
- ▼ ▼ ▼
202
- ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
203
- │ Security │ │ Config │ │ Utils │
204
- │ guards, saniti- │ │ models, │ │ logging, retry │
205
- │ zers, validators│ │ generators │ │ metrics, fs │
206
- └────────┬────────┘ └────────┬────────┘ └────────┬────────┘
207
- │ │ │
208
- └─────────────────────────┼─────────────────────────┘
209
- ▼
210
- ┌─────────────────────────────────────┐
211
- │ Core │
212
- │ Result types, base patterns │
213
- └─────────────────────────────────────┘
196
+ ┌────────────────────────────────────────────────────────┐
197
+ │ Application │
198
+ │ (src/app/main.py) │
199
+ └───────────────────────────┬────────────────────────────┘
200
+ │
201
+ ┌───────────────┬─────────────────────┼───────────────┬──────────────┐
202
+ ▼ ▼ ▼ ▼ ▼
203
+ ┌─────────────────┐┌──────────────┐ ┌──────────────┐┌──────────────┐┌──────────────┐
204
+ │ Security ││ Config │ │ Bridges ││ Resilience ││ Utils │
205
+ │ guards, saniti- ││ models, gens │ │ http, db ││ retry, break ││ logging, fs │
206
+ │ zers, validators││ │ │ ││ watchdogs ││ context │
207
+ └────────┬────────┘└──────┬───────┘ └───────┬──────┘└───────┬──────┘└──────┬───────┘
208
+ │ │ │ │ │
209
+ └────────────────┴─────────────────────┼───────────────┴──────────────┘
210
+ ▼
211
+ ┌────────────────────────────────┐
212
+ │ Core │
213
+ │ Result types, optimizations │
214
+ └────────────────────────────────┘
214
215
  ```
215
216
 
216
217
  ### Project Structure
@@ -224,7 +225,7 @@ TaipanStack/
224
225
  │ ├── config/ # ⚙️ Configuration models & generators
225
226
  │ ├── security/ # 🛡️ Guards, sanitizers, validators
226
227
  │ └── utils/ # 🔧 Logging, metrics, retry, filesystem
227
- ├── tests/ # ✅ 1,344 tests, 100% coverage
228
+ ├── tests/ # ✅ 1,430 tests, 100% coverage
228
229
  ├── .semgrep/ # 🔍 Custom SAST rules
229
230
  ├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
230
231
  ├── Dockerfile # 🐳 Hardened multi-stage container
@@ -31,11 +31,11 @@
31
31
 
32
32
  Taipan Stack 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.5.3
35
- - **Security Fixes & Hardening**: Fixed file descriptor leaks in `safe_write` on `BaseException` (PR #838). Hardened retry, fallback, and circuit breaker decorators/classes against runtime type mutations, clock jumps, and NaN state poisoning under chaos injection (PR #852, #853, #842, #856, #839, #864).
36
- - **Complexity Refactor**: Reduced cyclomatic and cognitive complexity in orchestrators, circuit breakers, and logging/retry utils (PR #862, #844, #866).
37
- - **QA & Test Count**: Standardized test naming conventions (PR #847), expanded test coverage to 100% genuine code and branch coverage across core components, verifying **1,344 passing tests** (PR #843, #857, #850).
38
- - **Documentation & CI/CD**: Cleaned up dead references and links (PR #854, #851), updated watchdogs code examples (PR #867), and synchronized CI badges (PR #863).
34
+ ### ✨ What's New in v0.6.0
35
+ - **Security & Hardening**: Hardened path sanitization, file extension checking, SSRF protections, and URL smugglers with bounds checks and strict type validation (PR #871, #900, #903, #908, #924, #951, #955, #957, #959).
36
+ - **Resilience and Concurrency**: Fixed concurrency permit leaks, potential infinite loops in health watchdogs, and stabilized timeout structures under cancellation and arithmetic overflow scenarios (PR #932, #937, #940, #948).
37
+ - **Typing & Clean Code**: Refactored hot paths to drastically reduce cyclomatic and cognitive complexity, and enhanced static typing with explicit `TypeAlias`, `Literal`, and `TypeGuard` mapping (PR #887, #901, #918, #964).
38
+ - **QA and Standardized Testing**: Consolidated and fully standardized the naming conventions across the entire testing suite, verifying **1,430 passing tests** with 100% genuine branch coverage and no bypasses (PR #882, #886, #891, #894, #909, #912, #926, #930, #944, #954).
39
39
 
40
40
  <table>
41
41
  <tr>
@@ -72,7 +72,7 @@ Taipan Stack is a battle-tested foundation for production-grade Python projects
72
72
 
73
73
  ### 🔧 Developer Experience
74
74
  - Pre-configured quality tools
75
- - **100% code coverage** (1,344 tests)
75
+ - **100% code coverage** (1,430 tests)
76
76
  - Architecture enforcement
77
77
  - Hardened Docker template
78
78
 
@@ -114,7 +114,7 @@ make all
114
114
  ### Verify Installation
115
115
 
116
116
  ```bash
117
- # Run tests with 100% coverage (1,344 tests)
117
+ # Run tests with 100% coverage (1,430 tests)
118
118
  make test
119
119
 
120
120
  # Check architecture contracts
@@ -135,25 +135,25 @@ make property-test
135
135
  Taipan Stack follows a clean, layered architecture with strict dependency rules enforced by **Import Linter**.
136
136
 
137
137
  ```
138
- ┌─────────────────────────────────────┐
139
- │ Application │
140
- │ (src/app/main.py) │
141
- └─────────────────┬───────────────────┘
142
- │
143
- ┌───────────────────────────┼───────────────────────────┐
144
- ▼ ▼ ▼
145
- ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
146
- │ Security │ │ Config │ │ Utils │
147
- │ guards, saniti- │ │ models, │ │ logging, retry │
148
- │ zers, validators│ │ generators │ │ metrics, fs │
149
- └────────┬────────┘ └────────┬────────┘ └────────┬────────┘
150
- │ │ │
151
- └─────────────────────────┼─────────────────────────┘
152
- ▼
153
- ┌─────────────────────────────────────┐
154
- │ Core │
155
- │ Result types, base patterns │
156
- └─────────────────────────────────────┘
138
+ ┌────────────────────────────────────────────────────────┐
139
+ │ Application │
140
+ │ (src/app/main.py) │
141
+ └───────────────────────────┬────────────────────────────┘
142
+ │
143
+ ┌───────────────┬─────────────────────┼───────────────┬──────────────┐
144
+ ▼ ▼ ▼ ▼ ▼
145
+ ┌─────────────────┐┌──────────────┐ ┌──────────────┐┌──────────────┐┌──────────────┐
146
+ │ Security ││ Config │ │ Bridges ││ Resilience ││ Utils │
147
+ │ guards, saniti- ││ models, gens │ │ http, db ││ retry, break ││ logging, fs │
148
+ │ zers, validators││ │ │ ││ watchdogs ││ context │
149
+ └────────┬────────┘└──────┬───────┘ └───────┬──────┘└───────┬──────┘└──────┬───────┘
150
+ │ │ │ │ │
151
+ └────────────────┴─────────────────────┼───────────────┴──────────────┘
152
+ ▼
153
+ ┌────────────────────────────────┐
154
+ │ Core │
155
+ │ Result types, optimizations │
156
+ └────────────────────────────────┘
157
157
  ```
158
158
 
159
159
  ### Project Structure
@@ -167,7 +167,7 @@ TaipanStack/
167
167
  │ ├── config/ # ⚙️ Configuration models & generators
168
168
  │ ├── security/ # 🛡️ Guards, sanitizers, validators
169
169
  │ └── utils/ # 🔧 Logging, metrics, retry, filesystem
170
- ├── tests/ # ✅ 1,344 tests, 100% coverage
170
+ ├── tests/ # ✅ 1,430 tests, 100% coverage
171
171
  ├── .semgrep/ # 🔍 Custom SAST rules
172
172
  ├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
173
173
  ├── Dockerfile # 🐳 Hardened multi-stage container
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "taipanstack"
3
- version = "0.5.3"
3
+ version = "0.6.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"}
@@ -23,13 +23,14 @@ classifiers = [
23
23
  ]
24
24
  dependencies = [
25
25
  "pydantic (>=2.0)",
26
- "pydantic-settings (>=2.0.0)",
26
+ "pydantic-settings (>=2.14.2,<3.0.0)",
27
27
  "orjson (>=3.9.0)",
28
28
  "email-validator (>=2.0.0)",
29
29
  "result (>=0.17.0)",
30
30
  "pyjwt (>=2.11.0,<3.0.0)",
31
31
  "argon2-cffi (>=25.1.0,<26.0.0)",
32
32
  "pip (>=26.1,<27.0)",
33
+ "msgpack (>=1.2.1,<2.0.0)",
33
34
  ]
34
35
 
35
36
  [project.urls]
@@ -102,7 +103,7 @@ dev = [
102
103
  "pygments (>=2.19.2)",
103
104
  "hypothesis (>=6.151.12,<7.0.0)",
104
105
  "authlib (>=1.6.11,<2.0.0)",
105
- "cryptography (>=46.0.7,<49.0.0)",
106
+ "cryptography (>=46.0.7,<50.0.0)",
106
107
  "mutmut (>=3.0.0,<4.0.0)",
107
108
  "mkdocs-material (>=9.7.6,<10.0.0)",
108
109
  ]
@@ -184,6 +185,7 @@ mypy_path = "src"
184
185
  explicit_package_bases = true
185
186
  warn_return_any = true
186
187
  warn_unused_configs = true
188
+ warn_unreachable = true
187
189
  disallow_untyped_defs = true
188
190
  disallow_any_unimported = false
189
191
  no_implicit_optional = true
@@ -210,7 +212,7 @@ warn_required_dynamic_aliases = true
210
212
 
211
213
  [tool.pytest.ini_options]
212
214
  testpaths = ["tests"]
213
- addopts = "-v --strict-markers --timeout=30 --cov=src --cov-report=html --cov-report=term-missing"
215
+ addopts = "-v --strict-markers --timeout=60 --cov=src --cov-report=html --cov-report=term-missing"
214
216
  asyncio_mode = "auto"
215
217
  asyncio_default_fixture_loop_scope = "function"
216
218
  markers = [
@@ -248,4 +250,3 @@ paths_to_mutate = ["src/taipanstack/security/sanitizers.py", "src/taipanstack/se
248
250
  tests_dir = ["tests/test_property_sanitizers_operations.py", "tests/test_security_validators_operations.py", "tests/test_security_guards_operations.py", "tests/test_security_ssrf_operations.py", "tests/test_utils_retry_operations.py", "tests/test_utils_circuit_breaker_operations.py"]
249
251
  also_copy = ["src/"]
250
252
  runner = "python -m pytest -x -q --tb=no --timeout=10 --no-cov"
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.5.3"
8
+ __version__ = "0.6.0"
9
9
 
10
10
  from taipanstack.config.version_config import (
11
11
  VersionRecommendations,
@@ -13,7 +13,9 @@ from typing import TYPE_CHECKING
13
13
 
14
14
  if TYPE_CHECKING:
15
15
  import redis.asyncio as aioredis
16
+ from sqlalchemy.engine import Result as SQLAlchemyResult
16
17
  from sqlalchemy.ext.asyncio import AsyncEngine
18
+ from sqlalchemy.sql.executable import Executable
17
19
 
18
20
  from taipanstack.core.result import Err, Ok, Result
19
21
  from taipanstack.resilience.circuit_breaker import (
@@ -95,6 +97,23 @@ class ResilientDatabase:
95
97
  self._circuit_breaker = circuit_breaker
96
98
  self._retry_config = retry_config
97
99
 
100
+ def _check_db_dependencies(self) -> Result[None, Exception]:
101
+ if not _HAS_SQLALCHEMY:
102
+ return Err(
103
+ ImportError(
104
+ "sqlalchemy is required for ResilientDatabase. "
105
+ "Install with: pip install taipanstack[bridges-db]",
106
+ ),
107
+ )
108
+ return Ok(None)
109
+
110
+ def _check_breaker_gate(self) -> Result[None, Exception]:
111
+ if self._circuit_breaker is not None:
112
+ cb_err = _breaker_is_open(self._circuit_breaker)
113
+ if cb_err is not None:
114
+ return Err(cb_err)
115
+ return Ok(None)
116
+
98
117
  async def _handle_attempt_failure(
99
118
  self,
100
119
  exc: Exception,
@@ -125,33 +144,62 @@ class ResilientDatabase:
125
144
  return True
126
145
  return False
127
146
 
147
+ async def _execute_single_attempt(
148
+ self,
149
+ statement: Executable,
150
+ **kwargs: object,
151
+ ) -> Result[SQLAlchemyResult[object], Exception]:
152
+ try:
153
+ async with AsyncSession(self._engine) as session:
154
+ result = await session.execute(statement, **kwargs)
155
+ return Ok(result)
156
+ except Exception as exc:
157
+ return Err(exc)
158
+
159
+ async def _process_attempt(
160
+ self,
161
+ statement: Executable,
162
+ attempt: int,
163
+ max_attempts: int,
164
+ **kwargs: object,
165
+ ) -> Result[SQLAlchemyResult[object], Exception] | tuple[bool, Exception]:
166
+ result = await self._execute_single_attempt(statement, **kwargs)
167
+ if isinstance(result, Ok):
168
+ return result
169
+
170
+ last_error = result.err_value
171
+ should_continue = await self._handle_attempt_failure(
172
+ last_error, attempt, max_attempts
173
+ )
174
+ return should_continue, last_error
175
+
128
176
  async def _execute_loop(
129
177
  self,
130
- statement: object,
178
+ statement: Executable,
131
179
  max_attempts: int,
132
180
  **kwargs: object,
133
- ) -> Result[object, Exception]:
181
+ ) -> Result[SQLAlchemyResult[object], Exception]:
134
182
  """Execute the retry loop for database operations."""
135
- last_error: Exception | None = None
183
+ last_error: Exception = RuntimeError("Database execute failed")
136
184
 
137
185
  for attempt in range(1, max_attempts + 1):
138
- try:
139
- async with AsyncSession(self._engine) as session:
140
- result = await session.execute(statement, **kwargs)
141
- return Ok(result)
142
- except Exception as exc:
143
- last_error = exc
144
- if await self._handle_attempt_failure(exc, attempt, max_attempts):
145
- continue
186
+ outcome = await self._process_attempt(
187
+ statement, attempt, max_attempts, **kwargs
188
+ )
189
+ if not isinstance(outcome, tuple):
190
+ return outcome
191
+
192
+ should_continue, last_error = outcome
193
+ if not should_continue:
146
194
  break
147
195
 
148
- return Err(last_error or RuntimeError("Database execute failed"))
196
+ return Err(last_error)
149
197
 
150
198
  async def execute(
151
199
  self,
152
- statement: object,
200
+ statement: Executable,
153
201
  **kwargs: object,
154
- ) -> Result[object, Exception]:
202
+ ) -> Result[SQLAlchemyResult[object], Exception]:
155
203
  """Execute a SQL statement with resilience.
156
204
 
157
205
  Args:
@@ -162,19 +210,13 @@ class ResilientDatabase:
162
210
  ``Ok(result)`` on success, ``Err`` on failure.
163
211
 
164
212
  """
165
- if not _HAS_SQLALCHEMY:
166
- return Err(
167
- ImportError(
168
- "sqlalchemy is required for ResilientDatabase. "
169
- "Install with: pip install taipanstack[bridges-db]",
170
- ),
171
- )
213
+ dep_result = self._check_db_dependencies()
214
+ if isinstance(dep_result, Err):
215
+ return dep_result
172
216
 
173
- # Circuit breaker gate
174
- if self._circuit_breaker is not None:
175
- cb_err = _breaker_is_open(self._circuit_breaker)
176
- if cb_err is not None:
177
- return Err(cb_err)
217
+ cb_result = self._check_breaker_gate()
218
+ if isinstance(cb_result, Err):
219
+ return cb_result
178
220
 
179
221
  max_attempts = 1
180
222
  if self._retry_config is not None:
@@ -248,6 +290,21 @@ class ResilientRedis:
248
290
  return Err(cb_err)
249
291
  return Ok(None)
250
292
 
293
+ async def _execute_command(
294
+ self,
295
+ command: str,
296
+ *args: object,
297
+ ) -> Result[object, Exception]:
298
+ try:
299
+ fn = getattr(self._client, command.lower())
300
+ result = await fn(*args)
301
+ return Ok(result)
302
+ except Exception as exc:
303
+ logger.warning("Redis command '%s' failed: %s", command, exc)
304
+ if self._circuit_breaker is not None:
305
+ self._circuit_breaker._record_failure(exc)
306
+ return Err(exc)
307
+
251
308
  async def execute(
252
309
  self,
253
310
  command: str,
@@ -271,15 +328,7 @@ class ResilientRedis:
271
328
  if isinstance(cb_result, Err):
272
329
  return cb_result
273
330
 
274
- try:
275
- fn = getattr(self._client, command.lower())
276
- result = await fn(*args)
277
- return Ok(result)
278
- except Exception as exc:
279
- logger.warning("Redis command '%s' failed: %s", command, exc)
280
- if self._circuit_breaker is not None:
281
- self._circuit_breaker._record_failure(exc)
282
- return Err(exc)
331
+ return await self._execute_command(command, *args)
283
332
 
284
333
  async def health_check(self) -> Result[bool, Exception]:
285
334
  """Check Redis connectivity via PING.
@@ -11,10 +11,14 @@ from __future__ import annotations
11
11
  import asyncio
12
12
  import logging
13
13
  from collections.abc import Awaitable, Callable, Mapping, Sequence
14
- from typing import TYPE_CHECKING, cast
14
+ from typing import TYPE_CHECKING, TypeAlias, cast
15
15
 
16
16
  from typing_extensions import TypedDict, Unpack
17
17
 
18
+ if TYPE_CHECKING:
19
+ import httpx
20
+
21
+
18
22
  from taipanstack.core.result import Err, Ok, Result
19
23
  from taipanstack.resilience.circuit_breaker import (
20
24
  CircuitBreaker,
@@ -26,6 +30,10 @@ from taipanstack.security.guards import guard_ssrf
26
30
  logger = logging.getLogger("taipanstack.bridges.http")
27
31
 
28
32
 
33
+ # JsonType definition for robust typing
34
+ JsonType: TypeAlias = dict[str, object] | list[object] | str | int | float | bool | None
35
+
36
+
29
37
  class HttpRequestKwargs(TypedDict, total=False):
30
38
  """Type definitions for HTTP request kwargs."""
31
39
 
@@ -38,7 +46,7 @@ class HttpRequestKwargs(TypedDict, total=False):
38
46
  | None
39
47
  )
40
48
  files: dict[str, bytes | tuple[str, bytes]]
41
- json: dict[str, object] | list[object] | str | int | float | bool | None
49
+ json: JsonType
42
50
  params: (
43
51
  dict[
44
52
  str,
@@ -70,7 +78,7 @@ class HttpClientKwargs(TypedDict, total=False):
70
78
  mounts: Mapping[str, httpx.AsyncBaseTransport | None]
71
79
  follow_redirects: bool
72
80
  max_redirects: int
73
- event_hooks: dict[str, list[Callable[..., object]]]
81
+ event_hooks: dict[str, list[Callable[..., Awaitable[object]]]]
74
82
  trust_env: bool
75
83
  default_encoding: str | Callable[[bytes], str]
76
84
 
@@ -241,6 +249,24 @@ async def _execute_with_retries(
241
249
  return Err(last_error)
242
250
 
243
251
 
252
+ def _check_preconditions(
253
+ url: str,
254
+ ssrf_protection: bool,
255
+ circuit_breaker: CircuitBreaker | None,
256
+ ) -> Err[Exception] | None:
257
+ """Check SSRF and circuit breaker preconditions."""
258
+ ssrf_check = _check_ssrf(url, ssrf_protection)
259
+ if isinstance(ssrf_check, Err):
260
+ return ssrf_check
261
+
262
+ if circuit_breaker is not None:
263
+ cb_err: Exception | None = _check_circuit_breaker(circuit_breaker)
264
+ if cb_err is not None:
265
+ return Err(cb_err)
266
+
267
+ return None
268
+
269
+
244
270
  async def safe_request(
245
271
  method: str,
246
272
  url: str,
@@ -276,16 +302,9 @@ async def safe_request(
276
302
  ),
277
303
  )
278
304
 
279
- # SSRF check
280
- ssrf_check = _check_ssrf(url, ssrf_protection)
281
- if isinstance(ssrf_check, Err):
282
- return ssrf_check
283
-
284
- # Circuit breaker gate
285
- if circuit_breaker is not None:
286
- cb_err = _check_circuit_breaker(circuit_breaker)
287
- if cb_err is not None:
288
- return Err(cb_err)
305
+ precondition_err = _check_preconditions(url, ssrf_protection, circuit_breaker)
306
+ if precondition_err is not None:
307
+ return precondition_err
289
308
 
290
309
  async def _do_request() -> httpx.Response:
291
310
  async with httpx.AsyncClient(timeout=timeout) as client: # nosemgrep
@@ -396,16 +415,11 @@ class SafeHttpClient:
396
415
  if self._client is None:
397
416
  return Err(RuntimeError("Client not initialised. Use 'async with'."))
398
417
 
399
- # SSRF check
400
- ssrf_check = _check_ssrf(url, self._ssrf_protection)
401
- if isinstance(ssrf_check, Err):
402
- return ssrf_check
403
-
404
- # Circuit breaker gate
405
- if self._circuit_breaker is not None:
406
- cb_err = _check_circuit_breaker(self._circuit_breaker)
407
- if cb_err is not None:
408
- return Err(cb_err)
418
+ precondition_err = _check_preconditions(
419
+ url, self._ssrf_protection, self._circuit_breaker
420
+ )
421
+ if precondition_err is not None:
422
+ return precondition_err
409
423
 
410
424
  async def _do_request() -> httpx.Response:
411
425
  # We explicitly verified client is not None above
@@ -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 TypeAlias, TypeVar
15
+ from typing import Literal, TypeAlias, TypeVar
16
16
 
17
17
  from taipanstack.core.result import Ok, Result
18
18
  from taipanstack.utils.rate_limit import RateLimiter
@@ -42,11 +42,23 @@ class SecurityHeadersConfig:
42
42
 
43
43
  """
44
44
 
45
- x_content_type_options: str = "nosniff"
46
- x_frame_options: str = "DENY"
47
- x_xss_protection: str = "1; mode=block"
45
+ x_content_type_options: Literal["nosniff"] | str = "nosniff"
46
+ x_frame_options: Literal["DENY", "SAMEORIGIN"] | str = "DENY"
47
+ x_xss_protection: Literal["1; mode=block", "0"] | str = "1; mode=block"
48
48
  strict_transport_security: str = "max-age=31536000; includeSubDomains"
49
- referrer_policy: str = "strict-origin-when-cross-origin"
49
+ referrer_policy: (
50
+ Literal[
51
+ "no-referrer",
52
+ "no-referrer-when-downgrade",
53
+ "origin",
54
+ "origin-when-cross-origin",
55
+ "same-origin",
56
+ "strict-origin",
57
+ "strict-origin-when-cross-origin",
58
+ "unsafe-url",
59
+ ]
60
+ | str
61
+ ) = "strict-origin-when-cross-origin"
50
62
  content_security_policy: str = "default-src 'self'"
51
63
 
52
64
  def to_headers(self) -> list[tuple[bytes, bytes]]:
@@ -193,7 +205,7 @@ class TaipanMiddleware:
193
205
  async def send_with_headers(message: MutableMapping[str, object]) -> None:
194
206
  if message.get("type") == "http.response.start":
195
207
  headers = message.get("headers")
196
- existing = list(headers) if isinstance(headers, list) else []
208
+ existing = list(headers) if isinstance(headers, (list, tuple)) else []
197
209
  existing.extend(extra_headers)
198
210
  message["headers"] = existing
199
211
  await send(message)
@@ -242,14 +242,14 @@ def _generate_paranoid_hooks() -> str:
242
242
  """
243
243
 
244
244
 
245
- def generate_pre_commit_config(config: StackConfig) -> str:
246
- """Generate .pre-commit-config.yaml content.
245
+ def _collect_security_hooks(config: StackConfig) -> list[str]:
246
+ """Collect security hooks based on configuration.
247
247
 
248
248
  Args:
249
249
  config: The Stack configuration.
250
250
 
251
251
  Returns:
252
- Pre-commit configuration YAML string.
252
+ A list of security hook YAML strings.
253
253
 
254
254
  """
255
255
  security_hooks: list[str] = []
@@ -270,6 +270,21 @@ def generate_pre_commit_config(config: StackConfig) -> str:
270
270
  if config.security.level == "paranoid":
271
271
  security_hooks.append(_generate_paranoid_hooks())
272
272
 
273
+ return security_hooks
274
+
275
+
276
+ def generate_pre_commit_config(config: StackConfig) -> str:
277
+ """Generate .pre-commit-config.yaml content.
278
+
279
+ Args:
280
+ config: The Stack configuration.
281
+
282
+ Returns:
283
+ Pre-commit configuration YAML string.
284
+
285
+ """
286
+ security_hooks = _collect_security_hooks(config)
287
+
273
288
  return f"""# Stack v2.0 Pre-commit Configuration
274
289
  # Security Level: {config.security.level}
275
290
  repos: