taipanstack 0.6.0__tar.gz → 0.6.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {taipanstack-0.6.0 → taipanstack-0.6.1}/PKG-INFO +10 -8
- {taipanstack-0.6.0 → taipanstack-0.6.1}/README.md +9 -7
- {taipanstack-0.6.0 → taipanstack-0.6.1}/pyproject.toml +1 -1
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/__init__.py +1 -1
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/bridges/web_bridge.py +13 -16
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/config/generators.py +33 -12
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/config/models.py +23 -15
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/core/compat.py +28 -9
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/core/optimizations.py +29 -8
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/resilience/adaptive/orchestrator.py +1 -12
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/resilience/retry.py +8 -4
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/resilience/watchdogs/config_watcher.py +16 -7
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/security/guards.py +0 -13
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/security/jwt.py +6 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/security/models.py +16 -15
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/security/password.py +8 -4
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/security/sanitizers.py +19 -12
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/security/types.py +0 -4
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/security/validators.py +25 -6
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/utils/filesystem.py +23 -6
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/utils/rate_limit.py +54 -16
- {taipanstack-0.6.0 → taipanstack-0.6.1}/LICENSE +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/bridges/__init__.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/bridges/_imports.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/bridges/db_bridge.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/bridges/http_bridge.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/config/__init__.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/config/version_config.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/core/__init__.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/core/result.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/resilience/__init__.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/resilience/adaptive/__init__.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/resilience/adaptive/adaptive_breaker.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/resilience/adaptive/adaptive_retry.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/resilience/adaptive/bulkhead.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/resilience/circuit_breaker.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/resilience/resilience.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/resilience/watchdogs/__init__.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/resilience/watchdogs/_base.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/resilience/watchdogs/health_pinger.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/resilience/watchdogs/resource_watcher.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/security/__init__.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/security/decorators.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/utils/__init__.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/utils/cache.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/utils/circuit_breaker.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/utils/concurrency.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/utils/context.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/utils/logging.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/utils/resilience.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/utils/retry.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/utils/serialization.py +0 -0
- {taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/utils/subprocess.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: taipanstack
|
|
3
|
-
Version: 0.6.
|
|
3
|
+
Version: 0.6.1
|
|
4
4
|
Summary: TaipanStack - Modular, secure, and scalable Python stack for robust development
|
|
5
5
|
License-Expression: MIT
|
|
6
6
|
License-File: LICENSE
|
|
@@ -89,11 +89,11 @@ Description-Content-Type: text/markdown
|
|
|
89
89
|
|
|
90
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.
|
|
91
91
|
|
|
92
|
-
### ✨ What's New in v0.6.
|
|
93
|
-
- **Security & Hardening**: Hardened
|
|
94
|
-
- **
|
|
95
|
-
- **
|
|
96
|
-
- **QA and Standardized Testing**:
|
|
92
|
+
### ✨ What's New in v0.6.1
|
|
93
|
+
- **Security & Hardening**: Hardened RateLimiter against infinite tokens mutations, key decoding in JWT, and validate_project_name argument parsing. Fixed large password payload crashes and removed unused constants (PR #966, #967, #968, #973, #989).
|
|
94
|
+
- **Concurrency & Resilience**: Fixed a bulkhead acquisition memory leak in ResilienceOrchestrator and documented AdaptiveRetry features (PR #974, #980).
|
|
95
|
+
- **Clean Code & Refactoring**: Significantly reduced cyclomatic complexity across compatibility shims, validators, filesystems, and token buckets. Enforced strict web bridge type hints and clean keyword parameters (PR #971, #976, #979, #984, #988, #993, #997, #1002, #1003).
|
|
96
|
+
- **QA and Standardized Testing**: Fully standardized test file nomenclature, verified **1,460+ passing tests** with 100% genuine branch coverage, and added rigorous microservice chaos engineering simulations (PR #972, #975, #981, #986, #990, #992, #994, #999, #1004).
|
|
97
97
|
|
|
98
98
|
<table>
|
|
99
99
|
<tr>
|
|
@@ -221,10 +221,12 @@ TaipanStack/
|
|
|
221
221
|
├── src/
|
|
222
222
|
│ ├── app/ # Application entry point
|
|
223
223
|
│ └── taipanstack/
|
|
224
|
-
│ ├──
|
|
224
|
+
│ ├── bridges/ # 🌉 External communication integrations (http, db, web)
|
|
225
225
|
│ ├── config/ # ⚙️ Configuration models & generators
|
|
226
|
+
│ ├── core/ # 🎯 Result types, functional patterns
|
|
227
|
+
│ ├── resilience/ # 🌊 Reliability patterns (circuit breakers, retries, watchdogs)
|
|
226
228
|
│ ├── security/ # 🛡️ Guards, sanitizers, validators
|
|
227
|
-
│ └── utils/ # 🔧
|
|
229
|
+
│ └── utils/ # 🔧 Cross-cutting utilities (logging, cache, filesystem)
|
|
228
230
|
├── tests/ # ✅ 1,430 tests, 100% coverage
|
|
229
231
|
├── .semgrep/ # 🔍 Custom SAST rules
|
|
230
232
|
├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
|
|
@@ -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.6.
|
|
35
|
-
- **Security & Hardening**: Hardened
|
|
36
|
-
- **
|
|
37
|
-
- **
|
|
38
|
-
- **QA and Standardized Testing**:
|
|
34
|
+
### ✨ What's New in v0.6.1
|
|
35
|
+
- **Security & Hardening**: Hardened RateLimiter against infinite tokens mutations, key decoding in JWT, and validate_project_name argument parsing. Fixed large password payload crashes and removed unused constants (PR #966, #967, #968, #973, #989).
|
|
36
|
+
- **Concurrency & Resilience**: Fixed a bulkhead acquisition memory leak in ResilienceOrchestrator and documented AdaptiveRetry features (PR #974, #980).
|
|
37
|
+
- **Clean Code & Refactoring**: Significantly reduced cyclomatic complexity across compatibility shims, validators, filesystems, and token buckets. Enforced strict web bridge type hints and clean keyword parameters (PR #971, #976, #979, #984, #988, #993, #997, #1002, #1003).
|
|
38
|
+
- **QA and Standardized Testing**: Fully standardized test file nomenclature, verified **1,460+ passing tests** with 100% genuine branch coverage, and added rigorous microservice chaos engineering simulations (PR #972, #975, #981, #986, #990, #992, #994, #999, #1004).
|
|
39
39
|
|
|
40
40
|
<table>
|
|
41
41
|
<tr>
|
|
@@ -163,10 +163,12 @@ TaipanStack/
|
|
|
163
163
|
├── src/
|
|
164
164
|
│ ├── app/ # Application entry point
|
|
165
165
|
│ └── taipanstack/
|
|
166
|
-
│ ├──
|
|
166
|
+
│ ├── bridges/ # 🌉 External communication integrations (http, db, web)
|
|
167
167
|
│ ├── config/ # ⚙️ Configuration models & generators
|
|
168
|
+
│ ├── core/ # 🎯 Result types, functional patterns
|
|
169
|
+
│ ├── resilience/ # 🌊 Reliability patterns (circuit breakers, retries, watchdogs)
|
|
168
170
|
│ ├── security/ # 🛡️ Guards, sanitizers, validators
|
|
169
|
-
│ └── utils/ # 🔧
|
|
171
|
+
│ └── utils/ # 🔧 Cross-cutting utilities (logging, cache, filesystem)
|
|
170
172
|
├── tests/ # ✅ 1,430 tests, 100% coverage
|
|
171
173
|
├── .semgrep/ # 🔍 Custom SAST rules
|
|
172
174
|
├── .github/ # 🔄 CI/CD + SBOM/SLSA workflows
|
|
@@ -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.6.
|
|
8
|
+
__version__ = "0.6.1"
|
|
9
9
|
|
|
10
10
|
from taipanstack.config.version_config import (
|
|
11
11
|
VersionRecommendations,
|
|
@@ -42,23 +42,20 @@ class SecurityHeadersConfig:
|
|
|
42
42
|
|
|
43
43
|
"""
|
|
44
44
|
|
|
45
|
-
x_content_type_options: Literal["nosniff"]
|
|
46
|
-
x_frame_options: Literal["DENY", "SAMEORIGIN"]
|
|
47
|
-
x_xss_protection: Literal["1; mode=block", "0"]
|
|
45
|
+
x_content_type_options: Literal["nosniff"] = "nosniff"
|
|
46
|
+
x_frame_options: Literal["DENY", "SAMEORIGIN"] = "DENY"
|
|
47
|
+
x_xss_protection: Literal["1; mode=block", "0"] = "1; mode=block"
|
|
48
48
|
strict_transport_security: str = "max-age=31536000; includeSubDomains"
|
|
49
|
-
referrer_policy:
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
]
|
|
60
|
-
| str
|
|
61
|
-
) = "strict-origin-when-cross-origin"
|
|
49
|
+
referrer_policy: Literal[
|
|
50
|
+
"no-referrer",
|
|
51
|
+
"no-referrer-when-downgrade",
|
|
52
|
+
"origin",
|
|
53
|
+
"origin-when-cross-origin",
|
|
54
|
+
"same-origin",
|
|
55
|
+
"strict-origin",
|
|
56
|
+
"strict-origin-when-cross-origin",
|
|
57
|
+
"unsafe-url",
|
|
58
|
+
] = "strict-origin-when-cross-origin"
|
|
62
59
|
content_security_policy: str = "default-src 'self'"
|
|
63
60
|
|
|
64
61
|
def to_headers(self) -> list[tuple[bytes, bytes]]:
|
|
@@ -242,33 +242,54 @@ def _generate_paranoid_hooks() -> str:
|
|
|
242
242
|
"""
|
|
243
243
|
|
|
244
244
|
|
|
245
|
-
def
|
|
246
|
-
"""Collect security hooks
|
|
245
|
+
def _collect_standard_security_hooks(config: StackConfig, hooks: list[str]) -> None:
|
|
246
|
+
"""Collect standard security hooks.
|
|
247
247
|
|
|
248
248
|
Args:
|
|
249
249
|
config: The Stack configuration.
|
|
250
|
-
|
|
251
|
-
Returns:
|
|
252
|
-
A list of security hook YAML strings.
|
|
250
|
+
hooks: The list to append hooks to.
|
|
253
251
|
|
|
254
252
|
"""
|
|
255
|
-
security_hooks: list[str] = []
|
|
256
|
-
|
|
257
253
|
if config.security.enable_bandit:
|
|
258
|
-
|
|
254
|
+
hooks.append(_generate_bandit_hook(config.security.bandit_severity))
|
|
259
255
|
|
|
260
256
|
if config.security.enable_pip_audit:
|
|
261
|
-
|
|
257
|
+
hooks.append(_generate_pip_audit_hook())
|
|
262
258
|
|
|
263
259
|
if config.security.enable_semgrep:
|
|
264
|
-
|
|
260
|
+
hooks.append(_generate_semgrep_hook())
|
|
265
261
|
|
|
262
|
+
|
|
263
|
+
def _collect_additional_security_hooks(config: StackConfig, hooks: list[str]) -> None:
|
|
264
|
+
"""Collect additional security hooks based on configuration level.
|
|
265
|
+
|
|
266
|
+
Args:
|
|
267
|
+
config: The Stack configuration.
|
|
268
|
+
hooks: The list to append hooks to.
|
|
269
|
+
|
|
270
|
+
"""
|
|
266
271
|
if config.security.enable_detect_secrets:
|
|
267
|
-
|
|
272
|
+
hooks.append(_generate_detect_secrets_hook())
|
|
268
273
|
|
|
269
274
|
# Add extra hooks for paranoid mode
|
|
270
275
|
if config.security.level == "paranoid":
|
|
271
|
-
|
|
276
|
+
hooks.append(_generate_paranoid_hooks())
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _collect_security_hooks(config: StackConfig) -> list[str]:
|
|
280
|
+
"""Collect security hooks based on configuration.
|
|
281
|
+
|
|
282
|
+
Args:
|
|
283
|
+
config: The Stack configuration.
|
|
284
|
+
|
|
285
|
+
Returns:
|
|
286
|
+
A list of security hook YAML strings.
|
|
287
|
+
|
|
288
|
+
"""
|
|
289
|
+
security_hooks: list[str] = []
|
|
290
|
+
|
|
291
|
+
_collect_standard_security_hooks(config, security_hooks)
|
|
292
|
+
_collect_additional_security_hooks(config, security_hooks)
|
|
272
293
|
|
|
273
294
|
return security_hooks
|
|
274
295
|
|
|
@@ -23,6 +23,27 @@ PYTHON_MAJOR_VERSION = 3
|
|
|
23
23
|
MIN_PYTHON_MINOR_VERSION = 10
|
|
24
24
|
|
|
25
25
|
|
|
26
|
+
def _check_python_version_format(value: str) -> None:
|
|
27
|
+
"""Validate Python version matches the X.Y format."""
|
|
28
|
+
pattern = r"^\d+\.\d+\Z"
|
|
29
|
+
if not re.match(pattern, value):
|
|
30
|
+
msg = f"Python version '{value}' is invalid. Use format 'X.Y' (e.g., '3.12')."
|
|
31
|
+
raise ValueError(msg)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _check_python_minimum_version(major: int, minor: int, value: str) -> None:
|
|
35
|
+
"""Validate Python version meets the minimum supported requirement."""
|
|
36
|
+
is_old_python = major < PYTHON_MAJOR_VERSION or (
|
|
37
|
+
major == PYTHON_MAJOR_VERSION and minor < MIN_PYTHON_MINOR_VERSION
|
|
38
|
+
)
|
|
39
|
+
if is_old_python:
|
|
40
|
+
msg = (
|
|
41
|
+
f"Python version {value} is not supported. "
|
|
42
|
+
f"Minimum is {PYTHON_MAJOR_VERSION}.{MIN_PYTHON_MINOR_VERSION}."
|
|
43
|
+
)
|
|
44
|
+
raise ValueError(msg)
|
|
45
|
+
|
|
46
|
+
|
|
26
47
|
class SecurityConfig(BaseModel):
|
|
27
48
|
"""Security-related configuration options.
|
|
28
49
|
|
|
@@ -237,23 +258,10 @@ class StackConfig(BaseModel):
|
|
|
237
258
|
|
|
238
259
|
"""
|
|
239
260
|
_ = cls
|
|
240
|
-
|
|
241
|
-
if not re.match(pattern, value):
|
|
242
|
-
msg = (
|
|
243
|
-
f"Python version '{value}' is invalid. Use format 'X.Y' (e.g., '3.12')."
|
|
244
|
-
)
|
|
245
|
-
raise ValueError(msg)
|
|
261
|
+
_check_python_version_format(value)
|
|
246
262
|
|
|
247
263
|
major, minor = map(int, value.split("."))
|
|
248
|
-
|
|
249
|
-
major == PYTHON_MAJOR_VERSION and minor < MIN_PYTHON_MINOR_VERSION
|
|
250
|
-
)
|
|
251
|
-
if is_old_python:
|
|
252
|
-
msg = (
|
|
253
|
-
f"Python version {value} is not supported. "
|
|
254
|
-
f"Minimum is {PYTHON_MAJOR_VERSION}.{MIN_PYTHON_MINOR_VERSION}."
|
|
255
|
-
)
|
|
256
|
-
raise ValueError(msg)
|
|
264
|
+
_check_python_minimum_version(major, minor, value)
|
|
257
265
|
|
|
258
266
|
return value
|
|
259
267
|
|
|
@@ -93,22 +93,26 @@ def _check_jit_available() -> bool:
|
|
|
93
93
|
return False
|
|
94
94
|
|
|
95
95
|
|
|
96
|
-
def
|
|
97
|
-
"""Check if
|
|
96
|
+
def _check_nogil_flag() -> bool | None:
|
|
97
|
+
"""Check if nogil flag is present and enabled.
|
|
98
98
|
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
99
|
+
Returns:
|
|
100
|
+
True if the flag is present and True.
|
|
101
|
+
False if the flag is present and False.
|
|
102
|
+
None if the flag is not present.
|
|
103
103
|
|
|
104
|
+
"""
|
|
104
105
|
try:
|
|
105
|
-
# In free-threaded builds, sys.flags.nogil is True
|
|
106
|
-
# or the build was configured with --disable-gil
|
|
107
106
|
if hasattr(sys.flags, "nogil"):
|
|
108
107
|
return bool(sys.flags.nogil)
|
|
108
|
+
except (AttributeError, TypeError):
|
|
109
|
+
pass
|
|
110
|
+
return None
|
|
109
111
|
|
|
110
|
-
# Alternative check for 3.13+
|
|
111
112
|
|
|
113
|
+
def _check_disable_gil_config() -> bool:
|
|
114
|
+
"""Check if build was configured with --disable-gil."""
|
|
115
|
+
try:
|
|
112
116
|
config_args = sysconfig.get_config_var("CONFIG_ARGS") or ""
|
|
113
117
|
except (AttributeError, TypeError):
|
|
114
118
|
return False
|
|
@@ -116,6 +120,21 @@ def _check_free_threading_available() -> bool:
|
|
|
116
120
|
return "--disable-gil" in config_args
|
|
117
121
|
|
|
118
122
|
|
|
123
|
+
def _check_free_threading_available() -> bool:
|
|
124
|
+
"""Check if free-threading (no-GIL) build is being used.
|
|
125
|
+
|
|
126
|
+
Free-threading is available in Python 3.13+ experimental builds.
|
|
127
|
+
"""
|
|
128
|
+
if not PY313:
|
|
129
|
+
return False
|
|
130
|
+
|
|
131
|
+
nogil = _check_nogil_flag()
|
|
132
|
+
if nogil is not None:
|
|
133
|
+
return nogil
|
|
134
|
+
|
|
135
|
+
return _check_disable_gil_config()
|
|
136
|
+
|
|
137
|
+
|
|
119
138
|
def _check_mimalloc_available() -> bool:
|
|
120
139
|
"""Check if mimalloc allocator is being used.
|
|
121
140
|
|
|
@@ -206,6 +206,29 @@ def _build_aggressive_profile(profile: OptimizationProfile) -> OptimizationProfi
|
|
|
206
206
|
)
|
|
207
207
|
|
|
208
208
|
|
|
209
|
+
def _determine_optimization_profile(
|
|
210
|
+
opt_level: int,
|
|
211
|
+
experimental: bool,
|
|
212
|
+
base_profile: OptimizationProfile,
|
|
213
|
+
) -> OptimizationProfile:
|
|
214
|
+
"""Determine the optimization profile based on level and experimental flag.
|
|
215
|
+
|
|
216
|
+
Args:
|
|
217
|
+
opt_level: The configured optimization level.
|
|
218
|
+
experimental: Whether experimental features are enabled.
|
|
219
|
+
base_profile: The base profile for the current Python version.
|
|
220
|
+
|
|
221
|
+
Returns:
|
|
222
|
+
The resolved OptimizationProfile.
|
|
223
|
+
|
|
224
|
+
"""
|
|
225
|
+
if opt_level == OPT_LEVEL_NONE:
|
|
226
|
+
return _PROFILE_311
|
|
227
|
+
if opt_level == OPT_LEVEL_AGGRESSIVE and experimental:
|
|
228
|
+
return _build_aggressive_profile(base_profile)
|
|
229
|
+
return base_profile
|
|
230
|
+
|
|
231
|
+
|
|
209
232
|
def get_optimization_profile(*, force_refresh: bool = False) -> OptimizationProfile:
|
|
210
233
|
"""Get the optimization profile for the current Python version.
|
|
211
234
|
|
|
@@ -225,15 +248,13 @@ def get_optimization_profile(*, force_refresh: bool = False) -> OptimizationProf
|
|
|
225
248
|
experimental = is_experimental_enabled(force_refresh=force_refresh)
|
|
226
249
|
opt_level = get_optimization_level(force_refresh=force_refresh)
|
|
227
250
|
|
|
228
|
-
|
|
251
|
+
base_profile = _get_base_profile()
|
|
229
252
|
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
else:
|
|
236
|
-
_cached_optimization_profile = profile
|
|
253
|
+
_cached_optimization_profile = _determine_optimization_profile(
|
|
254
|
+
opt_level,
|
|
255
|
+
experimental,
|
|
256
|
+
base_profile,
|
|
257
|
+
)
|
|
237
258
|
|
|
238
259
|
return _cached_optimization_profile
|
|
239
260
|
|
|
@@ -167,18 +167,7 @@ class ResilienceOrchestrator(Generic[T]):
|
|
|
167
167
|
|
|
168
168
|
async def _acquire_bulkhead(self, bh: Bulkhead) -> Result[None, Exception]:
|
|
169
169
|
"""Attempt to acquire a bulkhead permit, handling timeouts and errors."""
|
|
170
|
-
|
|
171
|
-
await asyncio.wait_for(
|
|
172
|
-
bh._semaphore.acquire(),
|
|
173
|
-
timeout=bh._timeout,
|
|
174
|
-
)
|
|
175
|
-
return Ok(None)
|
|
176
|
-
except TimeoutError:
|
|
177
|
-
return Err(
|
|
178
|
-
TimeoutError(f"Bulkhead '{bh.name}' timed out after {bh._timeout}s")
|
|
179
|
-
)
|
|
180
|
-
except (RuntimeError, OSError, MemoryError) as e:
|
|
181
|
-
return Err(RuntimeError(f"Resource exhaustion: {e!s}"))
|
|
170
|
+
return await bh._acquire_permit()
|
|
182
171
|
|
|
183
172
|
async def _execute_with_bulkhead(
|
|
184
173
|
self,
|
|
@@ -630,16 +630,20 @@ class Retrier:
|
|
|
630
630
|
self.attempt += 1
|
|
631
631
|
return True
|
|
632
632
|
|
|
633
|
-
def
|
|
634
|
-
"""
|
|
633
|
+
def _is_matching_exception(self, exc_type: type[BaseException] | None) -> bool:
|
|
634
|
+
"""Check if the exception matches the types to retry on."""
|
|
635
635
|
if exc_type is None:
|
|
636
636
|
return False
|
|
637
637
|
try:
|
|
638
|
-
|
|
639
|
-
return False
|
|
638
|
+
return issubclass(exc_type, self.exception_types)
|
|
640
639
|
except TypeError:
|
|
641
640
|
return False
|
|
642
641
|
|
|
642
|
+
def _should_retry(self, exc_type: type[BaseException] | None) -> bool:
|
|
643
|
+
"""Determine if an exception should trigger a retry."""
|
|
644
|
+
if not self._is_matching_exception(exc_type):
|
|
645
|
+
return False
|
|
646
|
+
|
|
643
647
|
if not self._increment_attempt():
|
|
644
648
|
return False
|
|
645
649
|
|
{taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/resilience/watchdogs/config_watcher.py
RENAMED
|
@@ -44,6 +44,19 @@ def _hash_file(path: Path) -> Result[str, Exception]:
|
|
|
44
44
|
return Err(exc)
|
|
45
45
|
|
|
46
46
|
|
|
47
|
+
def _is_valid_env_line(line: str) -> bool:
|
|
48
|
+
"""Check if a line is a valid .env assignment."""
|
|
49
|
+
if not line or line.startswith("#"):
|
|
50
|
+
return False
|
|
51
|
+
return "=" in line
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _parse_env_line(line: str) -> tuple[str, str]:
|
|
55
|
+
"""Parse a valid .env assignment line into key and value."""
|
|
56
|
+
key, _, value = line.partition("=")
|
|
57
|
+
return key.strip(), value.strip().strip("\"'")
|
|
58
|
+
|
|
59
|
+
|
|
47
60
|
def _parse_env(text: str) -> dict[str, object]:
|
|
48
61
|
"""Parse a simple ``.env`` key=value file.
|
|
49
62
|
|
|
@@ -60,13 +73,9 @@ def _parse_env(text: str) -> dict[str, object]:
|
|
|
60
73
|
result: dict[str, object] = {}
|
|
61
74
|
for line in text.splitlines():
|
|
62
75
|
stripped = line.strip()
|
|
63
|
-
if
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
continue
|
|
67
|
-
key, _, value = stripped.partition("=")
|
|
68
|
-
value = value.strip().strip("\"'")
|
|
69
|
-
result[key.strip()] = value
|
|
76
|
+
if _is_valid_env_line(stripped):
|
|
77
|
+
key, value = _parse_env_line(stripped)
|
|
78
|
+
result[key] = value
|
|
70
79
|
return result
|
|
71
80
|
|
|
72
81
|
|
|
@@ -93,19 +93,6 @@ _SENSITIVE_ENV_VAR_PATTERN = re.compile(
|
|
|
93
93
|
r"SECRET|PASSWORD|TOKEN|PRIVATE.*?KEY|API.*?KEY",
|
|
94
94
|
)
|
|
95
95
|
|
|
96
|
-
_SAFE_HASH_ALGORITHMS = frozenset(
|
|
97
|
-
[
|
|
98
|
-
"sha256",
|
|
99
|
-
"sha384",
|
|
100
|
-
"sha512",
|
|
101
|
-
"sha3_256",
|
|
102
|
-
"sha3_384",
|
|
103
|
-
"sha3_512",
|
|
104
|
-
"blake2b",
|
|
105
|
-
"blake2s",
|
|
106
|
-
],
|
|
107
|
-
)
|
|
108
|
-
|
|
109
96
|
|
|
110
97
|
class SecurityError(Exception):
|
|
111
98
|
"""Raised when a security guard detects a violation.
|
|
@@ -54,6 +54,9 @@ def encode_jwt(
|
|
|
54
54
|
PyJWTError: If encoding fails.
|
|
55
55
|
|
|
56
56
|
"""
|
|
57
|
+
if not isinstance(secret_key, str):
|
|
58
|
+
raise TypeError("Secret must be a string")
|
|
59
|
+
|
|
57
60
|
if not isinstance(algorithm, str):
|
|
58
61
|
raise TypeError("Algorithm must be a string")
|
|
59
62
|
|
|
@@ -111,6 +114,9 @@ def decode_jwt(
|
|
|
111
114
|
PyJWTError: If the token is invalid, expired, or has incorrect claims.
|
|
112
115
|
|
|
113
116
|
"""
|
|
117
|
+
if not isinstance(secret_key, str):
|
|
118
|
+
raise TypeError("Secret must be a string")
|
|
119
|
+
|
|
114
120
|
_validate_jwt_algorithms(algorithms)
|
|
115
121
|
_validate_jwt_audience(audience)
|
|
116
122
|
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
import json
|
|
4
4
|
import re
|
|
5
5
|
from collections.abc import Callable, Iterator
|
|
6
|
-
from typing import TYPE_CHECKING, Literal, TypeAlias, cast
|
|
6
|
+
from typing import TYPE_CHECKING, Any, Literal, TypeAlias, cast
|
|
7
7
|
|
|
8
8
|
from pydantic import BaseModel, ConfigDict
|
|
9
9
|
|
|
@@ -25,15 +25,20 @@ _SENSITIVE_KEY_REGEX = (
|
|
|
25
25
|
_MAX_RECURSION_DEPTH = 100
|
|
26
26
|
|
|
27
27
|
|
|
28
|
+
def _is_sensitive_key(key: object) -> bool:
|
|
29
|
+
"""Check if a given key is considered sensitive."""
|
|
30
|
+
return (
|
|
31
|
+
isinstance(key, str)
|
|
32
|
+
and _SENSITIVE_KEY_REGEX is not None
|
|
33
|
+
and bool(_SENSITIVE_KEY_REGEX.search(key))
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
28
37
|
def _mask_dict(data: dict[str, object], depth: int) -> dict[str, object]:
|
|
29
38
|
"""Mask sensitive keys in a dictionary."""
|
|
30
39
|
masked: dict[str, object] = {}
|
|
31
40
|
for k, v in data.items():
|
|
32
|
-
if (
|
|
33
|
-
isinstance(k, str)
|
|
34
|
-
and _SENSITIVE_KEY_REGEX is not None
|
|
35
|
-
and _SENSITIVE_KEY_REGEX.search(k)
|
|
36
|
-
):
|
|
41
|
+
if _is_sensitive_key(k):
|
|
37
42
|
masked[k] = REDACTED_VALUE
|
|
38
43
|
else:
|
|
39
44
|
masked[k] = _mask_data(v, depth)
|
|
@@ -92,11 +97,7 @@ class SecureBaseModel(BaseModel):
|
|
|
92
97
|
def __repr_args__(self) -> Iterator[tuple[str | None, object]]:
|
|
93
98
|
"""Provide arguments for string representation, redacting sensitive fields."""
|
|
94
99
|
for k, v in super().__repr_args__():
|
|
95
|
-
if (
|
|
96
|
-
isinstance(k, str)
|
|
97
|
-
and _SENSITIVE_KEY_REGEX is not None
|
|
98
|
-
and _SENSITIVE_KEY_REGEX.search(k)
|
|
99
|
-
):
|
|
100
|
+
if _is_sensitive_key(k):
|
|
100
101
|
yield k, REDACTED_VALUE
|
|
101
102
|
else:
|
|
102
103
|
yield k, v
|
|
@@ -117,7 +118,7 @@ class SecureBaseModel(BaseModel):
|
|
|
117
118
|
warnings: bool | Literal["none", "warn", "error"] = True,
|
|
118
119
|
fallback: Callable[[object], object] | None = None,
|
|
119
120
|
serialize_as_any: bool = False,
|
|
120
|
-
**kwargs:
|
|
121
|
+
**kwargs: Any,
|
|
121
122
|
) -> dict[str, object]:
|
|
122
123
|
"""Dump the model to a dictionary, redacting sensitive fields.
|
|
123
124
|
|
|
@@ -139,7 +140,7 @@ class SecureBaseModel(BaseModel):
|
|
|
139
140
|
warnings=warnings,
|
|
140
141
|
fallback=fallback,
|
|
141
142
|
serialize_as_any=serialize_as_any,
|
|
142
|
-
**kwargs,
|
|
143
|
+
**kwargs,
|
|
143
144
|
)
|
|
144
145
|
return cast(dict[str, object], _mask_data(data))
|
|
145
146
|
|
|
@@ -160,7 +161,7 @@ class SecureBaseModel(BaseModel):
|
|
|
160
161
|
warnings: bool | Literal["none", "warn", "error"] = True,
|
|
161
162
|
fallback: Callable[[object], object] | None = None,
|
|
162
163
|
serialize_as_any: bool = False,
|
|
163
|
-
**kwargs:
|
|
164
|
+
**kwargs: Any,
|
|
164
165
|
) -> str:
|
|
165
166
|
"""Dump the model to a JSON string, redacting sensitive fields.
|
|
166
167
|
|
|
@@ -185,7 +186,7 @@ class SecureBaseModel(BaseModel):
|
|
|
185
186
|
warnings=warnings,
|
|
186
187
|
fallback=fallback,
|
|
187
188
|
serialize_as_any=serialize_as_any,
|
|
188
|
-
**kwargs,
|
|
189
|
+
**kwargs,
|
|
189
190
|
)
|
|
190
191
|
masked_dict = _mask_data(dumped_dict)
|
|
191
192
|
# We need to respect Pydantic's indent/separators if possible,
|
|
@@ -103,6 +103,13 @@ def _verify_argon2(password_str: str, password_hash: str) -> bool:
|
|
|
103
103
|
return False
|
|
104
104
|
|
|
105
105
|
|
|
106
|
+
def _is_valid_password_string(password_str: str) -> bool:
|
|
107
|
+
"""Validate a password string for emptiness and maximum length."""
|
|
108
|
+
if not password_str:
|
|
109
|
+
return False
|
|
110
|
+
return len(password_str) <= MAX_PASSWORD_LENGTH
|
|
111
|
+
|
|
112
|
+
|
|
106
113
|
def verify_password(password: str | SecretStr, password_hash: str) -> bool:
|
|
107
114
|
"""
|
|
108
115
|
Verify a password against an Argon2 or legacy PBKDF2-HMAC-SHA256 hash.
|
|
@@ -124,10 +131,7 @@ def verify_password(password: str | SecretStr, password_hash: str) -> bool:
|
|
|
124
131
|
msg = "password_hash must be a string" # type: ignore[unreachable]
|
|
125
132
|
raise TypeError(msg)
|
|
126
133
|
|
|
127
|
-
if not password_str:
|
|
128
|
-
return False
|
|
129
|
-
|
|
130
|
-
if len(password_str) > MAX_PASSWORD_LENGTH:
|
|
134
|
+
if not _is_valid_password_string(password_str):
|
|
131
135
|
return False
|
|
132
136
|
|
|
133
137
|
if password_hash.startswith(LEGACY_FORMAT + "$"):
|
|
@@ -20,9 +20,6 @@ _HTML_TAGS_RE = re.compile(r"<[^>]+>") # pragma: no mutate
|
|
|
20
20
|
_CONTROL_CHARS_RE = re.compile(
|
|
21
21
|
r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]",
|
|
22
22
|
) # pragma: no mutate
|
|
23
|
-
_VALID_SQL_PREFIX = frozenset(
|
|
24
|
-
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_",
|
|
25
|
-
) # pragma: no mutate
|
|
26
23
|
_WINDOWS_RESERVED_NAMES = frozenset( # pragma: no mutate
|
|
27
24
|
{
|
|
28
25
|
"CON",
|
|
@@ -396,6 +393,23 @@ def _apply_base_dir_constraint(
|
|
|
396
393
|
return sanitized
|
|
397
394
|
|
|
398
395
|
|
|
396
|
+
def _process_string_path(path: str) -> Path:
|
|
397
|
+
"""Process a string path, removing null bytes and validating length."""
|
|
398
|
+
if len(path) > MAX_PATH_LENGTH:
|
|
399
|
+
msg = "Path length exceeds maximum allowed"
|
|
400
|
+
raise ValueError(msg)
|
|
401
|
+
if "\x00" in path:
|
|
402
|
+
path = path.replace("\x00", "")
|
|
403
|
+
return Path(path)
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def _check_pathlike_length(path: os.PathLike[str]) -> None:
|
|
407
|
+
"""Check the length of a PathLike object."""
|
|
408
|
+
if len(str(path)) > MAX_PATH_LENGTH:
|
|
409
|
+
msg = "Path length exceeds maximum allowed"
|
|
410
|
+
raise ValueError(msg)
|
|
411
|
+
|
|
412
|
+
|
|
399
413
|
def _normalize_path_input(path: str | os.PathLike[str]) -> Path:
|
|
400
414
|
"""Normalize input path string or Path object."""
|
|
401
415
|
if not isinstance(path, (str, os.PathLike)):
|
|
@@ -404,16 +418,9 @@ def _normalize_path_input(path: str | os.PathLike[str]) -> Path:
|
|
|
404
418
|
)
|
|
405
419
|
|
|
406
420
|
if isinstance(path, str):
|
|
407
|
-
|
|
408
|
-
msg = "Path length exceeds maximum allowed"
|
|
409
|
-
raise ValueError(msg)
|
|
410
|
-
if "\x00" in path:
|
|
411
|
-
path = path.replace("\x00", "")
|
|
412
|
-
return Path(path)
|
|
421
|
+
return _process_string_path(path)
|
|
413
422
|
|
|
414
|
-
|
|
415
|
-
msg = "Path length exceeds maximum allowed"
|
|
416
|
-
raise ValueError(msg)
|
|
423
|
+
_check_pathlike_length(path)
|
|
417
424
|
return Path(path)
|
|
418
425
|
|
|
419
426
|
|
|
@@ -7,7 +7,6 @@ declarative, type-safe input validation inside ``BaseModel``
|
|
|
7
7
|
definitions.
|
|
8
8
|
"""
|
|
9
9
|
|
|
10
|
-
import re
|
|
11
10
|
from typing import Annotated
|
|
12
11
|
|
|
13
12
|
from pydantic.functional_validators import AfterValidator
|
|
@@ -131,6 +130,3 @@ SafeCommand = Annotated[str, AfterValidator(_validate_safe_command)]
|
|
|
131
130
|
|
|
132
131
|
SafeProjectName = Annotated[str, AfterValidator(_validate_safe_project_name)]
|
|
133
132
|
"""A project name validated for safe naming conventions."""
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
_SQL_IDENTIFIER_REGEX = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*\Z")
|
|
@@ -37,6 +37,13 @@ PROJECT_NAME_RESERVED = frozenset(
|
|
|
37
37
|
)
|
|
38
38
|
|
|
39
39
|
|
|
40
|
+
def _get_type_name(expected_type: type | tuple[type, ...]) -> str:
|
|
41
|
+
"""Get the string representation of expected type(s)."""
|
|
42
|
+
if isinstance(expected_type, type):
|
|
43
|
+
return expected_type.__name__
|
|
44
|
+
return " | ".join(t.__name__ for t in expected_type)
|
|
45
|
+
|
|
46
|
+
|
|
40
47
|
def _validate_type(
|
|
41
48
|
value: object,
|
|
42
49
|
expected_type: type | tuple[type, ...],
|
|
@@ -53,12 +60,12 @@ def _validate_type(
|
|
|
53
60
|
TypeError: If value is not of the expected type.
|
|
54
61
|
|
|
55
62
|
"""
|
|
63
|
+
# Explicitly reject bools if expecting an int (but not if expecting bool)
|
|
64
|
+
if expected_type is int and isinstance(value, bool):
|
|
65
|
+
raise TypeError(f"{name} must be int, got bool")
|
|
66
|
+
|
|
56
67
|
if not isinstance(value, expected_type):
|
|
57
|
-
type_name = (
|
|
58
|
-
expected_type.__name__
|
|
59
|
-
if isinstance(expected_type, type)
|
|
60
|
-
else " | ".join(t.__name__ for t in expected_type)
|
|
61
|
-
)
|
|
68
|
+
type_name = _get_type_name(expected_type)
|
|
62
69
|
msg = f"{name} must be {type_name}, got {type(value).__name__}"
|
|
63
70
|
raise TypeError(msg)
|
|
64
71
|
|
|
@@ -173,6 +180,9 @@ def validate_project_name(
|
|
|
173
180
|
|
|
174
181
|
"""
|
|
175
182
|
_validate_type(name, str, "Project name")
|
|
183
|
+
_validate_type(max_length, int, "max_length")
|
|
184
|
+
_validate_type(allow_hyphen, bool, "allow_hyphen")
|
|
185
|
+
_validate_type(allow_underscore, bool, "allow_underscore")
|
|
176
186
|
_check_project_name_length(name, max_length)
|
|
177
187
|
_check_project_name_chars(name, allow_hyphen, allow_underscore)
|
|
178
188
|
_check_project_name_reserved(name)
|
|
@@ -180,7 +190,7 @@ def validate_project_name(
|
|
|
180
190
|
return name
|
|
181
191
|
|
|
182
192
|
|
|
183
|
-
def
|
|
193
|
+
def _check_version_string_safety(version: str) -> None:
|
|
184
194
|
"""Check the basic formatting and safety of a version string."""
|
|
185
195
|
# Prevent DoS from massive integer string conversion limit in Python
|
|
186
196
|
if len(version) > MAX_PYTHON_VERSION_LENGTH:
|
|
@@ -191,6 +201,9 @@ def _check_version_format(version: str) -> None:
|
|
|
191
201
|
msg = "Version contains invalid characters"
|
|
192
202
|
raise ValueError(msg)
|
|
193
203
|
|
|
204
|
+
|
|
205
|
+
def _check_version_regex_pattern(version: str) -> None:
|
|
206
|
+
"""Check the regex pattern of a version string."""
|
|
194
207
|
if not version.isascii():
|
|
195
208
|
msg = f"Invalid version format: '{version}'. Use 'X.Y' format (e.g., '3.12')"
|
|
196
209
|
raise ValueError(msg)
|
|
@@ -202,6 +215,12 @@ def _check_version_format(version: str) -> None:
|
|
|
202
215
|
raise ValueError(msg)
|
|
203
216
|
|
|
204
217
|
|
|
218
|
+
def _check_version_format(version: str) -> None:
|
|
219
|
+
"""Check the basic formatting and safety of a version string."""
|
|
220
|
+
_check_version_string_safety(version)
|
|
221
|
+
_check_version_regex_pattern(version)
|
|
222
|
+
|
|
223
|
+
|
|
205
224
|
def _check_version_numbers(version: str) -> None:
|
|
206
225
|
"""Check the major and minor version numbers."""
|
|
207
226
|
try:
|
|
@@ -317,7 +317,28 @@ def ensure_dir(
|
|
|
317
317
|
path = _validate_path(path, base_dir, allow_symlinks=True)
|
|
318
318
|
resolved_path = path.resolve()
|
|
319
319
|
|
|
320
|
-
|
|
320
|
+
paths_to_create = _get_missing_parents(resolved_path)
|
|
321
|
+
|
|
322
|
+
# Iterate through parents and create them with specific mode
|
|
323
|
+
for p in paths_to_create:
|
|
324
|
+
p.mkdir(mode=mode, exist_ok=True)
|
|
325
|
+
|
|
326
|
+
return resolved_path
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def _get_missing_parents(resolved_path: Path) -> list[Path]:
|
|
330
|
+
"""Identify missing parent directories from root to leaf.
|
|
331
|
+
|
|
332
|
+
Args:
|
|
333
|
+
resolved_path: The fully resolved path to check.
|
|
334
|
+
|
|
335
|
+
Returns:
|
|
336
|
+
List of paths to create in order from root to leaf.
|
|
337
|
+
|
|
338
|
+
Raises:
|
|
339
|
+
FileExistsError: If a file exists in the path that is not a directory.
|
|
340
|
+
|
|
341
|
+
"""
|
|
321
342
|
paths_to_create: list[Path] = []
|
|
322
343
|
current_path = resolved_path
|
|
323
344
|
|
|
@@ -330,8 +351,4 @@ def ensure_dir(
|
|
|
330
351
|
break
|
|
331
352
|
current_path = parent
|
|
332
353
|
|
|
333
|
-
|
|
334
|
-
for p in paths_to_create:
|
|
335
|
-
p.mkdir(mode=mode, exist_ok=True)
|
|
336
|
-
|
|
337
|
-
return resolved_path
|
|
354
|
+
return paths_to_create
|
|
@@ -39,6 +39,13 @@ class RateLimitError(Exception):
|
|
|
39
39
|
class RateLimiter:
|
|
40
40
|
"""Token bucket rate limiter logic."""
|
|
41
41
|
|
|
42
|
+
def _validate_init_params(self, max_calls: int, time_window: float) -> None:
|
|
43
|
+
"""Validate initialization parameters."""
|
|
44
|
+
if not math.isfinite(max_calls) or not math.isfinite(time_window):
|
|
45
|
+
raise ValueError("max_calls and time_window must be finite numbers")
|
|
46
|
+
if max_calls <= 0 or time_window <= 0:
|
|
47
|
+
raise ValueError("max_calls and time_window must be > 0.0")
|
|
48
|
+
|
|
42
49
|
def __init__(self, max_calls: int, time_window: float) -> None:
|
|
43
50
|
"""Initialize the token bucket.
|
|
44
51
|
|
|
@@ -47,10 +54,7 @@ class RateLimiter:
|
|
|
47
54
|
time_window: The time window in seconds.
|
|
48
55
|
|
|
49
56
|
"""
|
|
50
|
-
|
|
51
|
-
raise ValueError("max_calls and time_window must be finite numbers")
|
|
52
|
-
if max_calls <= 0 or time_window <= 0:
|
|
53
|
-
raise ValueError("max_calls and time_window must be > 0.0")
|
|
57
|
+
self._validate_init_params(max_calls, time_window)
|
|
54
58
|
self.capacity: float = float(max_calls)
|
|
55
59
|
self.time_window: float = float(time_window)
|
|
56
60
|
self.tokens: float = self.capacity
|
|
@@ -93,6 +97,15 @@ class RateLimiter:
|
|
|
93
97
|
self.tokens = min(self.tokens, self.capacity)
|
|
94
98
|
return True
|
|
95
99
|
|
|
100
|
+
def _calculate_elapsed(self, now: float) -> float | None:
|
|
101
|
+
"""Calculate the elapsed time since the last update."""
|
|
102
|
+
if not isinstance(self.last_update, (int, float)):
|
|
103
|
+
return None # type: ignore[unreachable]
|
|
104
|
+
raw_elapsed = now - self.last_update
|
|
105
|
+
if not math.isfinite(raw_elapsed):
|
|
106
|
+
return None
|
|
107
|
+
return max(0.0, raw_elapsed)
|
|
108
|
+
|
|
96
109
|
def _add_tokens(self, now: float) -> bool:
|
|
97
110
|
"""Calculate and add new tokens to the bucket based on elapsed time.
|
|
98
111
|
|
|
@@ -103,12 +116,10 @@ class RateLimiter:
|
|
|
103
116
|
True if token update succeeds, False if state corruption is detected.
|
|
104
117
|
|
|
105
118
|
"""
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
raw_elapsed = now - self.last_update
|
|
109
|
-
if not math.isfinite(raw_elapsed):
|
|
119
|
+
elapsed = self._calculate_elapsed(now)
|
|
120
|
+
if elapsed is None:
|
|
110
121
|
return False
|
|
111
|
-
|
|
122
|
+
|
|
112
123
|
self.last_update = now
|
|
113
124
|
|
|
114
125
|
# Prevent state corruption or infinite elapsed time
|
|
@@ -125,27 +136,54 @@ class RateLimiter:
|
|
|
125
136
|
"""Attempt to consume the tokens from the bucket if available."""
|
|
126
137
|
if not isinstance(self.tokens, (int, float)):
|
|
127
138
|
return False # type: ignore[unreachable]
|
|
139
|
+
if not math.isfinite(self.tokens):
|
|
140
|
+
# Reset to capacity if state is corrupted to inf/nan
|
|
141
|
+
self.tokens = self.capacity
|
|
142
|
+
return False
|
|
128
143
|
if self.tokens >= tokens:
|
|
129
144
|
self.tokens -= tokens
|
|
130
145
|
return True
|
|
131
146
|
return False
|
|
132
147
|
|
|
133
|
-
def
|
|
134
|
-
"""
|
|
148
|
+
def _get_current_time(self) -> float | None:
|
|
149
|
+
"""Get current monotonic time safely."""
|
|
135
150
|
try:
|
|
136
|
-
|
|
151
|
+
return time.monotonic()
|
|
137
152
|
except Exception:
|
|
153
|
+
return None
|
|
154
|
+
|
|
155
|
+
def _validate_and_add_tokens(self, now: float | None) -> bool:
|
|
156
|
+
"""Validate time and add tokens.
|
|
157
|
+
|
|
158
|
+
Returns True if tokens were added successfully, False otherwise.
|
|
159
|
+
"""
|
|
160
|
+
if now is None:
|
|
138
161
|
return False
|
|
162
|
+
if not isinstance(now, (int, float)):
|
|
163
|
+
return False # type: ignore[unreachable]
|
|
164
|
+
if not math.isfinite(now):
|
|
165
|
+
# If not finite, we can't add tokens, but we shouldn't fail
|
|
166
|
+
# the consumption if there are already tokens.
|
|
167
|
+
return True
|
|
168
|
+
return self._add_tokens(now)
|
|
169
|
+
|
|
170
|
+
def _process_consumption(self, tokens: float) -> bool:
|
|
171
|
+
"""Process token consumption inside the lock."""
|
|
172
|
+
now = self._get_current_time()
|
|
139
173
|
|
|
140
174
|
# Prevent time corruption from poisoning the bucket state.
|
|
141
175
|
# Only try to add tokens if time is finite.
|
|
142
|
-
if not
|
|
143
|
-
math.isfinite(now) and not self._add_tokens(now)
|
|
144
|
-
):
|
|
176
|
+
if not self._validate_and_add_tokens(now):
|
|
145
177
|
return False
|
|
146
178
|
|
|
147
179
|
return self._try_consume(tokens)
|
|
148
180
|
|
|
181
|
+
def _is_valid_token_amount(self, tokens: float) -> bool:
|
|
182
|
+
"""Check if requested token amount is valid."""
|
|
183
|
+
if not isinstance(tokens, (int, float)):
|
|
184
|
+
return False # type: ignore[unreachable]
|
|
185
|
+
return math.isfinite(tokens)
|
|
186
|
+
|
|
149
187
|
def consume(self, tokens: float = 1.0) -> bool:
|
|
150
188
|
"""Try to consume tokens.
|
|
151
189
|
|
|
@@ -156,7 +194,7 @@ class RateLimiter:
|
|
|
156
194
|
True if tokens were consumed (allow), False otherwise (limit exceeded).
|
|
157
195
|
|
|
158
196
|
"""
|
|
159
|
-
if not
|
|
197
|
+
if not self._is_valid_token_amount(tokens):
|
|
160
198
|
return False
|
|
161
199
|
if tokens <= 0:
|
|
162
200
|
return True
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/resilience/adaptive/adaptive_breaker.py
RENAMED
|
File without changes
|
{taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/resilience/adaptive/adaptive_retry.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/resilience/watchdogs/health_pinger.py
RENAMED
|
File without changes
|
{taipanstack-0.6.0 → taipanstack-0.6.1}/src/taipanstack/resilience/watchdogs/resource_watcher.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|