taipanstack 0.3.7__tar.gz → 0.3.8__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.3.7 → taipanstack-0.3.8}/PKG-INFO +1 -1
- {taipanstack-0.3.7 → taipanstack-0.3.8}/pyproject.toml +2 -2
- {taipanstack-0.3.7 → taipanstack-0.3.8}/src/taipanstack/__init__.py +1 -1
- {taipanstack-0.3.7 → taipanstack-0.3.8}/src/taipanstack/config/generators.py +77 -24
- {taipanstack-0.3.7 → taipanstack-0.3.8}/src/taipanstack/security/__init__.py +2 -0
- {taipanstack-0.3.7 → taipanstack-0.3.8}/src/taipanstack/security/guards.py +12 -7
- taipanstack-0.3.8/src/taipanstack/security/models.py +79 -0
- {taipanstack-0.3.7 → taipanstack-0.3.8}/src/taipanstack/utils/__init__.py +5 -0
- taipanstack-0.3.8/src/taipanstack/utils/concurrency.py +136 -0
- {taipanstack-0.3.7 → taipanstack-0.3.8}/src/taipanstack/utils/logging.py +13 -5
- taipanstack-0.3.8/src/taipanstack/utils/serialization.py +47 -0
- {taipanstack-0.3.7 → taipanstack-0.3.8}/LICENSE +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.8}/README.md +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.8}/src/taipanstack/config/__init__.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.8}/src/taipanstack/config/models.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.8}/src/taipanstack/config/version_config.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.8}/src/taipanstack/core/__init__.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.8}/src/taipanstack/core/compat.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.8}/src/taipanstack/core/optimizations.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.8}/src/taipanstack/core/result.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.8}/src/taipanstack/security/decorators.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.8}/src/taipanstack/security/jwt.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.8}/src/taipanstack/security/password.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.8}/src/taipanstack/security/sanitizers.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.8}/src/taipanstack/security/types.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.8}/src/taipanstack/security/validators.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.8}/src/taipanstack/utils/circuit_breaker.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.8}/src/taipanstack/utils/filesystem.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.8}/src/taipanstack/utils/metrics.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.8}/src/taipanstack/utils/rate_limit.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.8}/src/taipanstack/utils/retry.py +0 -0
- {taipanstack-0.3.7 → taipanstack-0.3.8}/src/taipanstack/utils/subprocess.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "taipanstack"
|
|
3
|
-
version = "0.3.
|
|
3
|
+
version = "0.3.8"
|
|
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"}
|
|
@@ -119,7 +119,7 @@ max-complexity = 10
|
|
|
119
119
|
|
|
120
120
|
[tool.ruff.lint.per-file-ignores]
|
|
121
121
|
# Tests: allow asserts, skip docs, magic values, unused args, long lines, shadowing builtins
|
|
122
|
-
"tests/**/*.py" = ["S101", "D", "PLR2004", "ARG001", "ARG002", "SIM117", "RUF043", "PLC0415", "E501", "A004", "TRY301", "UP024"]
|
|
122
|
+
"tests/**/*.py" = ["S101", "S105", "S106", "D", "PLR2004", "ARG001", "ARG002", "SIM117", "RUF043", "PLC0415", "E501", "A004", "TRY301", "UP024"]
|
|
123
123
|
# TaipanStack bootstrapper: allow print, long lines, complex branches, docstring style, unused args
|
|
124
124
|
"taipanstack_bootstrapper.py" = ["T201", "E501", "PLR0912", "TRY300", "S603", "D205", "ARG001"]
|
|
125
125
|
# Utils: allow too many args, subprocess, random for jitter
|
|
@@ -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.
|
|
8
|
+
__version__ = "0.3.8"
|
|
9
9
|
|
|
10
10
|
from taipanstack.config.version_config import (
|
|
11
11
|
VersionRecommendations,
|
|
@@ -153,58 +153,82 @@ def generate_pyproject_config(config: StackConfig) -> str:
|
|
|
153
153
|
{_generate_coverage_config()}"""
|
|
154
154
|
|
|
155
155
|
|
|
156
|
-
def
|
|
157
|
-
"""Generate
|
|
156
|
+
def _generate_bandit_hook(severity: str) -> str:
|
|
157
|
+
"""Generate Bandit pre-commit hook.
|
|
158
158
|
|
|
159
159
|
Args:
|
|
160
|
-
|
|
160
|
+
severity: Bandit severity level.
|
|
161
161
|
|
|
162
162
|
Returns:
|
|
163
|
-
|
|
163
|
+
Bandit hook YAML string.
|
|
164
164
|
|
|
165
165
|
"""
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
if config.security.enable_bandit:
|
|
169
|
-
severity = config.security.bandit_severity[0].upper()
|
|
170
|
-
security_hooks.append(f"""
|
|
166
|
+
sev_char = severity[0].upper()
|
|
167
|
+
return f"""
|
|
171
168
|
- repo: https://github.com/PyCQA/bandit
|
|
172
169
|
rev: '1.8.0'
|
|
173
170
|
hooks:
|
|
174
171
|
- id: bandit
|
|
175
|
-
args: ["-r", ".", "-l{
|
|
176
|
-
"""
|
|
172
|
+
args: ["-r", ".", "-l{sev_char}"]
|
|
173
|
+
"""
|
|
177
174
|
|
|
178
|
-
|
|
179
|
-
|
|
175
|
+
|
|
176
|
+
def _generate_safety_hook() -> str:
|
|
177
|
+
"""Generate Safety pre-commit hook.
|
|
178
|
+
|
|
179
|
+
Returns:
|
|
180
|
+
Safety hook YAML string.
|
|
181
|
+
|
|
182
|
+
"""
|
|
183
|
+
return """
|
|
180
184
|
- repo: https://github.com/pyupio/safety
|
|
181
185
|
rev: '3.2.11'
|
|
182
186
|
hooks:
|
|
183
187
|
- id: safety
|
|
184
188
|
args: ["check", "--json"]
|
|
185
|
-
"""
|
|
189
|
+
"""
|
|
186
190
|
|
|
187
|
-
|
|
188
|
-
|
|
191
|
+
|
|
192
|
+
def _generate_semgrep_hook() -> str:
|
|
193
|
+
"""Generate Semgrep pre-commit hook.
|
|
194
|
+
|
|
195
|
+
Returns:
|
|
196
|
+
Semgrep hook YAML string.
|
|
197
|
+
|
|
198
|
+
"""
|
|
199
|
+
return """
|
|
189
200
|
- repo: https://github.com/semgrep/pre-commit
|
|
190
201
|
rev: 'v1.99.0'
|
|
191
202
|
hooks:
|
|
192
203
|
- id: semgrep
|
|
193
204
|
args: ['--config=auto']
|
|
194
|
-
"""
|
|
205
|
+
"""
|
|
195
206
|
|
|
196
|
-
|
|
197
|
-
|
|
207
|
+
|
|
208
|
+
def _generate_detect_secrets_hook() -> str:
|
|
209
|
+
"""Generate detect-secrets pre-commit hook.
|
|
210
|
+
|
|
211
|
+
Returns:
|
|
212
|
+
Detect-secrets hook YAML string.
|
|
213
|
+
|
|
214
|
+
"""
|
|
215
|
+
return """
|
|
198
216
|
- repo: https://github.com/Yelp/detect-secrets
|
|
199
217
|
rev: 'v1.5.0'
|
|
200
218
|
hooks:
|
|
201
219
|
- id: detect-secrets
|
|
202
220
|
args: ['--baseline', '.secrets.baseline']
|
|
203
|
-
"""
|
|
221
|
+
"""
|
|
204
222
|
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
223
|
+
|
|
224
|
+
def _generate_paranoid_hooks() -> str:
|
|
225
|
+
"""Generate extra security hooks for paranoid mode.
|
|
226
|
+
|
|
227
|
+
Returns:
|
|
228
|
+
Paranoid hooks YAML string.
|
|
229
|
+
|
|
230
|
+
"""
|
|
231
|
+
return """
|
|
208
232
|
- repo: https://github.com/trailofbits/pip-audit
|
|
209
233
|
rev: 'v2.7.3'
|
|
210
234
|
hooks:
|
|
@@ -219,7 +243,36 @@ def generate_pre_commit_config(config: StackConfig) -> str:
|
|
|
219
243
|
rev: 'v2.3.3'
|
|
220
244
|
hooks:
|
|
221
245
|
- id: tryceratops
|
|
222
|
-
"""
|
|
246
|
+
"""
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def generate_pre_commit_config(config: StackConfig) -> str:
|
|
250
|
+
"""Generate .pre-commit-config.yaml content.
|
|
251
|
+
|
|
252
|
+
Args:
|
|
253
|
+
config: The Stack configuration.
|
|
254
|
+
|
|
255
|
+
Returns:
|
|
256
|
+
Pre-commit configuration YAML string.
|
|
257
|
+
|
|
258
|
+
"""
|
|
259
|
+
security_hooks: list[str] = []
|
|
260
|
+
|
|
261
|
+
if config.security.enable_bandit:
|
|
262
|
+
security_hooks.append(_generate_bandit_hook(config.security.bandit_severity))
|
|
263
|
+
|
|
264
|
+
if config.security.enable_safety:
|
|
265
|
+
security_hooks.append(_generate_safety_hook())
|
|
266
|
+
|
|
267
|
+
if config.security.enable_semgrep:
|
|
268
|
+
security_hooks.append(_generate_semgrep_hook())
|
|
269
|
+
|
|
270
|
+
if config.security.enable_detect_secrets:
|
|
271
|
+
security_hooks.append(_generate_detect_secrets_hook())
|
|
272
|
+
|
|
273
|
+
# Add extra hooks for paranoid mode
|
|
274
|
+
if config.security.level == "paranoid":
|
|
275
|
+
security_hooks.append(_generate_paranoid_hooks())
|
|
223
276
|
|
|
224
277
|
return f"""# Stack v2.0 Pre-commit Configuration
|
|
225
278
|
# Security Level: {config.security.level}
|
|
@@ -17,6 +17,7 @@ from taipanstack.security.guards import (
|
|
|
17
17
|
guard_ssrf,
|
|
18
18
|
)
|
|
19
19
|
from taipanstack.security.jwt import decode_jwt, encode_jwt
|
|
20
|
+
from taipanstack.security.models import SecureBaseModel
|
|
20
21
|
from taipanstack.security.password import hash_password, verify_password
|
|
21
22
|
from taipanstack.security.sanitizers import (
|
|
22
23
|
sanitize_filename,
|
|
@@ -43,6 +44,7 @@ __all__ = [
|
|
|
43
44
|
"SafePath",
|
|
44
45
|
"SafeProjectName",
|
|
45
46
|
"SafeUrl",
|
|
47
|
+
"SecureBaseModel",
|
|
46
48
|
"SecurityError",
|
|
47
49
|
"ValidationError",
|
|
48
50
|
"decode_jwt",
|
|
@@ -27,6 +27,10 @@ _TRAVERSAL_PATTERNS: frozenset[str] = frozenset(
|
|
|
27
27
|
]
|
|
28
28
|
)
|
|
29
29
|
|
|
30
|
+
_TRAVERSAL_REGEX = re.compile(
|
|
31
|
+
"|".join(re.escape(p) for p in sorted(_TRAVERSAL_PATTERNS, key=len, reverse=True))
|
|
32
|
+
)
|
|
33
|
+
|
|
30
34
|
_DANGEROUS_COMMAND_PATTERNS: tuple[tuple[str, str], ...] = (
|
|
31
35
|
(";", "command separator"),
|
|
32
36
|
("|", "pipe"),
|
|
@@ -155,13 +159,14 @@ def guard_path_traversal(
|
|
|
155
159
|
path_str = str(path)
|
|
156
160
|
path_str_lower = path_str.lower()
|
|
157
161
|
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
162
|
+
match = _TRAVERSAL_REGEX.search(path_str_lower)
|
|
163
|
+
if match:
|
|
164
|
+
pattern = match.group(0)
|
|
165
|
+
raise SecurityError(
|
|
166
|
+
f"Path traversal pattern detected: {pattern}",
|
|
167
|
+
guard_name="path_traversal",
|
|
168
|
+
value=path_str[:50], # Truncate for safety
|
|
169
|
+
)
|
|
165
170
|
|
|
166
171
|
# Resolve the path
|
|
167
172
|
try:
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Secure base models."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from pydantic import BaseModel
|
|
8
|
+
|
|
9
|
+
from taipanstack.utils.logging import REDACTED_VALUE, SENSITIVE_KEY_PATTERNS
|
|
10
|
+
|
|
11
|
+
__all__ = ["SecureBaseModel"]
|
|
12
|
+
|
|
13
|
+
_SENSITIVE_KEY_REGEX = (
|
|
14
|
+
re.compile("|".join(map(re.escape, SENSITIVE_KEY_PATTERNS)), re.IGNORECASE)
|
|
15
|
+
if SENSITIVE_KEY_PATTERNS
|
|
16
|
+
else None
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _mask_data(data: Any) -> Any:
|
|
21
|
+
"""Recursively mask sensitive keys in data."""
|
|
22
|
+
if _SENSITIVE_KEY_REGEX is None:
|
|
23
|
+
return data
|
|
24
|
+
|
|
25
|
+
if isinstance(data, dict):
|
|
26
|
+
masked = {}
|
|
27
|
+
for k, v in data.items():
|
|
28
|
+
if isinstance(k, str) and _SENSITIVE_KEY_REGEX.search(k):
|
|
29
|
+
masked[k] = REDACTED_VALUE
|
|
30
|
+
else:
|
|
31
|
+
masked[k] = _mask_data(v)
|
|
32
|
+
return masked
|
|
33
|
+
elif isinstance(data, list):
|
|
34
|
+
return [_mask_data(item) for item in data]
|
|
35
|
+
return data
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class SecureBaseModel(BaseModel):
|
|
39
|
+
"""Secure base model that redacts sensitive fields when dumped."""
|
|
40
|
+
|
|
41
|
+
def model_dump(
|
|
42
|
+
self,
|
|
43
|
+
**kwargs: Any,
|
|
44
|
+
) -> dict[str, Any]:
|
|
45
|
+
"""Dump the model to a dictionary, redacting sensitive fields.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
**kwargs: Arguments to pass to Pydantic's model_dump.
|
|
49
|
+
|
|
50
|
+
Returns:
|
|
51
|
+
The redacting dictionary representation of the model.
|
|
52
|
+
|
|
53
|
+
"""
|
|
54
|
+
data = super().model_dump(**kwargs)
|
|
55
|
+
return _mask_data(data) # type: ignore[no-any-return]
|
|
56
|
+
|
|
57
|
+
def model_dump_json(
|
|
58
|
+
self,
|
|
59
|
+
**kwargs: Any,
|
|
60
|
+
) -> str:
|
|
61
|
+
"""Dump the model to a JSON string, redacting sensitive fields.
|
|
62
|
+
|
|
63
|
+
Args:
|
|
64
|
+
**kwargs: Arguments to pass to Pydantic's model_dump.
|
|
65
|
+
|
|
66
|
+
Returns:
|
|
67
|
+
The redacted JSON string representation of the model.
|
|
68
|
+
|
|
69
|
+
"""
|
|
70
|
+
# Extract indent if any, as model_dump does not accept it
|
|
71
|
+
indent = kwargs.pop("indent", None)
|
|
72
|
+
# Dump to JSON-compatible dict, mask, then serialize
|
|
73
|
+
dumped_dict = super().model_dump(mode="json", **kwargs)
|
|
74
|
+
masked_dict = _mask_data(dumped_dict)
|
|
75
|
+
# We need to respect Pydantic's indent/separators if possible,
|
|
76
|
+
# but json.dumps is the safest standard way.
|
|
77
|
+
if indent is not None:
|
|
78
|
+
return json.dumps(masked_dict, indent=indent)
|
|
79
|
+
return json.dumps(masked_dict)
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"""Utility modules for Stack."""
|
|
2
2
|
|
|
3
|
+
from .concurrency import OverloadError, limit_concurrency
|
|
3
4
|
from .filesystem import ensure_dir, safe_read, safe_write
|
|
4
5
|
from .logging import (
|
|
5
6
|
REDACTED_VALUE,
|
|
@@ -12,20 +13,24 @@ from .logging import (
|
|
|
12
13
|
)
|
|
13
14
|
from .rate_limit import RateLimiter, RateLimitError, rate_limit
|
|
14
15
|
from .retry import Retrier, RetryConfig, RetryError, retry
|
|
16
|
+
from .serialization import default_encoder
|
|
15
17
|
from .subprocess import SafeCommandResult, run_safe_command
|
|
16
18
|
|
|
17
19
|
__all__ = (
|
|
18
20
|
"REDACTED_VALUE",
|
|
19
21
|
"SENSITIVE_KEY_PATTERNS",
|
|
22
|
+
"OverloadError",
|
|
20
23
|
"RateLimitError",
|
|
21
24
|
"RateLimiter",
|
|
22
25
|
"Retrier",
|
|
23
26
|
"RetryConfig",
|
|
24
27
|
"RetryError",
|
|
25
28
|
"SafeCommandResult",
|
|
29
|
+
"default_encoder",
|
|
26
30
|
"ensure_dir",
|
|
27
31
|
"get_correlation_id",
|
|
28
32
|
"get_logger",
|
|
33
|
+
"limit_concurrency",
|
|
29
34
|
"log_operation",
|
|
30
35
|
"rate_limit",
|
|
31
36
|
"retry",
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Concurrency utilities.
|
|
3
|
+
|
|
4
|
+
Provides a bulkhead pattern concurrency limiter decorator for both
|
|
5
|
+
synchronous and asynchronous functions. Uses an `OverloadError` and
|
|
6
|
+
returns a `Result` type.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
import functools
|
|
11
|
+
import inspect
|
|
12
|
+
import threading
|
|
13
|
+
from collections.abc import Callable, Coroutine
|
|
14
|
+
from typing import Any, ParamSpec, Protocol, TypeVar, overload
|
|
15
|
+
|
|
16
|
+
from taipanstack.core.result import Err, Ok, Result
|
|
17
|
+
|
|
18
|
+
__all__ = ["OverloadError", "limit_concurrency"]
|
|
19
|
+
|
|
20
|
+
P = ParamSpec("P")
|
|
21
|
+
T = TypeVar("T")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class OverloadError(Exception):
|
|
25
|
+
"""Exception raised when a concurrency limit is exceeded or timed out."""
|
|
26
|
+
|
|
27
|
+
def __init__(self, message: str = "Concurrency limit reached") -> None:
|
|
28
|
+
"""Initialize the OverloadError.
|
|
29
|
+
|
|
30
|
+
Args:
|
|
31
|
+
message: The error message to display.
|
|
32
|
+
Defaults to "Concurrency limit reached".
|
|
33
|
+
|
|
34
|
+
"""
|
|
35
|
+
super().__init__(message)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class ConcurrencyLimitDecorator(Protocol):
|
|
39
|
+
"""Protocol for the concurrency limit decorator."""
|
|
40
|
+
|
|
41
|
+
@overload
|
|
42
|
+
def __call__(
|
|
43
|
+
self, func: Callable[P, T]
|
|
44
|
+
) -> Callable[P, Result[T, OverloadError]]: ... # pragma: no cover
|
|
45
|
+
|
|
46
|
+
@overload
|
|
47
|
+
def __call__(
|
|
48
|
+
self, func: Callable[P, Coroutine[Any, Any, T]]
|
|
49
|
+
) -> Callable[
|
|
50
|
+
P, Coroutine[Any, Any, Result[T, OverloadError]]
|
|
51
|
+
]: ... # pragma: no cover
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def limit_concurrency(
|
|
55
|
+
max_tasks: int,
|
|
56
|
+
timeout: float = 0.0,
|
|
57
|
+
) -> ConcurrencyLimitDecorator:
|
|
58
|
+
"""Decorate a function to apply the bulkhead concurrency limit pattern.
|
|
59
|
+
|
|
60
|
+
If the maximum concurrent executions are reached, the wrapper will wait up
|
|
61
|
+
to `timeout` seconds to acquire a execution slot. If it fails, it returns
|
|
62
|
+
an ``Err(OverloadError)``.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
max_tasks: Maximum concurrent function executions allowed.
|
|
66
|
+
timeout: Maximum time in seconds to wait for a slot if limit is reached.
|
|
67
|
+
|
|
68
|
+
Returns:
|
|
69
|
+
Decorated function returning a ``Result[T, OverloadError]``.
|
|
70
|
+
|
|
71
|
+
Example:
|
|
72
|
+
>>> @limit_concurrency(max_tasks=2, timeout=0.1)
|
|
73
|
+
... def process_data() -> str:
|
|
74
|
+
... return "data"
|
|
75
|
+
>>> process_data()
|
|
76
|
+
Ok('data')
|
|
77
|
+
|
|
78
|
+
"""
|
|
79
|
+
if max_tasks <= 0:
|
|
80
|
+
raise ValueError("max_tasks must be > 0")
|
|
81
|
+
if timeout < 0.0:
|
|
82
|
+
raise ValueError("timeout must be >= 0.0")
|
|
83
|
+
|
|
84
|
+
def decorator(
|
|
85
|
+
func: Callable[P, T] | Callable[P, Coroutine[Any, Any, T]],
|
|
86
|
+
) -> (
|
|
87
|
+
Callable[P, Result[T, OverloadError]]
|
|
88
|
+
| Callable[P, Coroutine[Any, Any, Result[T, OverloadError]]]
|
|
89
|
+
):
|
|
90
|
+
if inspect.iscoroutinefunction(func):
|
|
91
|
+
async_semaphore = asyncio.Semaphore(max_tasks)
|
|
92
|
+
|
|
93
|
+
@functools.wraps(func)
|
|
94
|
+
async def async_wrapper(
|
|
95
|
+
*args: P.args,
|
|
96
|
+
**kwargs: P.kwargs,
|
|
97
|
+
) -> Result[T, OverloadError]:
|
|
98
|
+
if timeout > 0.0:
|
|
99
|
+
try:
|
|
100
|
+
async with asyncio.timeout(timeout):
|
|
101
|
+
await async_semaphore.acquire()
|
|
102
|
+
except TimeoutError:
|
|
103
|
+
return Err(OverloadError())
|
|
104
|
+
else:
|
|
105
|
+
if async_semaphore.locked():
|
|
106
|
+
return Err(OverloadError())
|
|
107
|
+
await async_semaphore.acquire()
|
|
108
|
+
|
|
109
|
+
try:
|
|
110
|
+
return Ok(await func(*args, **kwargs))
|
|
111
|
+
finally:
|
|
112
|
+
async_semaphore.release()
|
|
113
|
+
|
|
114
|
+
return async_wrapper
|
|
115
|
+
|
|
116
|
+
sync_semaphore = threading.Semaphore(max_tasks)
|
|
117
|
+
|
|
118
|
+
@functools.wraps(func)
|
|
119
|
+
def wrapper(*args: P.args, **kwargs: P.kwargs) -> Result[T, OverloadError]:
|
|
120
|
+
if timeout > 0.0:
|
|
121
|
+
acquired = sync_semaphore.acquire(timeout=timeout)
|
|
122
|
+
if not acquired:
|
|
123
|
+
return Err(OverloadError())
|
|
124
|
+
else:
|
|
125
|
+
acquired = sync_semaphore.acquire(blocking=False)
|
|
126
|
+
if not acquired:
|
|
127
|
+
return Err(OverloadError())
|
|
128
|
+
|
|
129
|
+
try:
|
|
130
|
+
return Ok(func(*args, **kwargs)) # type: ignore[arg-type]
|
|
131
|
+
finally:
|
|
132
|
+
sync_semaphore.release()
|
|
133
|
+
|
|
134
|
+
return wrapper
|
|
135
|
+
|
|
136
|
+
return decorator # type: ignore[return-value]
|
|
@@ -6,6 +6,7 @@ context propagation, and proper formatting.
|
|
|
6
6
|
"""
|
|
7
7
|
|
|
8
8
|
import logging
|
|
9
|
+
import re
|
|
9
10
|
import sys
|
|
10
11
|
from collections.abc import MutableMapping
|
|
11
12
|
from contextlib import contextmanager
|
|
@@ -36,6 +37,13 @@ SENSITIVE_KEY_PATTERNS: tuple[str, ...] = (
|
|
|
36
37
|
"api_key",
|
|
37
38
|
)
|
|
38
39
|
|
|
40
|
+
# Pre-compile the regex for O(1) checks per key instead of O(N*M)
|
|
41
|
+
_SENSITIVE_KEY_REGEX = (
|
|
42
|
+
re.compile("|".join(map(re.escape, SENSITIVE_KEY_PATTERNS)), re.IGNORECASE)
|
|
43
|
+
if SENSITIVE_KEY_PATTERNS
|
|
44
|
+
else None
|
|
45
|
+
)
|
|
46
|
+
|
|
39
47
|
REDACTED_VALUE = "***REDACTED***"
|
|
40
48
|
|
|
41
49
|
|
|
@@ -59,12 +67,12 @@ def mask_sensitive_data_processor(
|
|
|
59
67
|
The event dictionary with sensitive values masked.
|
|
60
68
|
|
|
61
69
|
"""
|
|
70
|
+
if _SENSITIVE_KEY_REGEX is None:
|
|
71
|
+
return event_dict
|
|
72
|
+
|
|
62
73
|
for key in event_dict:
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
if pattern in key_lower:
|
|
66
|
-
event_dict[key] = REDACTED_VALUE
|
|
67
|
-
break
|
|
74
|
+
if _SENSITIVE_KEY_REGEX.search(key):
|
|
75
|
+
event_dict[key] = REDACTED_VALUE
|
|
68
76
|
return event_dict
|
|
69
77
|
|
|
70
78
|
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Serialization utilities.
|
|
3
|
+
|
|
4
|
+
Provides an optimized default encoder for use with ``orjson.dumps``.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from taipanstack.core.result import Err, Ok
|
|
10
|
+
|
|
11
|
+
__all__ = ["default_encoder"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def default_encoder(obj: Any) -> dict[str, Any]:
|
|
15
|
+
"""Default encoder for orjson.dumps handling Result types.
|
|
16
|
+
|
|
17
|
+
Intercepts objects of type ``Ok`` and ``Err``:
|
|
18
|
+
- ``Ok(value)``: Returns ``{"status": "success"}`` merged with ``value`` if
|
|
19
|
+
``value`` is a dict. Otherwise returns ``{"status": "success", "data": value}``.
|
|
20
|
+
- ``Err(error)``: Returns ``{"status": "error", "message": str(error)}``.
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
obj: The object to encode.
|
|
24
|
+
|
|
25
|
+
Returns:
|
|
26
|
+
A serializable representation of the object.
|
|
27
|
+
|
|
28
|
+
Raises:
|
|
29
|
+
TypeError: If the object type is not supported.
|
|
30
|
+
|
|
31
|
+
Example:
|
|
32
|
+
>>> import orjson
|
|
33
|
+
>>> orjson.dumps(Ok({"id": 1}), default=default_encoder)
|
|
34
|
+
b'{"status":"success","id":1}'
|
|
35
|
+
>>> orjson.dumps(Err(ValueError("oops")), default=default_encoder)
|
|
36
|
+
b'{"status":"error","message":"oops"}'
|
|
37
|
+
|
|
38
|
+
"""
|
|
39
|
+
if isinstance(obj, Ok):
|
|
40
|
+
if isinstance(obj.value, dict):
|
|
41
|
+
return {"status": "success", **obj.value}
|
|
42
|
+
return {"status": "success", "data": obj.value}
|
|
43
|
+
|
|
44
|
+
if isinstance(obj, Err):
|
|
45
|
+
return {"status": "error", "message": str(obj.value)}
|
|
46
|
+
|
|
47
|
+
raise TypeError(f"Type {type(obj).__name__} is not JSON serializable")
|
|
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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|