taipanstack 0.3.3__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 (28) hide show
  1. {taipanstack-0.3.3 → taipanstack-0.3.5}/PKG-INFO +1 -1
  2. {taipanstack-0.3.3 → taipanstack-0.3.5}/pyproject.toml +4 -3
  3. {taipanstack-0.3.3 → taipanstack-0.3.5}/src/taipanstack/__init__.py +1 -10
  4. {taipanstack-0.3.3 → taipanstack-0.3.5}/src/taipanstack/config/generators.py +13 -17
  5. {taipanstack-0.3.3 → taipanstack-0.3.5}/src/taipanstack/core/__init__.py +0 -22
  6. {taipanstack-0.3.3 → taipanstack-0.3.5}/src/taipanstack/core/optimizations.py +0 -2
  7. {taipanstack-0.3.3 → taipanstack-0.3.5}/src/taipanstack/core/result.py +0 -2
  8. {taipanstack-0.3.3 → taipanstack-0.3.5}/src/taipanstack/security/__init__.py +13 -0
  9. {taipanstack-0.3.3 → taipanstack-0.3.5}/src/taipanstack/security/decorators.py +0 -2
  10. {taipanstack-0.3.3 → taipanstack-0.3.5}/src/taipanstack/security/guards.py +0 -2
  11. taipanstack-0.3.5/src/taipanstack/security/password.py +87 -0
  12. {taipanstack-0.3.3 → taipanstack-0.3.5}/src/taipanstack/security/sanitizers.py +0 -2
  13. taipanstack-0.3.5/src/taipanstack/security/types.py +133 -0
  14. {taipanstack-0.3.3 → taipanstack-0.3.5}/src/taipanstack/security/validators.py +1 -2
  15. taipanstack-0.3.5/src/taipanstack/utils/__init__.py +29 -0
  16. {taipanstack-0.3.3 → taipanstack-0.3.5}/src/taipanstack/utils/circuit_breaker.py +31 -12
  17. {taipanstack-0.3.3 → taipanstack-0.3.5}/src/taipanstack/utils/logging.py +41 -4
  18. {taipanstack-0.3.3 → taipanstack-0.3.5}/src/taipanstack/utils/metrics.py +4 -6
  19. {taipanstack-0.3.3 → taipanstack-0.3.5}/src/taipanstack/utils/retry.py +145 -44
  20. {taipanstack-0.3.3 → taipanstack-0.3.5}/src/taipanstack/utils/subprocess.py +1 -3
  21. taipanstack-0.3.3/src/taipanstack/utils/__init__.py +0 -24
  22. {taipanstack-0.3.3 → taipanstack-0.3.5}/LICENSE +0 -0
  23. {taipanstack-0.3.3 → taipanstack-0.3.5}/README.md +0 -0
  24. {taipanstack-0.3.3 → taipanstack-0.3.5}/src/taipanstack/config/__init__.py +0 -0
  25. {taipanstack-0.3.3 → taipanstack-0.3.5}/src/taipanstack/config/models.py +0 -0
  26. {taipanstack-0.3.3 → taipanstack-0.3.5}/src/taipanstack/config/version_config.py +0 -0
  27. {taipanstack-0.3.3 → taipanstack-0.3.5}/src/taipanstack/core/compat.py +0 -0
  28. {taipanstack-0.3.3 → 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.3
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.3"
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.3"
8
+ __version__ = "0.3.5"
9
9
 
10
10
  from taipanstack.config.version_config import (
11
11
  VersionRecommendations,
@@ -19,11 +19,6 @@ from taipanstack.core.compat import (
19
19
  get_features,
20
20
  get_python_info,
21
21
  )
22
- from taipanstack.core.optimizations import apply_optimizations, get_optimization_profile
23
- from taipanstack.security.guards import (
24
- guard_command_injection,
25
- guard_path_traversal,
26
- )
27
22
  from taipanstack.security.validators import (
28
23
  validate_email,
29
24
  validate_project_name,
@@ -36,13 +31,9 @@ __all__ = [
36
31
  "PY314",
37
32
  "PY_VERSION",
38
33
  "VersionRecommendations",
39
- "apply_optimizations",
40
34
  "get_features",
41
- "get_optimization_profile",
42
35
  "get_python_info",
43
36
  "get_version_recommendations",
44
- "guard_command_injection",
45
- "guard_path_traversal",
46
37
  "validate_email",
47
38
  "validate_project_name",
48
39
  "validate_python_version",
@@ -5,13 +5,9 @@ This module generates configuration files (pyproject.toml, pre-commit, etc.)
5
5
  with proper validation and templating.
6
6
  """
7
7
 
8
- from __future__ import annotations
9
-
10
8
  from pathlib import Path
11
- from typing import TYPE_CHECKING
12
9
 
13
- if TYPE_CHECKING:
14
- from taipanstack.config.models import StackConfig
10
+ from taipanstack.config.models import StackConfig
15
11
 
16
12
 
17
13
  def _generate_ruff_config(target_version: str) -> str:
@@ -167,48 +163,48 @@ def generate_pre_commit_config(config: StackConfig) -> str:
167
163
  Pre-commit configuration YAML string.
168
164
 
169
165
  """
170
- security_hooks = ""
166
+ security_hooks: list[str] = []
171
167
 
172
168
  if config.security.enable_bandit:
173
169
  severity = config.security.bandit_severity[0].upper()
174
- security_hooks += f"""
170
+ security_hooks.append(f"""
175
171
  - repo: https://github.com/PyCQA/bandit
176
172
  rev: '1.8.0'
177
173
  hooks:
178
174
  - id: bandit
179
175
  args: ["-r", ".", "-l{severity}"]
180
- """
176
+ """)
181
177
 
182
178
  if config.security.enable_safety:
183
- security_hooks += """
179
+ security_hooks.append("""
184
180
  - repo: https://github.com/pyupio/safety
185
181
  rev: '3.2.11'
186
182
  hooks:
187
183
  - id: safety
188
184
  args: ["check", "--json"]
189
- """
185
+ """)
190
186
 
191
187
  if config.security.enable_semgrep:
192
- security_hooks += """
188
+ security_hooks.append("""
193
189
  - repo: https://github.com/semgrep/pre-commit
194
190
  rev: 'v1.99.0'
195
191
  hooks:
196
192
  - id: semgrep
197
193
  args: ['--config=auto']
198
- """
194
+ """)
199
195
 
200
196
  if config.security.enable_detect_secrets:
201
- security_hooks += """
197
+ security_hooks.append("""
202
198
  - repo: https://github.com/Yelp/detect-secrets
203
199
  rev: 'v1.5.0'
204
200
  hooks:
205
201
  - id: detect-secrets
206
202
  args: ['--baseline', '.secrets.baseline']
207
- """
203
+ """)
208
204
 
209
205
  # Add pip-audit for paranoid mode
210
206
  if config.security.level == "paranoid":
211
- security_hooks += """
207
+ security_hooks.append("""
212
208
  - repo: https://github.com/trailofbits/pip-audit
213
209
  rev: 'v2.7.3'
214
210
  hooks:
@@ -223,7 +219,7 @@ def generate_pre_commit_config(config: StackConfig) -> str:
223
219
  rev: 'v2.3.3'
224
220
  hooks:
225
221
  - id: tryceratops
226
- """
222
+ """)
227
223
 
228
224
  return f"""# Stack v2.0 Pre-commit Configuration
229
225
  # Security Level: {config.security.level}
@@ -251,7 +247,7 @@ repos:
251
247
  hooks:
252
248
  - id: mypy
253
249
  additional_dependencies: [types-all, pydantic]
254
- {security_hooks}"""
250
+ {"".join(security_hooks)}"""
255
251
 
256
252
 
257
253
  def generate_dependabot_config() -> str:
@@ -4,18 +4,6 @@ Provides core functionality including Result types, version compatibility,
4
4
  and optimization utilities.
5
5
  """
6
6
 
7
- from taipanstack.core.compat import (
8
- PY311,
9
- PY312,
10
- PY313,
11
- PY314,
12
- PY_VERSION,
13
- PythonFeatures,
14
- VersionTier,
15
- get_features,
16
- get_python_info,
17
- is_experimental_enabled,
18
- )
19
7
  from taipanstack.core.optimizations import (
20
8
  OptimizationProfile,
21
9
  OptimizationResult,
@@ -26,22 +14,12 @@ from taipanstack.core.optimizations import (
26
14
  from taipanstack.core.result import Err, Ok, Result
27
15
 
28
16
  __all__ = [
29
- "PY311",
30
- "PY312",
31
- "PY313",
32
- "PY314",
33
- "PY_VERSION",
34
17
  "Err",
35
18
  "Ok",
36
19
  "OptimizationProfile",
37
20
  "OptimizationResult",
38
- "PythonFeatures",
39
21
  "Result",
40
- "VersionTier",
41
22
  "apply_optimizations",
42
- "get_features",
43
23
  "get_optimization_profile",
44
- "get_python_info",
45
24
  "get_recommended_thread_pool_size",
46
- "is_experimental_enabled",
47
25
  ]
@@ -7,8 +7,6 @@ versions, enabling performance improvements while maintaining stability.
7
7
  Following Stack pillars: Security, Stability, Simplicity, Scalability, Compatibility.
8
8
  """
9
9
 
10
- from __future__ import annotations
11
-
12
10
  import gc
13
11
  import logging
14
12
  import os
@@ -22,8 +22,6 @@ Example:
22
22
 
23
23
  """
24
24
 
25
- from __future__ import annotations
26
-
27
25
  import functools
28
26
  import inspect
29
27
  from collections.abc import Callable, Coroutine, Iterable
@@ -16,11 +16,18 @@ from taipanstack.security.guards import (
16
16
  guard_path_traversal,
17
17
  guard_ssrf,
18
18
  )
19
+ from taipanstack.security.password import hash_password, verify_password
19
20
  from taipanstack.security.sanitizers import (
20
21
  sanitize_filename,
21
22
  sanitize_path,
22
23
  sanitize_string,
23
24
  )
25
+ from taipanstack.security.types import (
26
+ SafeCommand,
27
+ SafePath,
28
+ SafeProjectName,
29
+ SafeUrl,
30
+ )
24
31
  from taipanstack.security.validators import (
25
32
  validate_email,
26
33
  validate_project_name,
@@ -31,6 +38,10 @@ from taipanstack.security.validators import (
31
38
  __all__ = [
32
39
  # Decorators
33
40
  # Guards
41
+ "SafeCommand",
42
+ "SafePath",
43
+ "SafeProjectName",
44
+ "SafeUrl",
34
45
  "SecurityError",
35
46
  "ValidationError",
36
47
  "deprecated",
@@ -40,6 +51,7 @@ __all__ = [
40
51
  "guard_file_extension",
41
52
  "guard_path_traversal",
42
53
  "guard_ssrf",
54
+ "hash_password",
43
55
  "require_type",
44
56
  # Sanitizers
45
57
  "sanitize_filename",
@@ -52,4 +64,5 @@ __all__ = [
52
64
  "validate_project_name",
53
65
  "validate_python_version",
54
66
  "validate_url",
67
+ "verify_password",
55
68
  ]
@@ -6,8 +6,6 @@ timeout control, and other security patterns. Compatible with
6
6
  any Python framework (Flask, FastAPI, Django, etc.).
7
7
  """
8
8
 
9
- from __future__ import annotations
10
-
11
9
  import functools
12
10
  import signal
13
11
  import sys
@@ -6,8 +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
- from __future__ import annotations
10
-
11
9
  import ipaddress
12
10
  import os
13
11
  import re
@@ -0,0 +1,87 @@
1
+ """
2
+ Password hashing and verification utilities.
3
+
4
+ This module provides functions for secure password management using
5
+ PBKDF2-HMAC-SHA256.
6
+ """
7
+
8
+ import hashlib
9
+ import secrets
10
+
11
+ from pydantic import SecretStr
12
+
13
+ # Constants for PBKDF2
14
+ ITERATIONS = 600_000
15
+ SALT_SIZE = 16
16
+ HASH_ALGORITHM = "sha256"
17
+ FORMAT = "pbkdf2_sha256"
18
+
19
+
20
+ def hash_password(password: str | SecretStr) -> str:
21
+ """
22
+ Hash a password using PBKDF2-HMAC-SHA256.
23
+
24
+ Args:
25
+ password: The plaintext password to hash.
26
+
27
+ Returns:
28
+ The hashed password in the format:
29
+ pbkdf2_sha256$<iterations>$<salt_hex>$<hash_hex>
30
+
31
+ """
32
+ if isinstance(password, SecretStr):
33
+ password_str = password.get_secret_value()
34
+ else:
35
+ password_str = password
36
+
37
+ salt = secrets.token_bytes(SALT_SIZE)
38
+ hash_bytes = hashlib.pbkdf2_hmac(
39
+ HASH_ALGORITHM,
40
+ password_str.encode("utf-8"),
41
+ salt,
42
+ ITERATIONS,
43
+ )
44
+
45
+ return f"{FORMAT}${ITERATIONS}${salt.hex()}${hash_bytes.hex()}"
46
+
47
+
48
+ def verify_password(password: str | SecretStr, password_hash: str) -> bool:
49
+ """
50
+ Verify a password against a PBKDF2-HMAC-SHA256 hash.
51
+
52
+ Args:
53
+ password: The plaintext password to verify.
54
+ password_hash: The stored password hash.
55
+
56
+ Returns:
57
+ True if the password matches the hash, False otherwise.
58
+
59
+ """
60
+ if isinstance(password, SecretStr):
61
+ password_str = password.get_secret_value()
62
+ else:
63
+ password_str = password
64
+
65
+ try:
66
+ parts = password_hash.split("$")
67
+ if len(parts) != 4: # noqa: PLR2004
68
+ return False
69
+
70
+ algorithm, iterations_str, salt_hex, hash_hex = parts
71
+ if algorithm != FORMAT:
72
+ return False
73
+
74
+ iterations = int(iterations_str)
75
+ salt = bytes.fromhex(salt_hex)
76
+ stored_hash = bytes.fromhex(hash_hex)
77
+
78
+ new_hash = hashlib.pbkdf2_hmac(
79
+ HASH_ALGORITHM,
80
+ password_str.encode("utf-8"),
81
+ salt,
82
+ iterations,
83
+ )
84
+
85
+ return secrets.compare_digest(new_hash, stored_hash)
86
+ except (ValueError, TypeError):
87
+ return False
@@ -5,8 +5,6 @@ Provides functions to sanitize strings, filenames, and paths
5
5
  to remove potentially dangerous characters.
6
6
  """
7
7
 
8
- from __future__ import annotations
9
-
10
8
  import re
11
9
  import unicodedata
12
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,8 +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
- from __future__ import annotations
9
-
10
8
  import re
11
9
  from ipaddress import IPv4Address, IPv6Address, ip_address
12
10
  from typing import Literal
@@ -283,6 +281,7 @@ def validate_url(
283
281
 
284
282
  try:
285
283
  parsed = urlparse(url)
284
+ _ = parsed.port
286
285
  except ValueError as e:
287
286
  msg = f"Invalid URL format: {e}"
288
287
  raise ValueError(msg) from e
@@ -0,0 +1,29 @@
1
+ """Utility modules for Stack."""
2
+
3
+ from .filesystem import ensure_dir, safe_read, safe_write
4
+ from .logging import (
5
+ REDACTED_VALUE,
6
+ SENSITIVE_KEY_PATTERNS,
7
+ get_logger,
8
+ mask_sensitive_data_processor,
9
+ setup_logging,
10
+ )
11
+ from .retry import Retrier, RetryConfig, RetryError, retry
12
+ from .subprocess import SafeCommandResult, run_safe_command
13
+
14
+ __all__ = (
15
+ "REDACTED_VALUE",
16
+ "SENSITIVE_KEY_PATTERNS",
17
+ "Retrier",
18
+ "RetryConfig",
19
+ "RetryError",
20
+ "SafeCommandResult",
21
+ "ensure_dir",
22
+ "get_logger",
23
+ "mask_sensitive_data_processor",
24
+ "retry",
25
+ "run_safe_command",
26
+ "safe_read",
27
+ "safe_write",
28
+ "setup_logging",
29
+ )
@@ -3,22 +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
- from __future__ import annotations
10
-
11
9
  import functools
10
+ import inspect
12
11
  import logging
13
12
  import threading
14
13
  import time
15
14
  from collections.abc import Callable
16
15
  from dataclasses import dataclass, field
17
16
  from enum import Enum
18
- from typing import ParamSpec, TypeVar
17
+ from typing import Any, ParamSpec, TypeVar, cast
19
18
 
20
19
  P = ParamSpec("P")
21
20
  R = TypeVar("R")
21
+ F = TypeVar("F", bound=Callable[..., Any])
22
22
 
23
23
  logger = logging.getLogger("taipanstack.utils.circuit_breaker")
24
24
 
@@ -91,7 +91,7 @@ class CircuitBreaker:
91
91
 
92
92
  Monitors function calls and opens the circuit when too many
93
93
  failures occur, preventing further calls until the service
94
- recovers.
94
+ recovers. Supports both sync and async functions.
95
95
 
96
96
  Example:
97
97
  >>> breaker = CircuitBreaker(failure_threshold=3)
@@ -277,11 +277,30 @@ class CircuitBreaker:
277
277
  self._state.success_count = 0
278
278
  logger.info("Circuit %s manually reset", self.name)
279
279
 
280
- def __call__(self, func: Callable[P, R]) -> Callable[P, R]:
281
- """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)
282
301
 
283
302
  @functools.wraps(func)
284
- def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
303
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
285
304
  if not self._should_attempt():
286
305
  raise CircuitBreakerError(
287
306
  f"Circuit {self.name} is open",
@@ -296,7 +315,7 @@ class CircuitBreaker:
296
315
  self._record_failure(e)
297
316
  raise
298
317
 
299
- return wrapper
318
+ return cast(F, wrapper)
300
319
 
301
320
 
302
321
  def circuit_breaker(
@@ -308,8 +327,8 @@ def circuit_breaker(
308
327
  failure_exceptions: tuple[type[Exception], ...] = (Exception,),
309
328
  name: str | None = None,
310
329
  on_state_change: Callable[[CircuitState, CircuitState], None] | None = None,
311
- ) -> Callable[[Callable[P, R]], Callable[P, R]]:
312
- """Decorator to apply circuit breaker pattern.
330
+ ) -> Callable[[F], F]:
331
+ """Decorate a sync or async function with circuit breaker pattern.
313
332
 
314
333
  Args:
315
334
  failure_threshold: Failures before opening circuit.
@@ -338,7 +357,7 @@ def circuit_breaker(
338
357
 
339
358
  """
340
359
 
341
- def decorator(func: Callable[P, R]) -> Callable[P, R]:
360
+ def decorator(func: F) -> F:
342
361
  breaker = CircuitBreaker(
343
362
  failure_threshold=failure_threshold,
344
363
  success_threshold=success_threshold,
@@ -5,8 +5,6 @@ Provides a configured logger with support for structured output,
5
5
  context propagation, and proper formatting.
6
6
  """
7
7
 
8
- from __future__ import annotations
9
-
10
8
  import logging
11
9
  import sys
12
10
  from contextlib import contextmanager
@@ -28,6 +26,45 @@ JSON_FORMAT = (
28
26
  '"logger": "%(name)s", "message": "%(message)s"}'
29
27
  )
30
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
+
31
68
 
32
69
  class StackLogger:
33
70
  """Enhanced logger with context support.
@@ -68,7 +105,7 @@ class StackLogger:
68
105
  self._logger.setLevel(getattr(logging, level.upper()))
69
106
  self._structured = False
70
107
 
71
- def bind(self, **context: Any) -> StackLogger:
108
+ def bind(self, **context: Any) -> "StackLogger":
72
109
  """Add context to logger.
73
110
 
74
111
  Args:
@@ -83,7 +120,7 @@ class StackLogger:
83
120
  self._logger = self._logger.bind(**context)
84
121
  return self
85
122
 
86
- def unbind(self, *keys: str) -> StackLogger:
123
+ def unbind(self, *keys: str) -> "StackLogger":
87
124
  """Remove context keys.
88
125
 
89
126
  Args:
@@ -6,8 +6,6 @@ application performance and health. Compatible with any
6
6
  Python framework.
7
7
  """
8
8
 
9
- from __future__ import annotations
10
-
11
9
  import functools
12
10
  import logging
13
11
  import threading
@@ -84,11 +82,11 @@ class MetricsCollector:
84
82
 
85
83
  """
86
84
 
87
- _instance: MetricsCollector | None = None
85
+ _instance: "MetricsCollector | None" = None
88
86
  _lock = threading.Lock()
89
87
  _initialized: bool
90
88
 
91
- def __new__(cls) -> MetricsCollector:
89
+ def __new__(cls) -> "MetricsCollector":
92
90
  """Singleton pattern for global metrics access."""
93
91
  if cls._instance is None:
94
92
  with cls._lock:
@@ -130,7 +128,7 @@ class MetricsCollector:
130
128
  """Record a timing measurement."""
131
129
  self._timers[name].record(duration)
132
130
 
133
- def timer(self, name: str) -> Timer:
131
+ def timer(self, name: str) -> "Timer":
134
132
  """Create a context manager timer."""
135
133
  return Timer(name, self)
136
134
 
@@ -183,7 +181,7 @@ class Timer:
183
181
  self.collector = collector
184
182
  self.start_time: float = 0.0
185
183
 
186
- def __enter__(self) -> Timer:
184
+ def __enter__(self) -> "Timer":
187
185
  """Start the timer."""
188
186
  self.start_time = time.perf_counter()
189
187
  return self
@@ -6,19 +6,20 @@ with configurable backoff strategies. Compatible with any
6
6
  Python framework (sync and async).
7
7
  """
8
8
 
9
- from __future__ import annotations
10
-
9
+ import asyncio
11
10
  import functools
11
+ import inspect
12
12
  import logging
13
13
  import secrets
14
14
  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 ParamSpec, TypeVar
18
+ from typing import Any, ParamSpec, TypeVar, cast
19
19
 
20
20
  P = ParamSpec("P")
21
21
  R = TypeVar("R")
22
+ F = TypeVar("F", bound=Callable[..., Any])
22
23
 
23
24
  logger = logging.getLogger("taipanstack.utils.retry")
24
25
 
@@ -108,6 +109,75 @@ def calculate_delay(
108
109
  return max(0, delay)
109
110
 
110
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
+
111
181
  def retry(
112
182
  *,
113
183
  max_attempts: int = 3,
@@ -119,11 +189,12 @@ def retry(
119
189
  reraise: bool = True,
120
190
  log_retries: bool = True,
121
191
  on_retry: Callable[[int, int, Exception, float], None] | None = None,
122
- ) -> Callable[[Callable[P, R]], Callable[P, R]]:
123
- """Retry a function with exponential backoff.
192
+ ) -> Callable[[F], F]:
193
+ """Retry a sync or async function with exponential backoff.
124
194
 
125
195
  Automatically retries the decorated function when specified
126
196
  exceptions are raised, with configurable backoff strategy.
197
+ Detects coroutine functions and preserves their async nature.
127
198
 
128
199
  Args:
129
200
  max_attempts: Maximum number of retry attempts.
@@ -159,9 +230,59 @@ def retry(
159
230
  jitter=jitter,
160
231
  )
161
232
 
162
- 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
+
163
284
  @functools.wraps(func)
164
- def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
285
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
165
286
  last_exception: Exception | None = None
166
287
 
167
288
  for attempt in range(1, max_attempts + 1): # pragma: no branch
@@ -171,45 +292,25 @@ def retry(
171
292
  last_exception = e
172
293
 
173
294
  if attempt == max_attempts:
174
- # Last attempt failed
175
- if log_retries:
176
- logger.warning(
177
- "All %d attempts failed for %s: %s",
178
- max_attempts,
179
- func.__name__,
180
- str(e),
181
- )
295
+ _log_all_failed(
296
+ func.__name__,
297
+ max_attempts,
298
+ e,
299
+ log_retries,
300
+ )
182
301
  break
183
302
 
184
303
  # Calculate delay and wait
185
304
  delay = calculate_delay(attempt, config)
186
-
187
- if log_retries:
188
- logger.info(
189
- "Attempt %d/%d failed for %s: %s. "
190
- "Retrying in %.2f seconds...",
191
- attempt,
192
- max_attempts,
193
- func.__name__,
194
- str(e),
195
- delay,
196
- )
197
-
198
- # Invoke callback or emit structured log if no callback set
199
- if on_retry is not None:
200
- on_retry(attempt, max_attempts, e, delay)
201
- elif (
202
- _HAS_STRUCTLOG and _structlog_logger is not None
203
- ): # pragma: no branch
204
- _structlog_logger.warning(
205
- "retry_attempted",
206
- function=func.__name__,
207
- attempt=attempt,
208
- max_attempts=max_attempts,
209
- error=str(e),
210
- delay_seconds=round(delay, 3),
211
- )
212
-
305
+ _log_retry_attempt(
306
+ func.__name__,
307
+ attempt,
308
+ max_attempts,
309
+ e,
310
+ delay,
311
+ log_retries,
312
+ on_retry,
313
+ )
213
314
  time.sleep(delay)
214
315
 
215
316
  # All attempts failed
@@ -227,7 +328,7 @@ def retry(
227
328
  last_exception=last_exception,
228
329
  )
229
330
 
230
- return wrapper
331
+ return cast(F, wrapper)
231
332
 
232
333
  return decorator
233
334
 
@@ -301,7 +402,7 @@ class Retrier:
301
402
  self.attempt = 0
302
403
  self.last_exception: Exception | None = None
303
404
 
304
- def __enter__(self) -> Retrier:
405
+ def __enter__(self) -> "Retrier":
305
406
  """Enter the retry context."""
306
407
  self.attempt = 0
307
408
  self.last_exception = None
@@ -5,8 +5,6 @@ Provides secure wrappers around subprocess execution with
5
5
  command validation, timeout handling, and retry logic.
6
6
  """
7
7
 
8
- from __future__ import annotations
9
-
10
8
  import shutil
11
9
  import subprocess
12
10
  import time
@@ -42,7 +40,7 @@ class SafeCommandResult:
42
40
  """Check if command succeeded."""
43
41
  return self.returncode == 0
44
42
 
45
- def raise_on_error(self) -> SafeCommandResult:
43
+ def raise_on_error(self) -> "SafeCommandResult":
46
44
  """Raise an exception if command failed.
47
45
 
48
46
  Returns:
@@ -1,24 +0,0 @@
1
- """Utility modules for Stack."""
2
-
3
- from taipanstack.utils.filesystem import ensure_dir, safe_read, safe_write
4
- from taipanstack.utils.logging import get_logger, setup_logging
5
- from taipanstack.utils.retry import Retrier, RetryConfig, RetryError, retry
6
- from taipanstack.utils.subprocess import SafeCommandResult, run_safe_command
7
-
8
- __all__ = [
9
- # Retry
10
- "Retrier",
11
- "RetryConfig",
12
- "RetryError",
13
- # Subprocess
14
- "SafeCommandResult",
15
- # Filesystem
16
- "ensure_dir",
17
- # Logging
18
- "get_logger",
19
- "retry",
20
- "run_safe_command",
21
- "safe_read",
22
- "safe_write",
23
- "setup_logging",
24
- ]
File without changes
File without changes