taipanstack 0.3.5__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.5 → taipanstack-0.3.6}/PKG-INFO +2 -1
  2. {taipanstack-0.3.5 → taipanstack-0.3.6}/pyproject.toml +2 -1
  3. {taipanstack-0.3.5 → taipanstack-0.3.6}/src/taipanstack/__init__.py +1 -1
  4. {taipanstack-0.3.5 → taipanstack-0.3.6}/src/taipanstack/core/result.py +111 -0
  5. {taipanstack-0.3.5 → taipanstack-0.3.6}/src/taipanstack/security/__init__.py +3 -0
  6. taipanstack-0.3.6/src/taipanstack/security/jwt.py +92 -0
  7. {taipanstack-0.3.5 → taipanstack-0.3.6}/src/taipanstack/utils/__init__.py +10 -2
  8. {taipanstack-0.3.5 → taipanstack-0.3.6}/src/taipanstack/utils/logging.py +52 -0
  9. taipanstack-0.3.6/src/taipanstack/utils/rate_limit.py +150 -0
  10. {taipanstack-0.3.5 → taipanstack-0.3.6}/src/taipanstack/utils/retry.py +21 -27
  11. {taipanstack-0.3.5 → taipanstack-0.3.6}/src/taipanstack/utils/subprocess.py +2 -2
  12. {taipanstack-0.3.5 → taipanstack-0.3.6}/LICENSE +0 -0
  13. {taipanstack-0.3.5 → taipanstack-0.3.6}/README.md +0 -0
  14. {taipanstack-0.3.5 → taipanstack-0.3.6}/src/taipanstack/config/__init__.py +0 -0
  15. {taipanstack-0.3.5 → taipanstack-0.3.6}/src/taipanstack/config/generators.py +0 -0
  16. {taipanstack-0.3.5 → taipanstack-0.3.6}/src/taipanstack/config/models.py +0 -0
  17. {taipanstack-0.3.5 → taipanstack-0.3.6}/src/taipanstack/config/version_config.py +0 -0
  18. {taipanstack-0.3.5 → taipanstack-0.3.6}/src/taipanstack/core/__init__.py +0 -0
  19. {taipanstack-0.3.5 → taipanstack-0.3.6}/src/taipanstack/core/compat.py +0 -0
  20. {taipanstack-0.3.5 → taipanstack-0.3.6}/src/taipanstack/core/optimizations.py +0 -0
  21. {taipanstack-0.3.5 → taipanstack-0.3.6}/src/taipanstack/security/decorators.py +0 -0
  22. {taipanstack-0.3.5 → taipanstack-0.3.6}/src/taipanstack/security/guards.py +0 -0
  23. {taipanstack-0.3.5 → taipanstack-0.3.6}/src/taipanstack/security/password.py +0 -0
  24. {taipanstack-0.3.5 → taipanstack-0.3.6}/src/taipanstack/security/sanitizers.py +0 -0
  25. {taipanstack-0.3.5 → taipanstack-0.3.6}/src/taipanstack/security/types.py +0 -0
  26. {taipanstack-0.3.5 → taipanstack-0.3.6}/src/taipanstack/security/validators.py +0 -0
  27. {taipanstack-0.3.5 → taipanstack-0.3.6}/src/taipanstack/utils/circuit_breaker.py +0 -0
  28. {taipanstack-0.3.5 → taipanstack-0.3.6}/src/taipanstack/utils/filesystem.py +0 -0
  29. {taipanstack-0.3.5 → taipanstack-0.3.6}/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.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.5"
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]
@@ -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.6"
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",
@@ -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]
@@ -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,23 +156,21 @@ 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
  )
@@ -228,6 +226,8 @@ def retry(
228
226
  max_delay=max_delay,
229
227
  exponential_base=exponential_base,
230
228
  jitter=jitter,
229
+ log_retries=log_retries,
230
+ on_retry=on_retry,
231
231
  )
232
232
 
233
233
  def decorator(func: F) -> F:
@@ -246,9 +246,8 @@ def retry(
246
246
  if attempt == max_attempts:
247
247
  _log_all_failed(
248
248
  func.__name__,
249
- max_attempts,
250
249
  e,
251
- log_retries,
250
+ config,
252
251
  )
253
252
  break
254
253
 
@@ -256,11 +255,9 @@ def retry(
256
255
  _log_retry_attempt(
257
256
  func.__name__,
258
257
  attempt,
259
- max_attempts,
260
258
  e,
261
259
  delay,
262
- log_retries,
263
- on_retry,
260
+ config,
264
261
  )
265
262
  await asyncio.sleep(delay)
266
263
 
@@ -294,9 +291,8 @@ def retry(
294
291
  if attempt == max_attempts:
295
292
  _log_all_failed(
296
293
  func.__name__,
297
- max_attempts,
298
294
  e,
299
- log_retries,
295
+ config,
300
296
  )
301
297
  break
302
298
 
@@ -305,11 +301,9 @@ def retry(
305
301
  _log_retry_attempt(
306
302
  func.__name__,
307
303
  attempt,
308
- max_attempts,
309
304
  e,
310
305
  delay,
311
- log_retries,
312
- on_retry,
306
+ config,
313
307
  )
314
308
  time.sleep(delay)
315
309
 
@@ -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,
File without changes
File without changes