taipanstack 0.3.4__tar.gz → 0.3.5__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 (27) hide show
  1. {taipanstack-0.3.4 → taipanstack-0.3.5}/PKG-INFO +1 -1
  2. {taipanstack-0.3.4 → taipanstack-0.3.5}/pyproject.toml +4 -3
  3. {taipanstack-0.3.4 → taipanstack-0.3.5}/src/taipanstack/__init__.py +1 -1
  4. {taipanstack-0.3.4 → taipanstack-0.3.5}/src/taipanstack/config/generators.py +0 -1
  5. {taipanstack-0.3.4 → taipanstack-0.3.5}/src/taipanstack/core/optimizations.py +0 -1
  6. {taipanstack-0.3.4 → taipanstack-0.3.5}/src/taipanstack/core/result.py +0 -1
  7. {taipanstack-0.3.4 → taipanstack-0.3.5}/src/taipanstack/security/__init__.py +11 -1
  8. {taipanstack-0.3.4 → taipanstack-0.3.5}/src/taipanstack/security/decorators.py +0 -1
  9. {taipanstack-0.3.4 → taipanstack-0.3.5}/src/taipanstack/security/guards.py +0 -1
  10. {taipanstack-0.3.4 → taipanstack-0.3.5}/src/taipanstack/security/password.py +1 -1
  11. {taipanstack-0.3.4 → taipanstack-0.3.5}/src/taipanstack/security/sanitizers.py +0 -1
  12. taipanstack-0.3.5/src/taipanstack/security/types.py +133 -0
  13. {taipanstack-0.3.4 → taipanstack-0.3.5}/src/taipanstack/security/validators.py +0 -1
  14. {taipanstack-0.3.4 → taipanstack-0.3.5}/src/taipanstack/utils/__init__.py +10 -1
  15. {taipanstack-0.3.4 → taipanstack-0.3.5}/src/taipanstack/utils/circuit_breaker.py +31 -11
  16. {taipanstack-0.3.4 → taipanstack-0.3.5}/src/taipanstack/utils/logging.py +39 -1
  17. {taipanstack-0.3.4 → taipanstack-0.3.5}/src/taipanstack/utils/metrics.py +0 -1
  18. {taipanstack-0.3.4 → taipanstack-0.3.5}/src/taipanstack/utils/retry.py +144 -42
  19. {taipanstack-0.3.4 → taipanstack-0.3.5}/src/taipanstack/utils/subprocess.py +0 -1
  20. {taipanstack-0.3.4 → taipanstack-0.3.5}/LICENSE +0 -0
  21. {taipanstack-0.3.4 → taipanstack-0.3.5}/README.md +0 -0
  22. {taipanstack-0.3.4 → taipanstack-0.3.5}/src/taipanstack/config/__init__.py +0 -0
  23. {taipanstack-0.3.4 → taipanstack-0.3.5}/src/taipanstack/config/models.py +0 -0
  24. {taipanstack-0.3.4 → taipanstack-0.3.5}/src/taipanstack/config/version_config.py +0 -0
  25. {taipanstack-0.3.4 → taipanstack-0.3.5}/src/taipanstack/core/__init__.py +0 -0
  26. {taipanstack-0.3.4 → taipanstack-0.3.5}/src/taipanstack/core/compat.py +0 -0
  27. {taipanstack-0.3.4 → taipanstack-0.3.5}/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.5
4
4
  Summary: TaipanStack - Modular, secure, and scalable Python stack for robust development
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "taipanstack"
3
- version = "0.3.4"
3
+ version = "0.3.5"
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"}
@@ -224,7 +224,8 @@ fail-under = 80
224
224
  verbose = 1
225
225
 
226
226
  [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"
227
+ 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"
228
+ 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
229
  runner = "python -m pytest -x -q --tb=no --timeout=10 --no-cov"
230
230
  dict_synonyms = "Struct, NamedStruct"
231
+
@@ -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.5"
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
@@ -22,6 +22,12 @@ from taipanstack.security.sanitizers import (
22
22
  sanitize_path,
23
23
  sanitize_string,
24
24
  )
25
+ from taipanstack.security.types import (
26
+ SafeCommand,
27
+ SafePath,
28
+ SafeProjectName,
29
+ SafeUrl,
30
+ )
25
31
  from taipanstack.security.validators import (
26
32
  validate_email,
27
33
  validate_project_name,
@@ -32,6 +38,10 @@ from taipanstack.security.validators import (
32
38
  __all__ = [
33
39
  # Decorators
34
40
  # Guards
41
+ "SafeCommand",
42
+ "SafePath",
43
+ "SafeProjectName",
44
+ "SafeUrl",
35
45
  "SecurityError",
36
46
  "ValidationError",
37
47
  "deprecated",
@@ -43,7 +53,6 @@ __all__ = [
43
53
  "guard_ssrf",
44
54
  "hash_password",
45
55
  "require_type",
46
- "verify_password",
47
56
  # Sanitizers
48
57
  "sanitize_filename",
49
58
  "sanitize_path",
@@ -55,4 +64,5 @@ __all__ = [
55
64
  "validate_project_name",
56
65
  "validate_python_version",
57
66
  "validate_url",
67
+ "verify_password",
58
68
  ]
@@ -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
@@ -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,17 +1,26 @@
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_logger,
8
+ mask_sensitive_data_processor,
9
+ setup_logging,
10
+ )
5
11
  from .retry import Retrier, RetryConfig, RetryError, retry
6
12
  from .subprocess import SafeCommandResult, run_safe_command
7
13
 
8
14
  __all__ = (
15
+ "REDACTED_VALUE",
16
+ "SENSITIVE_KEY_PATTERNS",
9
17
  "Retrier",
10
18
  "RetryConfig",
11
19
  "RetryError",
12
20
  "SafeCommandResult",
13
21
  "ensure_dir",
14
22
  "get_logger",
23
+ "mask_sensitive_data_processor",
15
24
  "retry",
16
25
  "run_safe_command",
17
26
  "safe_read",
@@ -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,7 +5,6 @@ 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
11
10
  from contextlib import contextmanager
@@ -27,6 +26,45 @@ JSON_FORMAT = (
27
26
  '"logger": "%(name)s", "message": "%(message)s"}'
28
27
  )
29
28
 
29
+ SENSITIVE_KEY_PATTERNS: tuple[str, ...] = (
30
+ "password",
31
+ "secret",
32
+ "token",
33
+ "authorization",
34
+ "api_key",
35
+ )
36
+
37
+ REDACTED_VALUE = "***REDACTED***"
38
+
39
+
40
+ def mask_sensitive_data_processor(
41
+ logger: Any, # noqa: ARG001
42
+ method: str, # noqa: ARG001
43
+ event_dict: dict[str, Any],
44
+ ) -> dict[str, Any]:
45
+ """Mask sensitive data in structlog event dictionaries.
46
+
47
+ Intercept the *event_dict* produced by structlog and replace the
48
+ value of any key whose name contains a sensitive substring with
49
+ ``"***REDACTED***"``. Matching is case-insensitive.
50
+
51
+ Args:
52
+ logger: The wrapped logger object (unused, required by structlog).
53
+ method: The name of the log method called (unused, required by structlog).
54
+ event_dict: The structured event dictionary.
55
+
56
+ Returns:
57
+ The event dictionary with sensitive values masked.
58
+
59
+ """
60
+ for key in event_dict:
61
+ key_lower = key.lower()
62
+ for pattern in SENSITIVE_KEY_PATTERNS:
63
+ if pattern in key_lower:
64
+ event_dict[key] = REDACTED_VALUE
65
+ break
66
+ return event_dict
67
+
30
68
 
31
69
  class StackLogger:
32
70
  """Enhanced logger with context support.
@@ -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
@@ -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
 
@@ -107,6 +109,75 @@ def calculate_delay(
107
109
  return max(0, delay)
108
110
 
109
111
 
112
+ def _log_retry_attempt(
113
+ func_name: str,
114
+ attempt: int,
115
+ max_attempts: int,
116
+ exc: Exception,
117
+ delay: float,
118
+ log_retries: bool,
119
+ on_retry: Callable[[int, int, Exception, float], None] | None,
120
+ ) -> None:
121
+ """Log a retry attempt via callback, structlog, or stdlib logger.
122
+
123
+ Args:
124
+ func_name: Name of the retried function.
125
+ attempt: Current attempt number.
126
+ max_attempts: Maximum number of attempts.
127
+ exc: The exception that triggered the retry.
128
+ delay: Delay in seconds before the next attempt.
129
+ log_retries: Whether to emit standard log messages.
130
+ on_retry: Optional user callback.
131
+
132
+ """
133
+ if log_retries:
134
+ logger.info(
135
+ "Attempt %d/%d failed for %s: %s. Retrying in %.2f seconds...",
136
+ attempt,
137
+ 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 on_retry is not None:
145
+ on_retry(attempt, 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=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
+ max_attempts: int,
160
+ exc: Exception,
161
+ log_retries: bool,
162
+ ) -> None:
163
+ """Log when all retry attempts have been exhausted.
164
+
165
+ Args:
166
+ func_name: Name of the retried function.
167
+ max_attempts: Maximum number of attempts.
168
+ exc: The last exception raised.
169
+ log_retries: Whether to emit standard log messages.
170
+
171
+ """
172
+ if log_retries:
173
+ logger.warning(
174
+ "All %d attempts failed for %s: %s",
175
+ max_attempts,
176
+ func_name,
177
+ str(exc),
178
+ )
179
+
180
+
110
181
  def retry(
111
182
  *,
112
183
  max_attempts: int = 3,
@@ -118,11 +189,12 @@ def retry(
118
189
  reraise: bool = True,
119
190
  log_retries: bool = True,
120
191
  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.
192
+ ) -> Callable[[F], F]:
193
+ """Retry a sync or async function with exponential backoff.
123
194
 
124
195
  Automatically retries the decorated function when specified
125
196
  exceptions are raised, with configurable backoff strategy.
197
+ Detects coroutine functions and preserves their async nature.
126
198
 
127
199
  Args:
128
200
  max_attempts: Maximum number of retry attempts.
@@ -158,9 +230,59 @@ def retry(
158
230
  jitter=jitter,
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
+ max_attempts,
250
+ e,
251
+ log_retries,
252
+ )
253
+ break
254
+
255
+ delay = calculate_delay(attempt, config)
256
+ _log_retry_attempt(
257
+ func.__name__,
258
+ attempt,
259
+ max_attempts,
260
+ e,
261
+ delay,
262
+ log_retries,
263
+ on_retry,
264
+ )
265
+ await asyncio.sleep(delay)
266
+
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,
280
+ )
281
+
282
+ return cast(F, async_wrapper)
283
+
162
284
  @functools.wraps(func)
163
- def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
285
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
164
286
  last_exception: Exception | None = None
165
287
 
166
288
  for attempt in range(1, max_attempts + 1): # pragma: no branch
@@ -170,45 +292,25 @@ def retry(
170
292
  last_exception = e
171
293
 
172
294
  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
- )
295
+ _log_all_failed(
296
+ func.__name__,
297
+ max_attempts,
298
+ e,
299
+ log_retries,
300
+ )
181
301
  break
182
302
 
183
303
  # Calculate delay and wait
184
304
  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
-
305
+ _log_retry_attempt(
306
+ func.__name__,
307
+ attempt,
308
+ max_attempts,
309
+ e,
310
+ delay,
311
+ log_retries,
312
+ on_retry,
313
+ )
212
314
  time.sleep(delay)
213
315
 
214
316
  # All attempts failed
@@ -226,7 +328,7 @@ def retry(
226
328
  last_exception=last_exception,
227
329
  )
228
330
 
229
- return wrapper
331
+ return cast(F, wrapper)
230
332
 
231
333
  return decorator
232
334
 
@@ -5,7 +5,6 @@ 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
9
  import subprocess
11
10
  import time
File without changes
File without changes