taipanstack 0.3.5__tar.gz → 0.3.7__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.5 → taipanstack-0.3.7}/PKG-INFO +2 -1
  2. {taipanstack-0.3.5 → taipanstack-0.3.7}/pyproject.toml +2 -1
  3. {taipanstack-0.3.5 → taipanstack-0.3.7}/src/taipanstack/__init__.py +1 -1
  4. {taipanstack-0.3.5 → taipanstack-0.3.7}/src/taipanstack/core/result.py +111 -0
  5. {taipanstack-0.3.5 → taipanstack-0.3.7}/src/taipanstack/security/__init__.py +3 -0
  6. {taipanstack-0.3.5 → taipanstack-0.3.7}/src/taipanstack/security/decorators.py +6 -7
  7. {taipanstack-0.3.5 → taipanstack-0.3.7}/src/taipanstack/security/guards.py +18 -12
  8. taipanstack-0.3.7/src/taipanstack/security/jwt.py +92 -0
  9. {taipanstack-0.3.5 → taipanstack-0.3.7}/src/taipanstack/utils/__init__.py +10 -2
  10. {taipanstack-0.3.5 → taipanstack-0.3.7}/src/taipanstack/utils/logging.py +52 -0
  11. taipanstack-0.3.7/src/taipanstack/utils/rate_limit.py +150 -0
  12. {taipanstack-0.3.5 → taipanstack-0.3.7}/src/taipanstack/utils/retry.py +64 -54
  13. {taipanstack-0.3.5 → taipanstack-0.3.7}/src/taipanstack/utils/subprocess.py +5 -3
  14. {taipanstack-0.3.5 → taipanstack-0.3.7}/LICENSE +0 -0
  15. {taipanstack-0.3.5 → taipanstack-0.3.7}/README.md +0 -0
  16. {taipanstack-0.3.5 → taipanstack-0.3.7}/src/taipanstack/config/__init__.py +0 -0
  17. {taipanstack-0.3.5 → taipanstack-0.3.7}/src/taipanstack/config/generators.py +0 -0
  18. {taipanstack-0.3.5 → taipanstack-0.3.7}/src/taipanstack/config/models.py +0 -0
  19. {taipanstack-0.3.5 → taipanstack-0.3.7}/src/taipanstack/config/version_config.py +0 -0
  20. {taipanstack-0.3.5 → taipanstack-0.3.7}/src/taipanstack/core/__init__.py +0 -0
  21. {taipanstack-0.3.5 → taipanstack-0.3.7}/src/taipanstack/core/compat.py +0 -0
  22. {taipanstack-0.3.5 → taipanstack-0.3.7}/src/taipanstack/core/optimizations.py +0 -0
  23. {taipanstack-0.3.5 → taipanstack-0.3.7}/src/taipanstack/security/password.py +0 -0
  24. {taipanstack-0.3.5 → taipanstack-0.3.7}/src/taipanstack/security/sanitizers.py +0 -0
  25. {taipanstack-0.3.5 → taipanstack-0.3.7}/src/taipanstack/security/types.py +0 -0
  26. {taipanstack-0.3.5 → taipanstack-0.3.7}/src/taipanstack/security/validators.py +0 -0
  27. {taipanstack-0.3.5 → taipanstack-0.3.7}/src/taipanstack/utils/circuit_breaker.py +0 -0
  28. {taipanstack-0.3.5 → taipanstack-0.3.7}/src/taipanstack/utils/filesystem.py +0 -0
  29. {taipanstack-0.3.5 → taipanstack-0.3.7}/src/taipanstack/utils/metrics.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: taipanstack
3
- Version: 0.3.5
3
+ Version: 0.3.7
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.5"
3
+ version = "0.3.7"
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]
@@ -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.5"
8
+ __version__ = "0.3.7"
9
9
 
10
10
  from taipanstack.config.version_config import (
11
11
  VersionRecommendations,
@@ -33,7 +33,9 @@ __all__ = [
33
33
  "Err",
34
34
  "Ok",
35
35
  "Result",
36
+ "and_then_async",
36
37
  "collect_results",
38
+ "map_async",
37
39
  "safe",
38
40
  "safe_from",
39
41
  "unwrap_or",
@@ -259,3 +261,112 @@ def unwrap_or_else(
259
261
  return value
260
262
  case Err(error):
261
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,6 +16,7 @@ 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,
@@ -44,7 +45,9 @@ __all__ = [
44
45
  "SafeUrl",
45
46
  "SecurityError",
46
47
  "ValidationError",
48
+ "decode_jwt",
47
49
  "deprecated",
50
+ "encode_jwt",
48
51
  "guard_command_injection",
49
52
  "guard_env_variable",
50
53
  "guard_exceptions",
@@ -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"\.\.",
@@ -152,9 +153,10 @@ def guard_path_traversal(
152
153
 
153
154
  # Check for explicit traversal patterns before resolution
154
155
  path_str = str(path)
156
+ path_str_lower = path_str.lower()
155
157
 
156
158
  for pattern in _TRAVERSAL_PATTERNS:
157
- if pattern.lower() in path_str.lower():
159
+ if pattern in path_str_lower:
158
160
  raise SecurityError(
159
161
  f"Path traversal pattern detected: {pattern}",
160
162
  guard_name="path_traversal",
@@ -163,7 +165,8 @@ def guard_path_traversal(
163
165
 
164
166
  # Resolve the path
165
167
  try:
166
- resolved = path.resolve() if path.is_absolute() else (base_dir / path).resolve()
168
+ full_path = path if path.is_absolute() else (base_dir / path)
169
+ resolved = full_path.resolve()
167
170
  except (OSError, ValueError) as e:
168
171
  raise SecurityError(
169
172
  f"Invalid path: {e}",
@@ -181,15 +184,18 @@ def guard_path_traversal(
181
184
  ) from e
182
185
 
183
186
  # 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
- )
187
+ if not allow_symlinks:
188
+ current = full_path
189
+ # Only check components from the user-provided path, not the base_dir
190
+ while current not in (base_dir, current.parent):
191
+ # We don't check .exists() because it returns False for broken symlinks
192
+ if current.is_symlink():
193
+ raise SecurityError(
194
+ "Symlinks are not allowed",
195
+ guard_name="path_traversal",
196
+ value=str(current),
197
+ )
198
+ current = current.parent
193
199
 
194
200
  return resolved
195
201
 
@@ -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
+ )
@@ -4,26 +4,34 @@ from .filesystem import ensure_dir, safe_read, safe_write
4
4
  from .logging import (
5
5
  REDACTED_VALUE,
6
6
  SENSITIVE_KEY_PATTERNS,
7
+ get_correlation_id,
7
8
  get_logger,
8
- mask_sensitive_data_processor,
9
+ log_operation,
10
+ set_correlation_id,
9
11
  setup_logging,
10
12
  )
13
+ from .rate_limit import RateLimiter, RateLimitError, rate_limit
11
14
  from .retry import Retrier, RetryConfig, RetryError, retry
12
15
  from .subprocess import SafeCommandResult, run_safe_command
13
16
 
14
17
  __all__ = (
15
18
  "REDACTED_VALUE",
16
19
  "SENSITIVE_KEY_PATTERNS",
20
+ "RateLimitError",
21
+ "RateLimiter",
17
22
  "Retrier",
18
23
  "RetryConfig",
19
24
  "RetryError",
20
25
  "SafeCommandResult",
21
26
  "ensure_dir",
27
+ "get_correlation_id",
22
28
  "get_logger",
23
- "mask_sensitive_data_processor",
29
+ "log_operation",
30
+ "rate_limit",
24
31
  "retry",
25
32
  "run_safe_command",
26
33
  "safe_read",
27
34
  "safe_write",
35
+ "set_correlation_id",
28
36
  "setup_logging",
29
37
  )
@@ -7,7 +7,9 @@ context propagation, and proper formatting.
7
7
 
8
8
  import logging
9
9
  import sys
10
+ from collections.abc import MutableMapping
10
11
  from contextlib import contextmanager
12
+ from contextvars import ContextVar
11
13
  from datetime import UTC, datetime
12
14
  from typing import Any, Literal
13
15
 
@@ -66,6 +68,55 @@ def mask_sensitive_data_processor(
66
68
  return event_dict
67
69
 
68
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
+
119
+
69
120
  class StackLogger:
70
121
  """Enhanced logger with context support.
71
122
 
@@ -257,6 +308,7 @@ def setup_logging(
257
308
  structlog.stdlib.add_logger_name,
258
309
  structlog.stdlib.add_log_level,
259
310
  structlog.processors.TimeStamper(fmt="iso"),
311
+ correlation_id_processor,
260
312
  structlog.processors.StackInfoRenderer(),
261
313
  structlog.processors.format_exc_info,
262
314
  structlog.processors.UnicodeDecoder(),
@@ -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]
@@ -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")
@@ -44,6 +44,8 @@ class RetryConfig:
44
44
  exponential_base: Base for exponential backoff (2 = double each time).
45
45
  jitter: Whether to add random jitter to delays.
46
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.
47
49
 
48
50
  """
49
51
 
@@ -53,6 +55,8 @@ class RetryConfig:
53
55
  exponential_base: float = 2.0
54
56
  jitter: bool = True
55
57
  jitter_factor: float = 0.1
58
+ log_retries: bool = True
59
+ on_retry: Callable[[int, int, Exception, float], None] | None = None
56
60
 
57
61
 
58
62
  class RetryError(Exception):
@@ -112,43 +116,39 @@ def calculate_delay(
112
116
  def _log_retry_attempt(
113
117
  func_name: str,
114
118
  attempt: int,
115
- max_attempts: int,
116
119
  exc: Exception,
117
120
  delay: float,
118
- log_retries: bool,
119
- on_retry: Callable[[int, int, Exception, float], None] | None,
121
+ config: RetryConfig,
120
122
  ) -> None:
121
123
  """Log a retry attempt via callback, structlog, or stdlib logger.
122
124
 
123
125
  Args:
124
126
  func_name: Name of the retried function.
125
127
  attempt: Current attempt number.
126
- max_attempts: Maximum number of attempts.
127
128
  exc: The exception that triggered the retry.
128
129
  delay: Delay in seconds before the next attempt.
129
- log_retries: Whether to emit standard log messages.
130
- on_retry: Optional user callback.
130
+ config: Retry configuration.
131
131
 
132
132
  """
133
- if log_retries:
133
+ if config.log_retries:
134
134
  logger.info(
135
135
  "Attempt %d/%d failed for %s: %s. Retrying in %.2f seconds...",
136
136
  attempt,
137
- max_attempts,
137
+ config.max_attempts,
138
138
  func_name,
139
139
  str(exc),
140
140
  delay,
141
141
  )
142
142
 
143
143
  # Invoke callback or emit structured log if no callback set
144
- if on_retry is not None:
145
- on_retry(attempt, max_attempts, exc, delay)
144
+ if config.on_retry is not None:
145
+ config.on_retry(attempt, config.max_attempts, exc, delay)
146
146
  elif _HAS_STRUCTLOG and _structlog_logger is not None: # pragma: no branch
147
147
  _structlog_logger.warning(
148
148
  "retry_attempted",
149
149
  function=func_name,
150
150
  attempt=attempt,
151
- max_attempts=max_attempts,
151
+ max_attempts=config.max_attempts,
152
152
  error=str(exc),
153
153
  delay_seconds=round(delay, 3),
154
154
  )
@@ -156,28 +156,58 @@ def _log_retry_attempt(
156
156
 
157
157
  def _log_all_failed(
158
158
  func_name: str,
159
- max_attempts: int,
160
159
  exc: Exception,
161
- log_retries: bool,
160
+ config: RetryConfig,
162
161
  ) -> None:
163
162
  """Log when all retry attempts have been exhausted.
164
163
 
165
164
  Args:
166
165
  func_name: Name of the retried function.
167
- max_attempts: Maximum number of attempts.
168
166
  exc: The last exception raised.
169
- log_retries: Whether to emit standard log messages.
167
+ config: Retry configuration.
170
168
 
171
169
  """
172
- if log_retries:
170
+ if config.log_retries:
173
171
  logger.warning(
174
172
  "All %d attempts failed for %s: %s",
175
- max_attempts,
173
+ config.max_attempts,
176
174
  func_name,
177
175
  str(exc),
178
176
  )
179
177
 
180
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
+
181
211
  def retry(
182
212
  *,
183
213
  max_attempts: int = 3,
@@ -228,6 +258,8 @@ def retry(
228
258
  max_delay=max_delay,
229
259
  exponential_base=exponential_base,
230
260
  jitter=jitter,
261
+ log_retries=log_retries,
262
+ on_retry=on_retry,
231
263
  )
232
264
 
233
265
  def decorator(func: F) -> F:
@@ -246,9 +278,8 @@ def retry(
246
278
  if attempt == max_attempts:
247
279
  _log_all_failed(
248
280
  func.__name__,
249
- max_attempts,
250
281
  e,
251
- log_retries,
282
+ config,
252
283
  )
253
284
  break
254
285
 
@@ -256,27 +287,17 @@ def retry(
256
287
  _log_retry_attempt(
257
288
  func.__name__,
258
289
  attempt,
259
- max_attempts,
260
290
  e,
261
291
  delay,
262
- log_retries,
263
- on_retry,
292
+ config,
264
293
  )
265
294
  await asyncio.sleep(delay)
266
295
 
267
- # All attempts failed
268
- if reraise and last_exception is not None:
269
- raise RetryError(
270
- f"All {max_attempts} attempts failed for {func.__name__}",
271
- attempts=max_attempts,
272
- last_exception=last_exception,
273
- ) from last_exception
274
-
275
- # Should never reach here if reraise=True
276
- raise RetryError(
277
- f"All {max_attempts} attempts failed for {func.__name__}",
278
- attempts=max_attempts,
279
- last_exception=last_exception,
296
+ _raise_retry_error(
297
+ func.__name__,
298
+ max_attempts,
299
+ reraise,
300
+ last_exception,
280
301
  )
281
302
 
282
303
  return cast(F, async_wrapper)
@@ -294,9 +315,8 @@ def retry(
294
315
  if attempt == max_attempts:
295
316
  _log_all_failed(
296
317
  func.__name__,
297
- max_attempts,
298
318
  e,
299
- log_retries,
319
+ config,
300
320
  )
301
321
  break
302
322
 
@@ -305,27 +325,17 @@ def retry(
305
325
  _log_retry_attempt(
306
326
  func.__name__,
307
327
  attempt,
308
- max_attempts,
309
328
  e,
310
329
  delay,
311
- log_retries,
312
- on_retry,
330
+ config,
313
331
  )
314
332
  time.sleep(delay)
315
333
 
316
- # All attempts failed
317
- if reraise and last_exception is not None:
318
- raise RetryError(
319
- f"All {max_attempts} attempts failed for {func.__name__}",
320
- attempts=max_attempts,
321
- last_exception=last_exception,
322
- ) from last_exception
323
-
324
- # Should never reach here if reraise=True
325
- raise RetryError(
326
- f"All {max_attempts} attempts failed for {func.__name__}",
327
- attempts=max_attempts,
328
- last_exception=last_exception,
334
+ _raise_retry_error(
335
+ func.__name__,
336
+ max_attempts,
337
+ reraise,
338
+ last_exception,
329
339
  )
330
340
 
331
341
  return cast(F, wrapper)
@@ -6,7 +6,7 @@ command validation, timeout handling, and retry logic.
6
6
  """
7
7
 
8
8
  import shutil
9
- import subprocess
9
+ import subprocess # nosec B404
10
10
  import time
11
11
  from collections.abc import Sequence
12
12
  from dataclasses import dataclass
@@ -189,7 +189,7 @@ def run_safe_command(
189
189
  start_time = time.time()
190
190
 
191
191
  try:
192
- result = subprocess.run(
192
+ result = subprocess.run( # nosec B603
193
193
  validated_cmd,
194
194
  cwd=cwd,
195
195
  timeout=timeout,
@@ -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