taipanstack 0.3.4__tar.gz → 0.3.6__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 (29) hide show
  1. {taipanstack-0.3.4 → taipanstack-0.3.6}/PKG-INFO +2 -1
  2. {taipanstack-0.3.4 → taipanstack-0.3.6}/pyproject.toml +5 -3
  3. {taipanstack-0.3.4 → taipanstack-0.3.6}/src/taipanstack/__init__.py +1 -1
  4. {taipanstack-0.3.4 → taipanstack-0.3.6}/src/taipanstack/config/generators.py +0 -1
  5. {taipanstack-0.3.4 → taipanstack-0.3.6}/src/taipanstack/core/optimizations.py +0 -1
  6. {taipanstack-0.3.4 → taipanstack-0.3.6}/src/taipanstack/core/result.py +111 -1
  7. {taipanstack-0.3.4 → taipanstack-0.3.6}/src/taipanstack/security/__init__.py +14 -1
  8. {taipanstack-0.3.4 → taipanstack-0.3.6}/src/taipanstack/security/decorators.py +0 -1
  9. {taipanstack-0.3.4 → taipanstack-0.3.6}/src/taipanstack/security/guards.py +0 -1
  10. taipanstack-0.3.6/src/taipanstack/security/jwt.py +92 -0
  11. {taipanstack-0.3.4 → taipanstack-0.3.6}/src/taipanstack/security/password.py +1 -1
  12. {taipanstack-0.3.4 → taipanstack-0.3.6}/src/taipanstack/security/sanitizers.py +0 -1
  13. taipanstack-0.3.6/src/taipanstack/security/types.py +133 -0
  14. {taipanstack-0.3.4 → taipanstack-0.3.6}/src/taipanstack/security/validators.py +0 -1
  15. {taipanstack-0.3.4 → taipanstack-0.3.6}/src/taipanstack/utils/__init__.py +18 -1
  16. {taipanstack-0.3.4 → taipanstack-0.3.6}/src/taipanstack/utils/circuit_breaker.py +31 -11
  17. {taipanstack-0.3.4 → taipanstack-0.3.6}/src/taipanstack/utils/logging.py +91 -1
  18. {taipanstack-0.3.4 → taipanstack-0.3.6}/src/taipanstack/utils/metrics.py +0 -1
  19. taipanstack-0.3.6/src/taipanstack/utils/rate_limit.py +150 -0
  20. {taipanstack-0.3.4 → taipanstack-0.3.6}/src/taipanstack/utils/retry.py +138 -42
  21. {taipanstack-0.3.4 → taipanstack-0.3.6}/src/taipanstack/utils/subprocess.py +2 -3
  22. {taipanstack-0.3.4 → taipanstack-0.3.6}/LICENSE +0 -0
  23. {taipanstack-0.3.4 → taipanstack-0.3.6}/README.md +0 -0
  24. {taipanstack-0.3.4 → taipanstack-0.3.6}/src/taipanstack/config/__init__.py +0 -0
  25. {taipanstack-0.3.4 → taipanstack-0.3.6}/src/taipanstack/config/models.py +0 -0
  26. {taipanstack-0.3.4 → taipanstack-0.3.6}/src/taipanstack/config/version_config.py +0 -0
  27. {taipanstack-0.3.4 → taipanstack-0.3.6}/src/taipanstack/core/__init__.py +0 -0
  28. {taipanstack-0.3.4 → taipanstack-0.3.6}/src/taipanstack/core/compat.py +0 -0
  29. {taipanstack-0.3.4 → taipanstack-0.3.6}/src/taipanstack/utils/filesystem.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: taipanstack
3
- Version: 0.3.4
3
+ Version: 0.3.6
4
4
  Summary: TaipanStack - Modular, secure, and scalable Python stack for robust development
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -23,6 +23,7 @@ Requires-Dist: email-validator (>=2.0.0)
23
23
  Requires-Dist: orjson (>=3.9.0)
24
24
  Requires-Dist: pydantic (>=2.0)
25
25
  Requires-Dist: pydantic-settings (>=2.0.0)
26
+ Requires-Dist: pyjwt (>=2.11.0,<3.0.0)
26
27
  Requires-Dist: result (>=0.17.0)
27
28
  Requires-Dist: structlog (>=23.0.0) ; extra == "runtime"
28
29
  Requires-Dist: uvloop (>=0.19.0) ; (sys_platform != "win32") and (extra == "runtime")
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "taipanstack"
3
- version = "0.3.4"
3
+ version = "0.3.6"
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"}
@@ -27,6 +27,7 @@ dependencies = [
27
27
  "orjson (>=3.9.0)",
28
28
  "email-validator (>=2.0.0)",
29
29
  "result (>=0.17.0)",
30
+ "pyjwt (>=2.11.0,<3.0.0)",
30
31
  ]
31
32
 
32
33
  [project.urls]
@@ -224,7 +225,8 @@ fail-under = 80
224
225
  verbose = 1
225
226
 
226
227
  [tool.mutmut]
227
- paths_to_mutate = "src/taipanstack/security/sanitizers.py,src/taipanstack/security/validators.py,src/taipanstack/security/guards.py"
228
- tests_dir = "tests/test_property_sanitizers.py,tests/test_security_validators.py,tests/test_security_guards.py,tests/test_security_ssrf.py"
228
+ paths_to_mutate = "src/taipanstack/security/sanitizers.py,src/taipanstack/security/validators.py,src/taipanstack/security/guards.py,src/taipanstack/utils/retry.py,src/taipanstack/utils/circuit_breaker.py"
229
+ tests_dir = "tests/test_property_sanitizers.py,tests/test_security_validators.py,tests/test_security_guards.py,tests/test_security_ssrf.py,tests/test_utils_retry.py,tests/test_utils_circuit_breaker.py"
229
230
  runner = "python -m pytest -x -q --tb=no --timeout=10 --no-cov"
230
231
  dict_synonyms = "Struct, NamedStruct"
232
+
@@ -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.4"
8
+ __version__ = "0.3.6"
9
9
 
10
10
  from taipanstack.config.version_config import (
11
11
  VersionRecommendations,
@@ -5,7 +5,6 @@ This module generates configuration files (pyproject.toml, pre-commit, etc.)
5
5
  with proper validation and templating.
6
6
  """
7
7
 
8
-
9
8
  from pathlib import Path
10
9
 
11
10
  from taipanstack.config.models import StackConfig
@@ -7,7 +7,6 @@ versions, enabling performance improvements while maintaining stability.
7
7
  Following Stack pillars: Security, Stability, Simplicity, Scalability, Compatibility.
8
8
  """
9
9
 
10
-
11
10
  import gc
12
11
  import logging
13
12
  import os
@@ -22,7 +22,6 @@ Example:
22
22
 
23
23
  """
24
24
 
25
-
26
25
  import functools
27
26
  import inspect
28
27
  from collections.abc import Callable, Coroutine, Iterable
@@ -34,7 +33,9 @@ __all__ = [
34
33
  "Err",
35
34
  "Ok",
36
35
  "Result",
36
+ "and_then_async",
37
37
  "collect_results",
38
+ "map_async",
38
39
  "safe",
39
40
  "safe_from",
40
41
  "unwrap_or",
@@ -260,3 +261,112 @@ def unwrap_or_else(
260
261
  return value
261
262
  case Err(error):
262
263
  return default_fn(error)
264
+
265
+
266
+ @overload
267
+ async def map_async(
268
+ result: Ok[T],
269
+ func: Callable[[T], Coroutine[Any, Any, U]],
270
+ ) -> Result[U, E]: ... # pragma: no cover
271
+
272
+
273
+ @overload
274
+ async def map_async(
275
+ result: Err[E],
276
+ func: Callable[[T], Coroutine[Any, Any, U]],
277
+ ) -> Err[E]: ... # pragma: no cover
278
+
279
+
280
+ @overload
281
+ async def map_async(
282
+ result: Result[T, E],
283
+ func: Callable[[T], Coroutine[Any, Any, U]],
284
+ ) -> Result[U, E]: ... # pragma: no cover
285
+
286
+
287
+ async def map_async(
288
+ result: Result[T, E],
289
+ func: Callable[[T], Coroutine[Any, Any, U]],
290
+ ) -> Result[U, E]:
291
+ """Asynchronously apply a function to the value of an Ok result.
292
+
293
+ If the result is Err, returns it unchanged.
294
+
295
+ Args:
296
+ result: The Result to process.
297
+ func: Coroutine function to apply to the Ok value.
298
+
299
+ Returns:
300
+ New Result containing the processed value or original error.
301
+
302
+ Example:
303
+ >>> async def process(x: int) -> str:
304
+ ... return str(x * 2)
305
+ >>> await map_async(Ok(5), process)
306
+ Ok('10')
307
+ >>> await map_async(Err("fail"), process)
308
+ Err('fail')
309
+
310
+ """
311
+ match result:
312
+ case Ok(value):
313
+ return Ok(await func(value))
314
+ case Err() as err:
315
+ return err
316
+
317
+
318
+ @overload
319
+ async def and_then_async(
320
+ result: Ok[T],
321
+ func: Callable[[T], Coroutine[Any, Any, Result[U, E]]],
322
+ ) -> Result[U, E]: ... # pragma: no cover
323
+
324
+
325
+ @overload
326
+ async def and_then_async(
327
+ result: Err[E],
328
+ func: Callable[[T], Coroutine[Any, Any, Result[U, E]]],
329
+ ) -> Err[E]: ... # pragma: no cover
330
+
331
+
332
+ @overload
333
+ async def and_then_async(
334
+ result: Result[T, E],
335
+ func: Callable[[T], Coroutine[Any, Any, Result[U, E]]],
336
+ ) -> Result[U, E]: ... # pragma: no cover
337
+
338
+
339
+ async def and_then_async(
340
+ result: Result[T, E],
341
+ func: Callable[[T], Coroutine[Any, Any, Result[U, E]]],
342
+ ) -> Result[U, E]:
343
+ """Asynchronously chain operations that return Results.
344
+
345
+ If the result is Ok, asynchronously applies `func` and returns its Result.
346
+ If the result is Err, returns it unchanged.
347
+
348
+ Args:
349
+ result: The Result to process.
350
+ func: Coroutine function taking the Ok value and returning a new Result.
351
+
352
+ Returns:
353
+ The new Result from `func` or the original error.
354
+
355
+ Example:
356
+ >>> async def fetch_user(uid: int) -> Result[str, ValueError]:
357
+ ... if uid == 1:
358
+ ... return Ok("Alice")
359
+ ... return Err(ValueError("User not found"))
360
+ >>> await and_then_async(Ok(1), fetch_user)
361
+ Ok('Alice')
362
+ >>> await and_then_async(Ok(2), fetch_user)
363
+ Err(ValueError('User not found'))
364
+ >>> await and_then_async(Err(ValueError("No DB")), fetch_user)
365
+ Err(ValueError('No DB'))
366
+
367
+ """
368
+ match result:
369
+ case Ok(value):
370
+ return await func(value)
371
+ case Err() as err:
372
+ return err
@@ -16,12 +16,19 @@ from taipanstack.security.guards import (
16
16
  guard_path_traversal,
17
17
  guard_ssrf,
18
18
  )
19
+ from taipanstack.security.jwt import decode_jwt, encode_jwt
19
20
  from taipanstack.security.password import hash_password, verify_password
20
21
  from taipanstack.security.sanitizers import (
21
22
  sanitize_filename,
22
23
  sanitize_path,
23
24
  sanitize_string,
24
25
  )
26
+ from taipanstack.security.types import (
27
+ SafeCommand,
28
+ SafePath,
29
+ SafeProjectName,
30
+ SafeUrl,
31
+ )
25
32
  from taipanstack.security.validators import (
26
33
  validate_email,
27
34
  validate_project_name,
@@ -32,9 +39,15 @@ from taipanstack.security.validators import (
32
39
  __all__ = [
33
40
  # Decorators
34
41
  # Guards
42
+ "SafeCommand",
43
+ "SafePath",
44
+ "SafeProjectName",
45
+ "SafeUrl",
35
46
  "SecurityError",
36
47
  "ValidationError",
48
+ "decode_jwt",
37
49
  "deprecated",
50
+ "encode_jwt",
38
51
  "guard_command_injection",
39
52
  "guard_env_variable",
40
53
  "guard_exceptions",
@@ -43,7 +56,6 @@ __all__ = [
43
56
  "guard_ssrf",
44
57
  "hash_password",
45
58
  "require_type",
46
- "verify_password",
47
59
  # Sanitizers
48
60
  "sanitize_filename",
49
61
  "sanitize_path",
@@ -55,4 +67,5 @@ __all__ = [
55
67
  "validate_project_name",
56
68
  "validate_python_version",
57
69
  "validate_url",
70
+ "verify_password",
58
71
  ]
@@ -6,7 +6,6 @@ timeout control, and other security patterns. Compatible with
6
6
  any Python framework (Flask, FastAPI, Django, etc.).
7
7
  """
8
8
 
9
-
10
9
  import functools
11
10
  import signal
12
11
  import sys
@@ -6,7 +6,6 @@ and programming errors that can occur from incorrect AI-generated code.
6
6
  All guards raise SecurityError on violation.
7
7
  """
8
8
 
9
-
10
9
  import ipaddress
11
10
  import os
12
11
  import re
@@ -0,0 +1,92 @@
1
+ """
2
+ Secure JWT Utility module.
3
+
4
+ Provides explicitly secure wrappers around PyJWT encoding and decoding,
5
+ enforcing strict validation of algorithms, expiration, and audience claims.
6
+ All operations return ``Result`` types.
7
+ """
8
+
9
+ from collections.abc import Iterable
10
+ from typing import Any
11
+
12
+ import jwt
13
+ from jwt.exceptions import PyJWTError
14
+
15
+ from taipanstack.core.result import safe_from
16
+
17
+ __all__ = ["decode_jwt", "encode_jwt"]
18
+
19
+
20
+ @safe_from(PyJWTError, ValueError)
21
+ def encode_jwt(
22
+ payload: dict[str, Any],
23
+ secret_key: str,
24
+ algorithm: str = "HS256",
25
+ ) -> str:
26
+ """Encode a payload into a JWT securely.
27
+
28
+ Explicitly rejects the "none" algorithm to prevent bypass vulnerabilities.
29
+
30
+ Args:
31
+ payload: Dictionary containing the JWT claims.
32
+ secret_key: The secret key for signing the token.
33
+ algorithm: The signing algorithm (default "HS256").
34
+
35
+ Returns:
36
+ The encoded JWT string.
37
+
38
+ Raises:
39
+ ValueError: If the "none" algorithm is specified.
40
+ PyJWTError: If encoding fails.
41
+
42
+ """
43
+ if str(algorithm).strip().lower() == "none":
44
+ raise ValueError('Algorithm "none" is explicitly disallowed.')
45
+
46
+ return jwt.encode(payload, secret_key, algorithm=algorithm)
47
+
48
+
49
+ @safe_from(PyJWTError, ValueError)
50
+ def decode_jwt(
51
+ token: str,
52
+ secret_key: str,
53
+ algorithms: list[str],
54
+ audience: str | Iterable[str],
55
+ ) -> dict[str, Any]:
56
+ """Decode a JWT securely with strict claim validation.
57
+
58
+ Enforces that 'exp' (expiration) and 'aud' (audience) claims are present
59
+ and validated. Explicitly rejects the "none" algorithm.
60
+
61
+ Args:
62
+ token: The encoded JWT string.
63
+ secret_key: The secret key for verifying the signature.
64
+ algorithms: List of exactly accepted algorithms.
65
+ audience: The expected audience(s).
66
+
67
+ Returns:
68
+ The decoded payload dictionary.
69
+
70
+ Raises:
71
+ ValueError: If the "none" algorithm is present in the `algorithms` list.
72
+ PyJWTError: If the token is invalid, expired, or has incorrect claims.
73
+
74
+ """
75
+ if "none" in [str(alg).strip().lower() for alg in algorithms]:
76
+ raise ValueError('Algorithm "none" is explicitly disallowed for decoding.')
77
+
78
+ # We enforce 'exp' and 'aud' through PyJWT's options parameter
79
+ options = {
80
+ "require": ["exp", "aud"],
81
+ "verify_signature": True,
82
+ "verify_exp": True,
83
+ "verify_aud": True,
84
+ }
85
+
86
+ return jwt.decode(
87
+ token,
88
+ secret_key,
89
+ algorithms=algorithms,
90
+ audience=audience,
91
+ options=options, # type: ignore[arg-type]
92
+ )
@@ -64,7 +64,7 @@ def verify_password(password: str | SecretStr, password_hash: str) -> bool:
64
64
 
65
65
  try:
66
66
  parts = password_hash.split("$")
67
- if len(parts) != 4:
67
+ if len(parts) != 4: # noqa: PLR2004
68
68
  return False
69
69
 
70
70
  algorithm, iterations_str, salt_hex, hash_hex = parts
@@ -5,7 +5,6 @@ Provides functions to sanitize strings, filenames, and paths
5
5
  to remove potentially dangerous characters.
6
6
  """
7
7
 
8
-
9
8
  import re
10
9
  import unicodedata
11
10
  from pathlib import Path
@@ -0,0 +1,133 @@
1
+ """
2
+ Pydantic-compatible security types.
3
+
4
+ Provide ``Annotated`` type aliases that integrate TaipanStack's
5
+ runtime security guards with Pydantic v2 validation, enabling
6
+ declarative, type-safe input validation inside ``BaseModel``
7
+ definitions.
8
+ """
9
+
10
+ from typing import Annotated
11
+
12
+ from pydantic.functional_validators import AfterValidator
13
+
14
+ from taipanstack.core.result import Err, Ok
15
+ from taipanstack.security.guards import (
16
+ SecurityError,
17
+ guard_command_injection,
18
+ guard_path_traversal,
19
+ guard_ssrf,
20
+ )
21
+ from taipanstack.security.validators import (
22
+ validate_project_name,
23
+ validate_url,
24
+ )
25
+
26
+
27
+ def _validate_safe_url(url: str) -> str:
28
+ """Validate a URL is safe from SSRF attacks.
29
+
30
+ Args:
31
+ url: The URL string to validate.
32
+
33
+ Returns:
34
+ The validated URL.
35
+
36
+ Raises:
37
+ ValueError: If the URL fails SSRF validation.
38
+
39
+ """
40
+ match guard_ssrf(url):
41
+ case Ok(val):
42
+ return val
43
+ case Err(err):
44
+ raise ValueError(str(err)) from err
45
+
46
+
47
+ def _validate_safe_path(path: str) -> str:
48
+ """Validate a path is safe from traversal attacks.
49
+
50
+ Args:
51
+ path: The path string to validate.
52
+
53
+ Returns:
54
+ The validated path string.
55
+
56
+ Raises:
57
+ ValueError: If path traversal is detected.
58
+
59
+ """
60
+ try:
61
+ guard_path_traversal(path)
62
+ except SecurityError as exc:
63
+ raise ValueError(str(exc)) from exc
64
+ return path
65
+
66
+
67
+ def _validate_safe_command(command: str) -> str:
68
+ """Validate a command string is safe from injection attacks.
69
+
70
+ Args:
71
+ command: The command string to validate.
72
+
73
+ Returns:
74
+ The validated command string.
75
+
76
+ Raises:
77
+ ValueError: If command injection is detected.
78
+
79
+ """
80
+ try:
81
+ guard_command_injection([command])
82
+ except SecurityError as exc:
83
+ raise ValueError(str(exc)) from exc
84
+ return command
85
+
86
+
87
+ def _validate_safe_project_name(name: str) -> str:
88
+ """Validate a project name conforms to safe naming rules.
89
+
90
+ Args:
91
+ name: The project name to validate.
92
+
93
+ Returns:
94
+ The validated project name.
95
+
96
+ Raises:
97
+ ValueError: If the name is invalid.
98
+
99
+ """
100
+ return validate_project_name(name)
101
+
102
+
103
+ def _validate_safe_url_format(url: str) -> str:
104
+ """Validate a URL has a correct format and allowed scheme.
105
+
106
+ Args:
107
+ url: The URL string to validate.
108
+
109
+ Returns:
110
+ The validated URL.
111
+
112
+ Raises:
113
+ ValueError: If the URL format is invalid.
114
+
115
+ """
116
+ return validate_url(url)
117
+
118
+
119
+ SafeUrl = Annotated[
120
+ str,
121
+ AfterValidator(_validate_safe_url_format),
122
+ AfterValidator(_validate_safe_url),
123
+ ]
124
+ """A URL validated for correct format and safe from SSRF attacks."""
125
+
126
+ SafePath = Annotated[str, AfterValidator(_validate_safe_path)]
127
+ """A filesystem path validated against path-traversal attacks."""
128
+
129
+ SafeCommand = Annotated[str, AfterValidator(_validate_safe_command)]
130
+ """A command string validated against shell-injection attacks."""
131
+
132
+ SafeProjectName = Annotated[str, AfterValidator(_validate_safe_project_name)]
133
+ """A project name validated for safe naming conventions."""
@@ -5,7 +5,6 @@ Provides validation functions for common input types like email,
5
5
  project names, URLs, etc. All validators raise ValueError on invalid input.
6
6
  """
7
7
 
8
-
9
8
  import re
10
9
  from ipaddress import IPv4Address, IPv6Address, ip_address
11
10
  from typing import Literal
@@ -1,20 +1,37 @@
1
1
  """Utility modules for Stack."""
2
2
 
3
3
  from .filesystem import ensure_dir, safe_read, safe_write
4
- from .logging import get_logger, setup_logging
4
+ from .logging import (
5
+ REDACTED_VALUE,
6
+ SENSITIVE_KEY_PATTERNS,
7
+ get_correlation_id,
8
+ get_logger,
9
+ log_operation,
10
+ set_correlation_id,
11
+ setup_logging,
12
+ )
13
+ from .rate_limit import RateLimiter, RateLimitError, rate_limit
5
14
  from .retry import Retrier, RetryConfig, RetryError, retry
6
15
  from .subprocess import SafeCommandResult, run_safe_command
7
16
 
8
17
  __all__ = (
18
+ "REDACTED_VALUE",
19
+ "SENSITIVE_KEY_PATTERNS",
20
+ "RateLimitError",
21
+ "RateLimiter",
9
22
  "Retrier",
10
23
  "RetryConfig",
11
24
  "RetryError",
12
25
  "SafeCommandResult",
13
26
  "ensure_dir",
27
+ "get_correlation_id",
14
28
  "get_logger",
29
+ "log_operation",
30
+ "rate_limit",
15
31
  "retry",
16
32
  "run_safe_command",
17
33
  "safe_read",
18
34
  "safe_write",
35
+ "set_correlation_id",
19
36
  "setup_logging",
20
37
  )
@@ -3,21 +3,22 @@ Circuit Breaker pattern implementation.
3
3
 
4
4
  Provides protection against cascading failures by temporarily
5
5
  blocking calls to a failing service. Compatible with any
6
- Python framework.
6
+ Python framework (sync and async).
7
7
  """
8
8
 
9
-
10
9
  import functools
10
+ import inspect
11
11
  import logging
12
12
  import threading
13
13
  import time
14
14
  from collections.abc import Callable
15
15
  from dataclasses import dataclass, field
16
16
  from enum import Enum
17
- from typing import ParamSpec, TypeVar
17
+ from typing import Any, ParamSpec, TypeVar, cast
18
18
 
19
19
  P = ParamSpec("P")
20
20
  R = TypeVar("R")
21
+ F = TypeVar("F", bound=Callable[..., Any])
21
22
 
22
23
  logger = logging.getLogger("taipanstack.utils.circuit_breaker")
23
24
 
@@ -90,7 +91,7 @@ class CircuitBreaker:
90
91
 
91
92
  Monitors function calls and opens the circuit when too many
92
93
  failures occur, preventing further calls until the service
93
- recovers.
94
+ recovers. Supports both sync and async functions.
94
95
 
95
96
  Example:
96
97
  >>> breaker = CircuitBreaker(failure_threshold=3)
@@ -276,11 +277,30 @@ class CircuitBreaker:
276
277
  self._state.success_count = 0
277
278
  logger.info("Circuit %s manually reset", self.name)
278
279
 
279
- def __call__(self, func: Callable[P, R]) -> Callable[P, R]:
280
- """Decorate a function with circuit breaker protection."""
280
+ def __call__(self, func: F) -> F:
281
+ """Decorate a sync or async function with circuit breaker protection."""
282
+ if inspect.iscoroutinefunction(func):
283
+
284
+ @functools.wraps(func)
285
+ async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
286
+ if not self._should_attempt():
287
+ raise CircuitBreakerError(
288
+ f"Circuit {self.name} is open",
289
+ state=self._state.state,
290
+ )
291
+
292
+ try:
293
+ result = await func(*args, **kwargs)
294
+ self._record_success()
295
+ return result
296
+ except self.config.failure_exceptions as e:
297
+ self._record_failure(e)
298
+ raise
299
+
300
+ return cast(F, async_wrapper)
281
301
 
282
302
  @functools.wraps(func)
283
- def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
303
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
284
304
  if not self._should_attempt():
285
305
  raise CircuitBreakerError(
286
306
  f"Circuit {self.name} is open",
@@ -295,7 +315,7 @@ class CircuitBreaker:
295
315
  self._record_failure(e)
296
316
  raise
297
317
 
298
- return wrapper
318
+ return cast(F, wrapper)
299
319
 
300
320
 
301
321
  def circuit_breaker(
@@ -307,8 +327,8 @@ def circuit_breaker(
307
327
  failure_exceptions: tuple[type[Exception], ...] = (Exception,),
308
328
  name: str | None = None,
309
329
  on_state_change: Callable[[CircuitState, CircuitState], None] | None = None,
310
- ) -> Callable[[Callable[P, R]], Callable[P, R]]:
311
- """Decorator to apply circuit breaker pattern.
330
+ ) -> Callable[[F], F]:
331
+ """Decorate a sync or async function with circuit breaker pattern.
312
332
 
313
333
  Args:
314
334
  failure_threshold: Failures before opening circuit.
@@ -337,7 +357,7 @@ def circuit_breaker(
337
357
 
338
358
  """
339
359
 
340
- def decorator(func: Callable[P, R]) -> Callable[P, R]:
360
+ def decorator(func: F) -> F:
341
361
  breaker = CircuitBreaker(
342
362
  failure_threshold=failure_threshold,
343
363
  success_threshold=success_threshold,
@@ -5,10 +5,11 @@ Provides a configured logger with support for structured output,
5
5
  context propagation, and proper formatting.
6
6
  """
7
7
 
8
-
9
8
  import logging
10
9
  import sys
10
+ from collections.abc import MutableMapping
11
11
  from contextlib import contextmanager
12
+ from contextvars import ContextVar
12
13
  from datetime import UTC, datetime
13
14
  from typing import Any, Literal
14
15
 
@@ -27,6 +28,94 @@ JSON_FORMAT = (
27
28
  '"logger": "%(name)s", "message": "%(message)s"}'
28
29
  )
29
30
 
31
+ SENSITIVE_KEY_PATTERNS: tuple[str, ...] = (
32
+ "password",
33
+ "secret",
34
+ "token",
35
+ "authorization",
36
+ "api_key",
37
+ )
38
+
39
+ REDACTED_VALUE = "***REDACTED***"
40
+
41
+
42
+ def mask_sensitive_data_processor(
43
+ logger: Any, # noqa: ARG001
44
+ method: str, # noqa: ARG001
45
+ event_dict: dict[str, Any],
46
+ ) -> dict[str, Any]:
47
+ """Mask sensitive data in structlog event dictionaries.
48
+
49
+ Intercept the *event_dict* produced by structlog and replace the
50
+ value of any key whose name contains a sensitive substring with
51
+ ``"***REDACTED***"``. Matching is case-insensitive.
52
+
53
+ Args:
54
+ logger: The wrapped logger object (unused, required by structlog).
55
+ method: The name of the log method called (unused, required by structlog).
56
+ event_dict: The structured event dictionary.
57
+
58
+ Returns:
59
+ The event dictionary with sensitive values masked.
60
+
61
+ """
62
+ 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
68
+ return event_dict
69
+
70
+
71
+ # Context variables for observability
72
+ correlation_id_var: ContextVar[str | None] = ContextVar(
73
+ "correlation_id",
74
+ default=None,
75
+ )
76
+
77
+
78
+ def get_correlation_id() -> str | None:
79
+ """Get the current correlation ID.
80
+
81
+ Returns:
82
+ The correlation ID if set, otherwise None.
83
+
84
+ """
85
+ return correlation_id_var.get()
86
+
87
+
88
+ def set_correlation_id(correlation_id: str | None) -> None:
89
+ """Set the correlation ID for the current context.
90
+
91
+ Args:
92
+ correlation_id: The correlation ID string, or None to clear.
93
+
94
+ """
95
+ correlation_id_var.set(correlation_id)
96
+
97
+
98
+ def correlation_id_processor(
99
+ logger: Any, # noqa: ARG001
100
+ method: str, # noqa: ARG001
101
+ event_dict: MutableMapping[str, Any],
102
+ ) -> MutableMapping[str, Any]:
103
+ """Structlog processor to inject correlation ID into events.
104
+
105
+ Args:
106
+ logger: The wrapped logger object.
107
+ method: The name of the log method called.
108
+ event_dict: The structured event dictionary.
109
+
110
+ Returns:
111
+ The event dictionary with correlation_id injected if sets.
112
+
113
+ """
114
+ correlation_id = get_correlation_id()
115
+ if correlation_id is not None:
116
+ event_dict["correlation_id"] = correlation_id
117
+ return event_dict
118
+
30
119
 
31
120
  class StackLogger:
32
121
  """Enhanced logger with context support.
@@ -219,6 +308,7 @@ def setup_logging(
219
308
  structlog.stdlib.add_logger_name,
220
309
  structlog.stdlib.add_log_level,
221
310
  structlog.processors.TimeStamper(fmt="iso"),
311
+ correlation_id_processor,
222
312
  structlog.processors.StackInfoRenderer(),
223
313
  structlog.processors.format_exc_info,
224
314
  structlog.processors.UnicodeDecoder(),
@@ -6,7 +6,6 @@ application performance and health. Compatible with any
6
6
  Python framework.
7
7
  """
8
8
 
9
-
10
9
  import functools
11
10
  import logging
12
11
  import threading
@@ -0,0 +1,150 @@
1
+ """
2
+ Rate limiting utilities.
3
+
4
+ Provides an in-memory token-bucket based rate limiting decorator
5
+ for both synchronous and asynchronous functions. The decorator
6
+ returns a ``Result`` type encapsulating the original return value
7
+ or a ``RateLimitError`` error.
8
+ """
9
+
10
+ import functools
11
+ import inspect
12
+ import time
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__ = ["RateLimitError", "RateLimiter", "rate_limit"]
19
+
20
+ P = ParamSpec("P")
21
+ T = TypeVar("T")
22
+
23
+
24
+ class RateLimitError(Exception):
25
+ """Exception raised when a rate limit is exceeded."""
26
+
27
+ def __init__(self, message: str = "Rate limit exceeded") -> None:
28
+ """Initialize the RateLimitError.
29
+
30
+ Args:
31
+ message: The error message to display.Defaults to "Rate limit exceeded".
32
+
33
+ """
34
+ super().__init__(message)
35
+
36
+
37
+ class RateLimiter:
38
+ """Token bucket rate limiter logic."""
39
+
40
+ def __init__(self, max_calls: int, time_window: float) -> None:
41
+ """Initialize the token bucket.
42
+
43
+ Args:
44
+ max_calls: The maximum number of calls allowed in the time window.
45
+ time_window: The time window in seconds.
46
+
47
+ """
48
+ if max_calls <= 0 or time_window <= 0:
49
+ raise ValueError("max_calls and time_window must be > 0.0")
50
+ self.capacity: float = float(max_calls)
51
+ self.time_window: float = float(time_window)
52
+ self.tokens: float = self.capacity
53
+ self.last_update: float = time.monotonic()
54
+
55
+ def consume(self) -> bool:
56
+ """Try to consume a single token.
57
+
58
+ Returns:
59
+ True if a token was consumed (allow), False otherwise (limit exceeded).
60
+
61
+ """
62
+ now = time.monotonic()
63
+ elapsed = now - self.last_update
64
+ self.last_update = now
65
+
66
+ # Add tokens for elapsed time based on fill rate
67
+ self.tokens += elapsed * (self.capacity / self.time_window)
68
+ self.tokens = min(self.tokens, self.capacity)
69
+
70
+ if self.tokens >= 1.0:
71
+ self.tokens -= 1.0
72
+ return True
73
+ return False
74
+
75
+
76
+ class RateLimitDecorator(Protocol):
77
+ """Protocol for the rate limit decorator."""
78
+
79
+ @overload
80
+ def __call__(
81
+ self, func: Callable[P, T]
82
+ ) -> Callable[P, Result[T, RateLimitError]]: ... # pragma: no cover
83
+
84
+ @overload
85
+ def __call__(
86
+ self, func: Callable[P, Coroutine[Any, Any, T]]
87
+ ) -> Callable[
88
+ P, Coroutine[Any, Any, Result[T, RateLimitError]]
89
+ ]: ... # pragma: no cover
90
+
91
+
92
+ def rate_limit(
93
+ max_calls: int,
94
+ time_window: float,
95
+ ) -> RateLimitDecorator:
96
+ """Decorate a function to apply rate limiting.
97
+
98
+ If the rate limit is exceeded, the wrapped function immediately returns
99
+ an ``Err(RateLimitError)``. Uses an in-memory token bucket strategy.
100
+
101
+ Args:
102
+ max_calls: Maximum function executions allowed in the defined window.
103
+ time_window: Time window size in seconds.
104
+
105
+ Returns:
106
+ Decorated function returning a ``Result[T, RateLimitError]``.
107
+
108
+ Example:
109
+ >>> @rate_limit(max_calls=2, time_window=1.0)
110
+ ... def fetch_data() -> str:
111
+ ... return "data"
112
+ >>> fetch_data()
113
+ Ok('data')
114
+ >>> fetch_data()
115
+ Ok('data')
116
+ >>> fetch_data()
117
+ Err(RateLimitError('Rate limit exceeded'))
118
+
119
+ """
120
+
121
+ def decorator(
122
+ func: Callable[P, T] | Callable[P, Coroutine[Any, Any, T]],
123
+ ) -> (
124
+ Callable[P, Result[T, RateLimitError]]
125
+ | Callable[P, Coroutine[Any, Any, Result[T, RateLimitError]]]
126
+ ):
127
+ limiter = RateLimiter(max_calls, time_window)
128
+
129
+ if inspect.iscoroutinefunction(func):
130
+
131
+ @functools.wraps(func)
132
+ async def async_wrapper(
133
+ *args: P.args,
134
+ **kwargs: P.kwargs,
135
+ ) -> Result[T, RateLimitError]:
136
+ if not limiter.consume():
137
+ return Err(RateLimitError())
138
+ return Ok(await func(*args, **kwargs))
139
+
140
+ return async_wrapper
141
+
142
+ @functools.wraps(func)
143
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> Result[T, RateLimitError]:
144
+ if not limiter.consume():
145
+ return Err(RateLimitError())
146
+ return Ok(func(*args, **kwargs)) # type: ignore[arg-type]
147
+
148
+ return wrapper
149
+
150
+ return decorator # type: ignore[return-value]
@@ -6,18 +6,20 @@ with configurable backoff strategies. Compatible with any
6
6
  Python framework (sync and async).
7
7
  """
8
8
 
9
-
9
+ import asyncio
10
10
  import functools
11
+ import inspect
11
12
  import logging
12
13
  import secrets
13
14
  import time
14
15
  from collections.abc import Callable
15
16
  from dataclasses import dataclass
16
17
  from types import TracebackType
17
- from typing import ParamSpec, TypeVar
18
+ from typing import Any, ParamSpec, TypeVar, cast
18
19
 
19
20
  P = ParamSpec("P")
20
21
  R = TypeVar("R")
22
+ F = TypeVar("F", bound=Callable[..., Any])
21
23
 
22
24
  logger = logging.getLogger("taipanstack.utils.retry")
23
25
 
@@ -42,6 +44,8 @@ class RetryConfig:
42
44
  exponential_base: Base for exponential backoff (2 = double each time).
43
45
  jitter: Whether to add random jitter to delays.
44
46
  jitter_factor: Maximum jitter as fraction of delay (0.1 = 10%).
47
+ log_retries: Whether to emit standard log messages.
48
+ on_retry: Optional callback invoked on each retry.
45
49
 
46
50
  """
47
51
 
@@ -51,6 +55,8 @@ class RetryConfig:
51
55
  exponential_base: float = 2.0
52
56
  jitter: bool = True
53
57
  jitter_factor: float = 0.1
58
+ log_retries: bool = True
59
+ on_retry: Callable[[int, int, Exception, float], None] | None = None
54
60
 
55
61
 
56
62
  class RetryError(Exception):
@@ -107,6 +113,69 @@ def calculate_delay(
107
113
  return max(0, delay)
108
114
 
109
115
 
116
+ def _log_retry_attempt(
117
+ func_name: str,
118
+ attempt: int,
119
+ exc: Exception,
120
+ delay: float,
121
+ config: RetryConfig,
122
+ ) -> None:
123
+ """Log a retry attempt via callback, structlog, or stdlib logger.
124
+
125
+ Args:
126
+ func_name: Name of the retried function.
127
+ attempt: Current attempt number.
128
+ exc: The exception that triggered the retry.
129
+ delay: Delay in seconds before the next attempt.
130
+ config: Retry configuration.
131
+
132
+ """
133
+ if config.log_retries:
134
+ logger.info(
135
+ "Attempt %d/%d failed for %s: %s. Retrying in %.2f seconds...",
136
+ attempt,
137
+ config.max_attempts,
138
+ func_name,
139
+ str(exc),
140
+ delay,
141
+ )
142
+
143
+ # Invoke callback or emit structured log if no callback set
144
+ if config.on_retry is not None:
145
+ config.on_retry(attempt, config.max_attempts, exc, delay)
146
+ elif _HAS_STRUCTLOG and _structlog_logger is not None: # pragma: no branch
147
+ _structlog_logger.warning(
148
+ "retry_attempted",
149
+ function=func_name,
150
+ attempt=attempt,
151
+ max_attempts=config.max_attempts,
152
+ error=str(exc),
153
+ delay_seconds=round(delay, 3),
154
+ )
155
+
156
+
157
+ def _log_all_failed(
158
+ func_name: str,
159
+ exc: Exception,
160
+ config: RetryConfig,
161
+ ) -> None:
162
+ """Log when all retry attempts have been exhausted.
163
+
164
+ Args:
165
+ func_name: Name of the retried function.
166
+ exc: The last exception raised.
167
+ config: Retry configuration.
168
+
169
+ """
170
+ if config.log_retries:
171
+ logger.warning(
172
+ "All %d attempts failed for %s: %s",
173
+ config.max_attempts,
174
+ func_name,
175
+ str(exc),
176
+ )
177
+
178
+
110
179
  def retry(
111
180
  *,
112
181
  max_attempts: int = 3,
@@ -118,11 +187,12 @@ def retry(
118
187
  reraise: bool = True,
119
188
  log_retries: bool = True,
120
189
  on_retry: Callable[[int, int, Exception, float], None] | None = None,
121
- ) -> Callable[[Callable[P, R]], Callable[P, R]]:
122
- """Retry a function with exponential backoff.
190
+ ) -> Callable[[F], F]:
191
+ """Retry a sync or async function with exponential backoff.
123
192
 
124
193
  Automatically retries the decorated function when specified
125
194
  exceptions are raised, with configurable backoff strategy.
195
+ Detects coroutine functions and preserves their async nature.
126
196
 
127
197
  Args:
128
198
  max_attempts: Maximum number of retry attempts.
@@ -156,11 +226,60 @@ def retry(
156
226
  max_delay=max_delay,
157
227
  exponential_base=exponential_base,
158
228
  jitter=jitter,
229
+ log_retries=log_retries,
230
+ on_retry=on_retry,
159
231
  )
160
232
 
161
- def decorator(func: Callable[P, R]) -> Callable[P, R]:
233
+ def decorator(func: F) -> F:
234
+ if inspect.iscoroutinefunction(func):
235
+
236
+ @functools.wraps(func)
237
+ async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
238
+ last_exception: Exception | None = None
239
+
240
+ for attempt in range(1, max_attempts + 1): # pragma: no branch
241
+ try:
242
+ return await func(*args, **kwargs)
243
+ except on as e:
244
+ last_exception = e
245
+
246
+ if attempt == max_attempts:
247
+ _log_all_failed(
248
+ func.__name__,
249
+ e,
250
+ config,
251
+ )
252
+ break
253
+
254
+ delay = calculate_delay(attempt, config)
255
+ _log_retry_attempt(
256
+ func.__name__,
257
+ attempt,
258
+ e,
259
+ delay,
260
+ config,
261
+ )
262
+ await asyncio.sleep(delay)
263
+
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,
277
+ )
278
+
279
+ return cast(F, async_wrapper)
280
+
162
281
  @functools.wraps(func)
163
- def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
282
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
164
283
  last_exception: Exception | None = None
165
284
 
166
285
  for attempt in range(1, max_attempts + 1): # pragma: no branch
@@ -170,45 +289,22 @@ def retry(
170
289
  last_exception = e
171
290
 
172
291
  if attempt == max_attempts:
173
- # Last attempt failed
174
- if log_retries:
175
- logger.warning(
176
- "All %d attempts failed for %s: %s",
177
- max_attempts,
178
- func.__name__,
179
- str(e),
180
- )
292
+ _log_all_failed(
293
+ func.__name__,
294
+ e,
295
+ config,
296
+ )
181
297
  break
182
298
 
183
299
  # Calculate delay and wait
184
300
  delay = calculate_delay(attempt, config)
185
-
186
- if log_retries:
187
- logger.info(
188
- "Attempt %d/%d failed for %s: %s. "
189
- "Retrying in %.2f seconds...",
190
- attempt,
191
- max_attempts,
192
- func.__name__,
193
- str(e),
194
- delay,
195
- )
196
-
197
- # Invoke callback or emit structured log if no callback set
198
- if on_retry is not None:
199
- on_retry(attempt, max_attempts, e, delay)
200
- elif (
201
- _HAS_STRUCTLOG and _structlog_logger is not None
202
- ): # pragma: no branch
203
- _structlog_logger.warning(
204
- "retry_attempted",
205
- function=func.__name__,
206
- attempt=attempt,
207
- max_attempts=max_attempts,
208
- error=str(e),
209
- delay_seconds=round(delay, 3),
210
- )
211
-
301
+ _log_retry_attempt(
302
+ func.__name__,
303
+ attempt,
304
+ e,
305
+ delay,
306
+ config,
307
+ )
212
308
  time.sleep(delay)
213
309
 
214
310
  # All attempts failed
@@ -226,7 +322,7 @@ def retry(
226
322
  last_exception=last_exception,
227
323
  )
228
324
 
229
- return wrapper
325
+ return cast(F, wrapper)
230
326
 
231
327
  return decorator
232
328
 
@@ -5,9 +5,8 @@ Provides secure wrappers around subprocess execution with
5
5
  command validation, timeout handling, and retry logic.
6
6
  """
7
7
 
8
-
9
8
  import shutil
10
- import subprocess
9
+ import subprocess # nosec B404
11
10
  import time
12
11
  from collections.abc import Sequence
13
12
  from dataclasses import dataclass
@@ -190,7 +189,7 @@ def run_safe_command(
190
189
  start_time = time.time()
191
190
 
192
191
  try:
193
- result = subprocess.run(
192
+ result = subprocess.run( # nosec B603
194
193
  validated_cmd,
195
194
  cwd=cwd,
196
195
  timeout=timeout,
File without changes
File without changes