taipanstack 0.3.1__tar.gz → 0.3.2__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 (25) hide show
  1. {taipanstack-0.3.1 → taipanstack-0.3.2}/PKG-INFO +2 -2
  2. {taipanstack-0.3.1 → taipanstack-0.3.2}/pyproject.toml +7 -2
  3. {taipanstack-0.3.1 → taipanstack-0.3.2}/src/taipanstack/__init__.py +1 -5
  4. {taipanstack-0.3.1 → taipanstack-0.3.2}/src/taipanstack/config/__init__.py +0 -2
  5. {taipanstack-0.3.1 → taipanstack-0.3.2}/src/taipanstack/config/generators.py +59 -13
  6. {taipanstack-0.3.1 → taipanstack-0.3.2}/src/taipanstack/config/models.py +1 -3
  7. {taipanstack-0.3.1 → taipanstack-0.3.2}/src/taipanstack/config/version_config.py +0 -2
  8. {taipanstack-0.3.1 → taipanstack-0.3.2}/src/taipanstack/core/compat.py +1 -6
  9. {taipanstack-0.3.1 → taipanstack-0.3.2}/src/taipanstack/security/__init__.py +0 -2
  10. {taipanstack-0.3.1 → taipanstack-0.3.2}/src/taipanstack/security/guards.py +80 -77
  11. {taipanstack-0.3.1 → taipanstack-0.3.2}/src/taipanstack/security/sanitizers.py +8 -4
  12. {taipanstack-0.3.1 → taipanstack-0.3.2}/src/taipanstack/security/validators.py +1 -1
  13. {taipanstack-0.3.1 → taipanstack-0.3.2}/src/taipanstack/utils/circuit_breaker.py +9 -1
  14. {taipanstack-0.3.1 → taipanstack-0.3.2}/src/taipanstack/utils/filesystem.py +0 -2
  15. {taipanstack-0.3.1 → taipanstack-0.3.2}/src/taipanstack/utils/logging.py +3 -1
  16. {taipanstack-0.3.1 → taipanstack-0.3.2}/LICENSE +0 -0
  17. {taipanstack-0.3.1 → taipanstack-0.3.2}/README.md +0 -0
  18. {taipanstack-0.3.1 → taipanstack-0.3.2}/src/taipanstack/core/__init__.py +0 -0
  19. {taipanstack-0.3.1 → taipanstack-0.3.2}/src/taipanstack/core/optimizations.py +0 -0
  20. {taipanstack-0.3.1 → taipanstack-0.3.2}/src/taipanstack/core/result.py +0 -0
  21. {taipanstack-0.3.1 → taipanstack-0.3.2}/src/taipanstack/security/decorators.py +0 -0
  22. {taipanstack-0.3.1 → taipanstack-0.3.2}/src/taipanstack/utils/__init__.py +0 -0
  23. {taipanstack-0.3.1 → taipanstack-0.3.2}/src/taipanstack/utils/metrics.py +0 -0
  24. {taipanstack-0.3.1 → taipanstack-0.3.2}/src/taipanstack/utils/retry.py +0 -0
  25. {taipanstack-0.3.1 → taipanstack-0.3.2}/src/taipanstack/utils/subprocess.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: taipanstack
3
- Version: 0.3.1
3
+ Version: 0.3.2
4
4
  Summary: TaipanStack - Modular, secure, and scalable Python stack for robust development
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -27,7 +27,7 @@ Requires-Dist: result (>=0.17.0)
27
27
  Requires-Dist: structlog (>=23.0.0) ; extra == "runtime"
28
28
  Requires-Dist: uvloop (>=0.19.0) ; (sys_platform != "win32") and (extra == "runtime")
29
29
  Project-URL: Changelog, https://github.com/gabrielima7/TaipanStack/blob/main/CHANGELOG.md
30
- Project-URL: Documentation, https://github.com/gabrielima7/TaipanStack#readme
30
+ Project-URL: Documentation, https://gabrielima7.github.io/TaipanStack/
31
31
  Project-URL: Homepage, https://github.com/gabrielima7/TaipanStack
32
32
  Project-URL: Issues, https://github.com/gabrielima7/TaipanStack/issues
33
33
  Project-URL: Repository, https://github.com/gabrielima7/TaipanStack
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "taipanstack"
3
- version = "0.3.1"
3
+ version = "0.3.2"
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"}
@@ -31,7 +31,7 @@ dependencies = [
31
31
 
32
32
  [project.urls]
33
33
  Homepage = "https://github.com/gabrielima7/TaipanStack"
34
- Documentation = "https://github.com/gabrielima7/TaipanStack#readme"
34
+ Documentation = "https://gabrielima7.github.io/TaipanStack/"
35
35
  Repository = "https://github.com/gabrielima7/TaipanStack"
36
36
  Changelog = "https://github.com/gabrielima7/TaipanStack/blob/main/CHANGELOG.md"
37
37
  Issues = "https://github.com/gabrielima7/TaipanStack/issues"
@@ -71,7 +71,12 @@ dev = [
71
71
 
72
72
 
73
73
 
74
+
74
75
  # --- TaipanStack v2.0 Quality Configuration ---
76
+ docs = [
77
+ "mkdocs-material (>=9.7.3,<10.0.0)",
78
+ "mkdocstrings[python] (>=1.0.3,<2.0.0)"
79
+ ]
75
80
  [tool.ruff]
76
81
  line-length = 88
77
82
  target-version = "py311"
@@ -5,15 +5,13 @@ 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.1"
8
+ __version__ = "0.3.2"
9
9
 
10
- from taipanstack.config.models import StackConfig
11
10
  from taipanstack.config.version_config import (
12
11
  VersionRecommendations,
13
12
  get_version_recommendations,
14
13
  )
15
14
  from taipanstack.core.compat import (
16
- PY311,
17
15
  PY312,
18
16
  PY313,
19
17
  PY314,
@@ -33,12 +31,10 @@ from taipanstack.security.validators import (
33
31
  )
34
32
 
35
33
  __all__ = [
36
- "PY311",
37
34
  "PY312",
38
35
  "PY313",
39
36
  "PY314",
40
37
  "PY_VERSION",
41
- "StackConfig",
42
38
  "VersionRecommendations",
43
39
  "apply_optimizations",
44
40
  "get_features",
@@ -1,7 +1,6 @@
1
1
  """Configuration models package."""
2
2
 
3
3
  from taipanstack.config.generators import (
4
- generate_dependabot_config,
5
4
  generate_pre_commit_config,
6
5
  generate_pyproject_config,
7
6
  generate_security_policy,
@@ -18,7 +17,6 @@ __all__ = [
18
17
  "LoggingConfig",
19
18
  "SecurityConfig",
20
19
  "StackConfig",
21
- "generate_dependabot_config",
22
20
  "generate_pre_commit_config",
23
21
  "generate_pyproject_config",
24
22
  "generate_security_policy",
@@ -14,22 +14,17 @@ if TYPE_CHECKING:
14
14
  from taipanstack.config.models import StackConfig
15
15
 
16
16
 
17
- def generate_pyproject_config(config: StackConfig) -> str:
18
- """Generate Ruff, Mypy, and Pytest configuration for pyproject.toml.
17
+ def _generate_ruff_config(target_version: str) -> str:
18
+ """Generate Ruff configuration.
19
19
 
20
20
  Args:
21
- config: The Stack configuration.
21
+ target_version: The target Python version.
22
22
 
23
23
  Returns:
24
- Configuration string to append to pyproject.toml.
24
+ Ruff configuration string.
25
25
 
26
26
  """
27
- target_version = config.to_target_version()
28
- python_version = config.python_version
29
-
30
- return f"""
31
- # --- Stack v2.0 Quality Configuration ---
32
- [tool.ruff]
27
+ return f"""[tool.ruff]
33
28
  line-length = 88
34
29
  target-version = "{target_version}"
35
30
 
@@ -72,8 +67,20 @@ max-complexity = 10
72
67
  [tool.ruff.format]
73
68
  quote-style = "double"
74
69
  indent-style = "space"
70
+ """
71
+
72
+
73
+ def _generate_mypy_config(python_version: str) -> str:
74
+ """Generate Mypy configuration.
75
75
 
76
- [tool.mypy]
76
+ Args:
77
+ python_version: The target Python version.
78
+
79
+ Returns:
80
+ Mypy configuration string.
81
+
82
+ """
83
+ return f"""[tool.mypy]
77
84
  python_version = "{python_version}"
78
85
  warn_return_any = true
79
86
  warn_unused_configs = true
@@ -86,16 +93,34 @@ strict_equality = true
86
93
  ignore_missing_imports = true
87
94
  show_error_codes = true
88
95
  enable_error_code = ["ignore-without-code", "redundant-cast", "truthy-bool"]
96
+ """
89
97
 
90
- [tool.pytest.ini_options]
98
+
99
+ def _generate_pytest_config() -> str:
100
+ """Generate Pytest configuration.
101
+
102
+ Returns:
103
+ Pytest configuration string.
104
+
105
+ """
106
+ return """[tool.pytest.ini_options]
91
107
  testpaths = ["tests"]
92
108
  addopts = "-v --cov=src --cov-report=html --cov-report=term-missing --cov-fail-under=80 --strict-markers"
93
109
  markers = [
94
110
  "slow: marks tests as slow (deselect with '-m \"not slow\"')",
95
111
  "security: marks tests as security-related",
96
112
  ]
113
+ """
114
+
115
+
116
+ def _generate_coverage_config() -> str:
117
+ """Generate Coverage configuration.
97
118
 
98
- [tool.coverage.run]
119
+ Returns:
120
+ Coverage configuration string.
121
+
122
+ """
123
+ return """[tool.coverage.run]
99
124
  branch = true
100
125
  source = ["src"]
101
126
  omit = ["*/tests/*", "*/__pycache__/*"]
@@ -111,6 +136,27 @@ exclude_lines = [
111
136
  """
112
137
 
113
138
 
139
+ def generate_pyproject_config(config: StackConfig) -> str:
140
+ """Generate Ruff, Mypy, and Pytest configuration for pyproject.toml.
141
+
142
+ Args:
143
+ config: The Stack configuration.
144
+
145
+ Returns:
146
+ Configuration string to append to pyproject.toml.
147
+
148
+ """
149
+ target_version = config.to_target_version()
150
+ python_version = config.python_version
151
+
152
+ return f"""
153
+ # --- Stack v2.0 Quality Configuration ---
154
+ {_generate_ruff_config(target_version)}
155
+ {_generate_mypy_config(python_version)}
156
+ {_generate_pytest_config()}
157
+ {_generate_coverage_config()}"""
158
+
159
+
114
160
  def generate_pre_commit_config(config: StackConfig) -> str:
115
161
  """Generate .pre-commit-config.yaml content.
116
162
 
@@ -5,8 +5,6 @@ This module provides type-safe configuration models that validate
5
5
  all inputs at runtime, preventing errors and AI hallucinations.
6
6
  """
7
7
 
8
- from __future__ import annotations
9
-
10
8
  import re
11
9
  import sys
12
10
  from pathlib import Path
@@ -281,7 +279,7 @@ class StackConfig(BaseModel):
281
279
  return resolved
282
280
 
283
281
  @model_validator(mode="after")
284
- def validate_config_consistency(self) -> StackConfig:
282
+ def validate_config_consistency(self) -> "StackConfig":
285
283
  """Validate configuration consistency.
286
284
 
287
285
  Returns:
@@ -8,8 +8,6 @@ maintaining stability.
8
8
  Following Stack pillars: Security, Stability, Simplicity, Scalability, Compatibility.
9
9
  """
10
10
 
11
- from __future__ import annotations
12
-
13
11
  import logging
14
12
  from dataclasses import dataclass
15
13
  from typing import TYPE_CHECKING
@@ -8,17 +8,12 @@ maintaining compatibility with Python 3.11+.
8
8
  Following Stack pillars: Security, Stability, Simplicity, Scalability, Compatibility.
9
9
  """
10
10
 
11
- from __future__ import annotations
12
-
13
11
  import logging
14
12
  import os
15
13
  import sys
16
14
  from dataclasses import dataclass
17
15
  from enum import StrEnum
18
- from typing import TYPE_CHECKING
19
-
20
- if TYPE_CHECKING:
21
- from typing import Final
16
+ from typing import Final
22
17
 
23
18
  __all__ = [
24
19
  "PY311",
@@ -1,7 +1,6 @@
1
1
  """Security package for runtime protection."""
2
2
 
3
3
  from taipanstack.security.decorators import (
4
- OperationTimeoutError,
5
4
  ValidationError,
6
5
  deprecated,
7
6
  guard_exceptions,
@@ -30,7 +29,6 @@ from taipanstack.security.validators import (
30
29
 
31
30
  __all__ = [
32
31
  # Decorators
33
- "OperationTimeoutError",
34
32
  # Guards
35
33
  "SecurityError",
36
34
  "ValidationError",
@@ -13,6 +13,78 @@ import re
13
13
  from collections.abc import Sequence
14
14
  from pathlib import Path
15
15
 
16
+ _TRAVERSAL_PATTERNS: frozenset[str] = frozenset(
17
+ [
18
+ "..",
19
+ "~",
20
+ r"\.\.",
21
+ "%2e%2e", # URL encoded ..
22
+ "%252e%252e", # Double URL encoded
23
+ ]
24
+ )
25
+
26
+ _DANGEROUS_COMMAND_PATTERNS: tuple[tuple[str, str], ...] = (
27
+ (";", "command separator"),
28
+ ("|", "pipe"),
29
+ ("&", "background/and operator"),
30
+ ("$", "variable expansion"),
31
+ ("`", "command substitution"),
32
+ ("$(", "command substitution"),
33
+ ("${", "variable expansion"),
34
+ (">", "redirect"),
35
+ ("<", "redirect"),
36
+ (">>", "redirect append"),
37
+ ("||", "or operator"),
38
+ ("&&", "and operator"),
39
+ ("\n", "newline"),
40
+ ("\r", "carriage return"),
41
+ ("\x00", "null byte"),
42
+ )
43
+
44
+ _DEFAULT_DENIED_EXTENSIONS = frozenset(
45
+ [
46
+ "exe",
47
+ "dll",
48
+ "so",
49
+ "dylib", # Executables
50
+ "sh",
51
+ "bash",
52
+ "zsh",
53
+ "ps1",
54
+ "bat",
55
+ "cmd", # Scripts
56
+ "php",
57
+ "jsp",
58
+ "asp",
59
+ "aspx", # Server-side scripts
60
+ ]
61
+ )
62
+
63
+ _DEFAULT_DENIED_ENV_VARS = frozenset(
64
+ [
65
+ "AWS_SECRET_ACCESS_KEY",
66
+ "AWS_SESSION_TOKEN",
67
+ "GITHUB_TOKEN",
68
+ "GH_TOKEN",
69
+ "GITLAB_TOKEN",
70
+ "DATABASE_URL",
71
+ "DB_PASSWORD",
72
+ "PASSWORD",
73
+ "SECRET_KEY",
74
+ "PRIVATE_KEY",
75
+ "API_KEY",
76
+ "API_SECRET",
77
+ ]
78
+ )
79
+
80
+ _SENSITIVE_ENV_VAR_PATTERNS = (
81
+ re.compile(r".*SECRET.*"),
82
+ re.compile(r".*PASSWORD.*"),
83
+ re.compile(r".*TOKEN.*"),
84
+ re.compile(r".*PRIVATE.*KEY.*"),
85
+ re.compile(r".*API.*KEY.*"),
86
+ )
87
+
16
88
 
17
89
  class SecurityError(Exception):
18
90
  """Raised when a security guard detects a violation.
@@ -77,15 +149,8 @@ def guard_path_traversal(
77
149
 
78
150
  # Check for explicit traversal patterns before resolution
79
151
  path_str = str(path)
80
- traversal_patterns = [
81
- "..",
82
- "~",
83
- r"\.\.",
84
- "%2e%2e", # URL encoded ..
85
- "%252e%252e", # Double URL encoded
86
- ]
87
152
 
88
- for pattern in traversal_patterns:
153
+ for pattern in _TRAVERSAL_PATTERNS:
89
154
  if pattern.lower() in path_str.lower():
90
155
  raise SecurityError(
91
156
  f"Path traversal pattern detected: {pattern}",
@@ -167,27 +232,8 @@ def guard_command_injection(
167
232
  f"got {type(arg).__name__} at index {i}"
168
233
  )
169
234
 
170
- # Dangerous shell metacharacters
171
- dangerous_patterns: list[tuple[str, str]] = [
172
- (";", "command separator"),
173
- ("|", "pipe"),
174
- ("&", "background/and operator"),
175
- ("$", "variable expansion"),
176
- ("`", "command substitution"),
177
- ("$(", "command substitution"),
178
- ("${", "variable expansion"),
179
- (">", "redirect"),
180
- ("<", "redirect"),
181
- (">>", "redirect append"),
182
- ("||", "or operator"),
183
- ("&&", "and operator"),
184
- ("\n", "newline"),
185
- ("\r", "carriage return"),
186
- ("\x00", "null byte"),
187
- ]
188
-
189
235
  for arg in cmd_list:
190
- for pattern, description in dangerous_patterns:
236
+ for pattern, description in _DANGEROUS_COMMAND_PATTERNS:
191
237
  if pattern in arg:
192
238
  raise SecurityError(
193
239
  f"Dangerous shell character detected: {description}",
@@ -237,32 +283,14 @@ def guard_file_extension(
237
283
  path = Path(filename)
238
284
  ext = path.suffix.lower().lstrip(".")
239
285
 
240
- # Default dangerous extensions
241
- default_denied = {
242
- "exe",
243
- "dll",
244
- "so",
245
- "dylib", # Executables
246
- "sh",
247
- "bash",
248
- "zsh",
249
- "ps1",
250
- "bat",
251
- "cmd", # Scripts
252
- "php",
253
- "jsp",
254
- "asp",
255
- "aspx", # Server-side scripts
256
- }
257
-
258
286
  # Normalize extension lists
259
287
  def normalize_ext(e: str) -> str:
260
288
  return e.lower().lstrip(".")
261
289
 
262
290
  if denied_extensions is not None:
263
- denied = {normalize_ext(e) for e in denied_extensions}
291
+ denied = frozenset(normalize_ext(e) for e in denied_extensions)
264
292
  else:
265
- denied = default_denied
293
+ denied = _DEFAULT_DENIED_EXTENSIONS
266
294
 
267
295
  if ext in denied:
268
296
  raise SecurityError(
@@ -303,22 +331,6 @@ def guard_env_variable(
303
331
  SecurityError: If variable access is not allowed.
304
332
 
305
333
  """
306
- # Default sensitive variables
307
- default_denied = {
308
- "AWS_SECRET_ACCESS_KEY",
309
- "AWS_SESSION_TOKEN",
310
- "GITHUB_TOKEN",
311
- "GH_TOKEN",
312
- "GITLAB_TOKEN",
313
- "DATABASE_URL",
314
- "DB_PASSWORD",
315
- "PASSWORD",
316
- "SECRET_KEY",
317
- "PRIVATE_KEY",
318
- "API_KEY",
319
- "API_SECRET",
320
- }
321
-
322
334
  # Validate input type
323
335
  if not isinstance(name, str):
324
336
  raise TypeError(f"Variable name must be str, got {type(name).__name__}")
@@ -333,18 +345,9 @@ def guard_env_variable(
333
345
  name_upper = name.upper()
334
346
 
335
347
  if denied_names is not None:
336
- denied = {n.upper() for n in denied_names}
348
+ denied = frozenset(n.upper() for n in denied_names)
337
349
  else:
338
- denied = default_denied
339
-
340
- # Check against patterns
341
- sensitive_patterns = [
342
- r".*SECRET.*",
343
- r".*PASSWORD.*",
344
- r".*TOKEN.*",
345
- r".*PRIVATE.*KEY.*",
346
- r".*API.*KEY.*",
347
- ]
350
+ denied = _DEFAULT_DENIED_ENV_VARS
348
351
 
349
352
  if name_upper in denied:
350
353
  raise SecurityError(
@@ -353,8 +356,8 @@ def guard_env_variable(
353
356
  value=name,
354
357
  )
355
358
 
356
- for pattern in sensitive_patterns:
357
- if re.match(pattern, name_upper):
359
+ for pattern in _SENSITIVE_ENV_VAR_PATTERNS:
360
+ if pattern.match(name_upper):
358
361
  # Only block if not explicitly allowed
359
362
  if allowed_names is not None:
360
363
  allowed = {n.upper() for n in allowed_names}
@@ -65,8 +65,10 @@ def sanitize_string(
65
65
  The sanitized string.
66
66
 
67
67
  Example:
68
- >>> sanitize_string("<script>alert('xss')</script>Hello")
69
- "scriptalert('xss')/scriptHello"
68
+ ```python
69
+ sanitize_string("<script>alert('xss')</script>Hello")
70
+ # Returns: "scriptalert('xss')/scriptHello"
71
+ ```
70
72
 
71
73
  """
72
74
  if not isinstance(value, str):
@@ -130,8 +132,10 @@ def sanitize_filename(
130
132
  The sanitized filename.
131
133
 
132
134
  Example:
133
- >>> sanitize_filename("my/../file<>:name.txt")
134
- 'my_file_name.txt'
135
+ ```python
136
+ sanitize_filename("my/../file<>:name.txt")
137
+ # Returns: 'my_file_name.txt'
138
+ ```
135
139
 
136
140
  """
137
141
  if not isinstance(filename, str):
@@ -131,7 +131,7 @@ def validate_python_version(version: str) -> str:
131
131
 
132
132
  try:
133
133
  major, minor = map(int, version.split("."))
134
- except ValueError as e: # pragma: no cover — regex already validates digits
134
+ except ValueError as e:
135
135
  msg = f"Invalid version numbers in '{version}'"
136
136
  raise ValueError(msg) from e
137
137
 
@@ -55,6 +55,7 @@ class CircuitBreakerConfig:
55
55
  success_threshold: Successes needed in half-open to close.
56
56
  timeout: Seconds before trying half-open after open.
57
57
  excluded_exceptions: Exceptions that don't count as failures.
58
+ failure_exceptions: Exceptions that count as failures.
58
59
 
59
60
  """
60
61
 
@@ -62,6 +63,7 @@ class CircuitBreakerConfig:
62
63
  success_threshold: int = 2
63
64
  timeout: float = 30.0
64
65
  excluded_exceptions: tuple[type[Exception], ...] = ()
66
+ failure_exceptions: tuple[type[Exception], ...] = (Exception,)
65
67
 
66
68
 
67
69
  @dataclass
@@ -97,6 +99,7 @@ class CircuitBreaker:
97
99
  success_threshold: int = 2,
98
100
  timeout: float = 30.0,
99
101
  excluded_exceptions: tuple[type[Exception], ...] = (),
102
+ failure_exceptions: tuple[type[Exception], ...] = (Exception,),
100
103
  name: str = "default",
101
104
  on_state_change: Callable[[CircuitState, CircuitState], None] | None = None,
102
105
  ) -> None:
@@ -107,6 +110,7 @@ class CircuitBreaker:
107
110
  success_threshold: Successes to close from half-open.
108
111
  timeout: Seconds before attempting half-open.
109
112
  excluded_exceptions: Exceptions that don't trip circuit.
113
+ failure_exceptions: Exceptions that count as failures.
110
114
  name: Name for logging/identification.
111
115
  on_state_change: Optional callback invoked on state transitions
112
116
  with (old_state, new_state). Useful for custom monitoring.
@@ -117,6 +121,7 @@ class CircuitBreaker:
117
121
  success_threshold=success_threshold,
118
122
  timeout=timeout,
119
123
  excluded_exceptions=excluded_exceptions,
124
+ failure_exceptions=failure_exceptions,
120
125
  )
121
126
  self.name = name
122
127
  self._state = CircuitBreakerState()
@@ -266,7 +271,7 @@ class CircuitBreaker:
266
271
  result = func(*args, **kwargs)
267
272
  self._record_success()
268
273
  return result
269
- except Exception as e:
274
+ except self.config.failure_exceptions as e:
270
275
  self._record_failure(e)
271
276
  raise
272
277
 
@@ -279,6 +284,7 @@ def circuit_breaker(
279
284
  success_threshold: int = 2,
280
285
  timeout: float = 30.0,
281
286
  excluded_exceptions: tuple[type[Exception], ...] = (),
287
+ failure_exceptions: tuple[type[Exception], ...] = (Exception,),
282
288
  name: str | None = None,
283
289
  on_state_change: Callable[[CircuitState, CircuitState], None] | None = None,
284
290
  ) -> Callable[[Callable[P, R]], Callable[P, R]]:
@@ -289,6 +295,7 @@ def circuit_breaker(
289
295
  success_threshold: Successes to close from half-open.
290
296
  timeout: Seconds before attempting half-open.
291
297
  excluded_exceptions: Exceptions that don't trip circuit.
298
+ failure_exceptions: Exceptions that count as failures.
292
299
  name: Optional name for the circuit.
293
300
  on_state_change: Optional callback invoked on state transitions
294
301
  with (old_state, new_state).
@@ -316,6 +323,7 @@ def circuit_breaker(
316
323
  success_threshold=success_threshold,
317
324
  timeout=timeout,
318
325
  excluded_exceptions=excluded_exceptions,
326
+ failure_exceptions=failure_exceptions,
319
327
  name=name or func.__name__,
320
328
  on_state_change=on_state_change,
321
329
  )
@@ -5,8 +5,6 @@ Provides secure wrappers around file operations with path validation,
5
5
  atomic writes, and proper error handling using Result types.
6
6
  """
7
7
 
8
- from __future__ import annotations
9
-
10
8
  import contextlib
11
9
  import hashlib
12
10
  import os
@@ -281,6 +281,7 @@ def log_operation(
281
281
  *,
282
282
  logger: StackLogger | None = None,
283
283
  level: str = "INFO",
284
+ expected_exceptions: tuple[type[Exception], ...] | type[Exception] = Exception,
284
285
  ) -> Any:
285
286
  """Context manager for logging operations.
286
287
 
@@ -288,6 +289,7 @@ def log_operation(
288
289
  operation: Name of the operation.
289
290
  logger: Logger to use (creates one if not provided).
290
291
  level: Log level for messages.
292
+ expected_exceptions: Exceptions to catch and log as failures.
291
293
 
292
294
  Yields:
293
295
  The logger instance.
@@ -314,7 +316,7 @@ def log_operation(
314
316
  yield logger
315
317
  duration = (datetime.now(UTC) - start_time).total_seconds()
316
318
  log_method(f"Completed: {operation}", duration_seconds=duration)
317
- except Exception as e:
319
+ except expected_exceptions as e:
318
320
  duration = (datetime.now(UTC) - start_time).total_seconds()
319
321
  logger.exception(
320
322
  f"Failed: {operation}",
File without changes
File without changes