taipanstack 0.3.6__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.
Files changed (32) hide show
  1. {taipanstack-0.3.6 → taipanstack-0.3.8}/PKG-INFO +1 -1
  2. {taipanstack-0.3.6 → taipanstack-0.3.8}/pyproject.toml +2 -2
  3. {taipanstack-0.3.6 → taipanstack-0.3.8}/src/taipanstack/__init__.py +1 -1
  4. {taipanstack-0.3.6 → taipanstack-0.3.8}/src/taipanstack/config/generators.py +77 -24
  5. {taipanstack-0.3.6 → taipanstack-0.3.8}/src/taipanstack/security/__init__.py +2 -0
  6. {taipanstack-0.3.6 → taipanstack-0.3.8}/src/taipanstack/security/decorators.py +6 -7
  7. {taipanstack-0.3.6 → taipanstack-0.3.8}/src/taipanstack/security/guards.py +29 -18
  8. taipanstack-0.3.8/src/taipanstack/security/models.py +79 -0
  9. {taipanstack-0.3.6 → taipanstack-0.3.8}/src/taipanstack/utils/__init__.py +5 -0
  10. taipanstack-0.3.8/src/taipanstack/utils/concurrency.py +136 -0
  11. {taipanstack-0.3.6 → taipanstack-0.3.8}/src/taipanstack/utils/logging.py +13 -5
  12. {taipanstack-0.3.6 → taipanstack-0.3.8}/src/taipanstack/utils/retry.py +43 -27
  13. taipanstack-0.3.8/src/taipanstack/utils/serialization.py +47 -0
  14. {taipanstack-0.3.6 → taipanstack-0.3.8}/src/taipanstack/utils/subprocess.py +3 -1
  15. {taipanstack-0.3.6 → taipanstack-0.3.8}/LICENSE +0 -0
  16. {taipanstack-0.3.6 → taipanstack-0.3.8}/README.md +0 -0
  17. {taipanstack-0.3.6 → taipanstack-0.3.8}/src/taipanstack/config/__init__.py +0 -0
  18. {taipanstack-0.3.6 → taipanstack-0.3.8}/src/taipanstack/config/models.py +0 -0
  19. {taipanstack-0.3.6 → taipanstack-0.3.8}/src/taipanstack/config/version_config.py +0 -0
  20. {taipanstack-0.3.6 → taipanstack-0.3.8}/src/taipanstack/core/__init__.py +0 -0
  21. {taipanstack-0.3.6 → taipanstack-0.3.8}/src/taipanstack/core/compat.py +0 -0
  22. {taipanstack-0.3.6 → taipanstack-0.3.8}/src/taipanstack/core/optimizations.py +0 -0
  23. {taipanstack-0.3.6 → taipanstack-0.3.8}/src/taipanstack/core/result.py +0 -0
  24. {taipanstack-0.3.6 → taipanstack-0.3.8}/src/taipanstack/security/jwt.py +0 -0
  25. {taipanstack-0.3.6 → taipanstack-0.3.8}/src/taipanstack/security/password.py +0 -0
  26. {taipanstack-0.3.6 → taipanstack-0.3.8}/src/taipanstack/security/sanitizers.py +0 -0
  27. {taipanstack-0.3.6 → taipanstack-0.3.8}/src/taipanstack/security/types.py +0 -0
  28. {taipanstack-0.3.6 → taipanstack-0.3.8}/src/taipanstack/security/validators.py +0 -0
  29. {taipanstack-0.3.6 → taipanstack-0.3.8}/src/taipanstack/utils/circuit_breaker.py +0 -0
  30. {taipanstack-0.3.6 → taipanstack-0.3.8}/src/taipanstack/utils/filesystem.py +0 -0
  31. {taipanstack-0.3.6 → taipanstack-0.3.8}/src/taipanstack/utils/metrics.py +0 -0
  32. {taipanstack-0.3.6 → taipanstack-0.3.8}/src/taipanstack/utils/rate_limit.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: taipanstack
3
- Version: 0.3.6
3
+ Version: 0.3.8
4
4
  Summary: TaipanStack - Modular, secure, and scalable Python stack for robust development
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "taipanstack"
3
- version = "0.3.6"
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.6"
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 generate_pre_commit_config(config: StackConfig) -> str:
157
- """Generate .pre-commit-config.yaml content.
156
+ def _generate_bandit_hook(severity: str) -> str:
157
+ """Generate Bandit pre-commit hook.
158
158
 
159
159
  Args:
160
- config: The Stack configuration.
160
+ severity: Bandit severity level.
161
161
 
162
162
  Returns:
163
- Pre-commit configuration YAML string.
163
+ Bandit hook YAML string.
164
164
 
165
165
  """
166
- security_hooks: list[str] = []
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{severity}"]
176
- """)
172
+ args: ["-r", ".", "-l{sev_char}"]
173
+ """
177
174
 
178
- if config.security.enable_safety:
179
- security_hooks.append("""
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
- if config.security.enable_semgrep:
188
- security_hooks.append("""
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
- if config.security.enable_detect_secrets:
197
- security_hooks.append("""
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
- # Add pip-audit for paranoid mode
206
- if config.security.level == "paranoid":
207
- security_hooks.append("""
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",
@@ -7,6 +7,7 @@ any Python framework (Flask, FastAPI, Django, etc.).
7
7
  """
8
8
 
9
9
  import functools
10
+ import inspect
10
11
  import signal
11
12
  import sys
12
13
  import threading
@@ -83,12 +84,11 @@ def validate_inputs(
83
84
  """
84
85
 
85
86
  def decorator(func: Callable[P, R]) -> Callable[P, R]:
87
+ sig = inspect.signature(func)
88
+
86
89
  @functools.wraps(func)
87
90
  def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
88
- # Get function's parameter names
89
- import inspect
90
-
91
- sig = inspect.signature(func)
91
+ # Bind and apply defaults on each call
92
92
  bound = sig.bind(*args, **kwargs)
93
93
  bound.apply_defaults()
94
94
 
@@ -353,11 +353,10 @@ def require_type(
353
353
  """
354
354
 
355
355
  def decorator(func: Callable[P, R]) -> Callable[P, R]:
356
+ sig = inspect.signature(func)
357
+
356
358
  @functools.wraps(func)
357
359
  def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
358
- import inspect
359
-
360
- sig = inspect.signature(func)
361
360
  bound = sig.bind(*args, **kwargs)
362
361
  bound.apply_defaults()
363
362
 
@@ -17,7 +17,8 @@ from urllib.parse import urlparse
17
17
  from result import Err, Ok, Result
18
18
 
19
19
  _TRAVERSAL_PATTERNS: frozenset[str] = frozenset(
20
- [
20
+ p.lower()
21
+ for p in [
21
22
  "..",
22
23
  "~",
23
24
  r"\.\.",
@@ -26,6 +27,10 @@ _TRAVERSAL_PATTERNS: frozenset[str] = frozenset(
26
27
  ]
27
28
  )
28
29
 
30
+ _TRAVERSAL_REGEX = re.compile(
31
+ "|".join(re.escape(p) for p in sorted(_TRAVERSAL_PATTERNS, key=len, reverse=True))
32
+ )
33
+
29
34
  _DANGEROUS_COMMAND_PATTERNS: tuple[tuple[str, str], ...] = (
30
35
  (";", "command separator"),
31
36
  ("|", "pipe"),
@@ -152,18 +157,21 @@ def guard_path_traversal(
152
157
 
153
158
  # Check for explicit traversal patterns before resolution
154
159
  path_str = str(path)
160
+ path_str_lower = path_str.lower()
155
161
 
156
- for pattern in _TRAVERSAL_PATTERNS:
157
- if pattern.lower() in path_str.lower():
158
- raise SecurityError(
159
- f"Path traversal pattern detected: {pattern}",
160
- guard_name="path_traversal",
161
- value=path_str[:50], # Truncate for safety
162
- )
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
+ )
163
170
 
164
171
  # Resolve the path
165
172
  try:
166
- resolved = path.resolve() if path.is_absolute() else (base_dir / path).resolve()
173
+ full_path = path if path.is_absolute() else (base_dir / path)
174
+ resolved = full_path.resolve()
167
175
  except (OSError, ValueError) as e:
168
176
  raise SecurityError(
169
177
  f"Invalid path: {e}",
@@ -181,15 +189,18 @@ def guard_path_traversal(
181
189
  ) from e
182
190
 
183
191
  # Check for symlinks if not allowed
184
- is_existing_symlink = (
185
- not allow_symlinks and resolved.exists() and resolved.is_symlink()
186
- )
187
- if is_existing_symlink:
188
- raise SecurityError(
189
- "Symlinks are not allowed",
190
- guard_name="path_traversal",
191
- value=str(resolved),
192
- )
192
+ if not allow_symlinks:
193
+ current = full_path
194
+ # Only check components from the user-provided path, not the base_dir
195
+ while current not in (base_dir, current.parent):
196
+ # We don't check .exists() because it returns False for broken symlinks
197
+ if current.is_symlink():
198
+ raise SecurityError(
199
+ "Symlinks are not allowed",
200
+ guard_name="path_traversal",
201
+ value=str(current),
202
+ )
203
+ current = current.parent
193
204
 
194
205
  return resolved
195
206
 
@@ -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
- key_lower = key.lower()
64
- for pattern in SENSITIVE_KEY_PATTERNS:
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
 
@@ -15,7 +15,7 @@ import time
15
15
  from collections.abc import Callable
16
16
  from dataclasses import dataclass
17
17
  from types import TracebackType
18
- from typing import Any, ParamSpec, TypeVar, cast
18
+ from typing import Any, NoReturn, ParamSpec, TypeVar, cast
19
19
 
20
20
  P = ParamSpec("P")
21
21
  R = TypeVar("R")
@@ -176,6 +176,38 @@ def _log_all_failed(
176
176
  )
177
177
 
178
178
 
179
+ def _raise_retry_error(
180
+ func_name: str,
181
+ max_attempts: int,
182
+ reraise: bool,
183
+ last_exception: Exception | None,
184
+ ) -> NoReturn:
185
+ """Raise a RetryError after all attempts fail.
186
+
187
+ Args:
188
+ func_name: Name of the retried function.
189
+ max_attempts: Number of attempts made.
190
+ reraise: Whether to reraise the original exception.
191
+ last_exception: The last exception that was raised.
192
+
193
+ Raises:
194
+ RetryError: The wrapped or unwrapped exception.
195
+
196
+ """
197
+ if reraise and last_exception is not None:
198
+ raise RetryError(
199
+ f"All {max_attempts} attempts failed for {func_name}",
200
+ attempts=max_attempts,
201
+ last_exception=last_exception,
202
+ ) from last_exception
203
+
204
+ raise RetryError(
205
+ f"All {max_attempts} attempts failed for {func_name}",
206
+ attempts=max_attempts,
207
+ last_exception=last_exception,
208
+ )
209
+
210
+
179
211
  def retry(
180
212
  *,
181
213
  max_attempts: int = 3,
@@ -261,19 +293,11 @@ def retry(
261
293
  )
262
294
  await asyncio.sleep(delay)
263
295
 
264
- # All attempts failed
265
- if reraise and last_exception is not None:
266
- raise RetryError(
267
- f"All {max_attempts} attempts failed for {func.__name__}",
268
- attempts=max_attempts,
269
- last_exception=last_exception,
270
- ) from last_exception
271
-
272
- # Should never reach here if reraise=True
273
- raise RetryError(
274
- f"All {max_attempts} attempts failed for {func.__name__}",
275
- attempts=max_attempts,
276
- last_exception=last_exception,
296
+ _raise_retry_error(
297
+ func.__name__,
298
+ max_attempts,
299
+ reraise,
300
+ last_exception,
277
301
  )
278
302
 
279
303
  return cast(F, async_wrapper)
@@ -307,19 +331,11 @@ def retry(
307
331
  )
308
332
  time.sleep(delay)
309
333
 
310
- # All attempts failed
311
- if reraise and last_exception is not None:
312
- raise RetryError(
313
- f"All {max_attempts} attempts failed for {func.__name__}",
314
- attempts=max_attempts,
315
- last_exception=last_exception,
316
- ) from last_exception
317
-
318
- # Should never reach here if reraise=True
319
- raise RetryError(
320
- f"All {max_attempts} attempts failed for {func.__name__}",
321
- attempts=max_attempts,
322
- last_exception=last_exception,
334
+ _raise_retry_error(
335
+ func.__name__,
336
+ max_attempts,
337
+ reraise,
338
+ last_exception,
323
339
  )
324
340
 
325
341
  return cast(F, wrapper)
@@ -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")
@@ -295,7 +295,7 @@ def run_git_command(
295
295
  )
296
296
 
297
297
 
298
- def check_command_exists(command: str) -> bool:
298
+ def check_command_exists(command: str | None) -> bool:
299
299
  """Check if a command exists in PATH.
300
300
 
301
301
  Args:
@@ -305,6 +305,8 @@ def check_command_exists(command: str) -> bool:
305
305
  True if command exists, False otherwise.
306
306
 
307
307
  """
308
+ if not command:
309
+ return False
308
310
  return shutil.which(command) is not None
309
311
 
310
312
 
File without changes
File without changes