Coverage for src/taipanstack/resilience/circuit_breaker.py: 100%
386 statements
« prev ^ index » next coverage.py v7.15.1, created at 2026-11-23 17:43 +0000
« prev ^ index » next coverage.py v7.15.1, created at 2026-11-23 17:43 +0000
1"""
2Circuit Breaker pattern implementation.
4Provides protection against cascading failures by temporarily
5blocking calls to a failing service. Compatible with any
6Python framework (sync and async).
7"""
9import contextlib
10import functools
11import inspect
12import logging
13import math
14import threading
15import time
16from collections.abc import Awaitable, Callable
17from dataclasses import dataclass, field
18from enum import Enum
19from typing import (
20 TYPE_CHECKING,
21 ParamSpec,
22 Protocol,
23 TypeGuard,
24 TypeVar,
25 cast,
26 overload,
27)
29from taipanstack.core.result import Err
31P = ParamSpec("P")
32R = TypeVar("R")
35class CircuitBreakerDecorator(Protocol):
36 """Protocol for the circuit breaker decorator."""
38 @overload
39 def __call__(self, func: Callable[P, R]) -> Callable[P, R]: ...
41 @overload
42 def __call__(
43 self,
44 func: Callable[P, Awaitable[R]],
45 ) -> Callable[P, Awaitable[R]]: ...
48logger = logging.getLogger("taipanstack.resilience.circuit_breaker")
50if TYPE_CHECKING:
52 class StructlogProtocol(Protocol):
53 """Protocol for structural logging to appease static checkers."""
55 def error(self, _event: str, **kwargs: object) -> None:
56 """Log an error event."""
57 ...
59 def warning(self, _event: str, **kwargs: object) -> None:
60 """Log a warning event."""
61 ...
62else:
63 StructlogProtocol = object
65try:
66 import structlog as _structlog
68 _structlog_logger: StructlogProtocol | None = cast(
69 StructlogProtocol,
70 _structlog.get_logger("taipanstack.resilience.circuit_breaker"),
71 )
72 _HAS_STRUCTLOG = True
73except ImportError:
74 _structlog_logger = None
75 _HAS_STRUCTLOG = False
78class CircuitState(Enum):
79 """States of the circuit breaker."""
81 CLOSED = "closed" # Normal operation, requests flow through
82 OPEN = "open" # Circuit is tripped, requests are blocked
83 HALF_OPEN = "half_open" # Testing if service has recovered
86def _safe_str(e: Exception) -> str:
87 try:
88 return str(e)
89 except Exception:
90 try:
91 return repr(e)
92 except Exception:
93 return "<unprintable exception>"
96class CircuitBreakerError(Exception):
97 """Raised when circuit breaker is open."""
99 def __init__(self, message: str, state: CircuitState) -> None:
100 """Initialize CircuitBreakerError.
102 Args:
103 message: Error description.
104 state: Current circuit state.
106 """
107 self.state = state
108 super().__init__(message)
111@dataclass(frozen=True)
112class CircuitBreakerConfig:
113 """Configuration for circuit breaker behavior.
115 Attributes:
116 failure_threshold: Number of failures before opening circuit.
117 success_threshold: Successes needed in half-open to close.
118 timeout: Seconds before trying half-open after open.
119 excluded_exceptions: Exceptions that don't count as failures.
120 failure_exceptions: Exceptions that count as failures.
122 """
124 failure_threshold: int = 5
125 success_threshold: int = 2
126 timeout: float = 30.0
127 excluded_exceptions: tuple[type[Exception], ...] = ()
128 failure_exceptions: tuple[type[Exception], ...] = (Exception,)
130 def _check_finite(self, value: int | float, name: str) -> None:
131 if type(value) not in (int, float):
132 raise TypeError(f"{name} must be of type int or float")
133 # type narrowing for type checker
134 val = float(value)
135 if not math.isfinite(val) or val < 0:
136 raise ValueError(f"{name} must be finite and non-negative")
138 def __post_init__(self) -> None:
139 """Validate configuration values."""
140 self._check_finite(self.failure_threshold, "failure_threshold")
141 self._check_finite(self.success_threshold, "success_threshold")
142 self._check_finite(self.timeout, "timeout")
145@dataclass
146class CircuitBreakerState:
147 """Internal state tracking for circuit breaker."""
149 state: CircuitState = CircuitState.CLOSED
150 failure_count: int = 0
151 success_count: int = 0
152 half_open_attempts: int = 0
153 last_failure_time: float = 0.0
154 lock: threading.Lock = field(default_factory=threading.Lock)
157class CircuitBreaker:
158 """Circuit breaker implementation.
160 Monitors function calls and opens the circuit when too many
161 failures occur, preventing further calls until the service
162 recovers. Supports both sync and async functions.
164 Example:
165 >>> breaker = CircuitBreaker(failure_threshold=3)
166 >>> @breaker
167 ... def call_external_api():
168 ... return requests.get("https://api.example.com", timeout=10)
170 """
172 @staticmethod
173 def _is_valid_metric(value: object, min_val: float = 0) -> TypeGuard[int | float]:
174 """Check if metric is a valid finite number >= min_val."""
175 if not isinstance(value, (int, float)):
176 return False
177 try:
178 return math.isfinite(value) and value >= min_val
179 except Exception:
180 return False
182 @staticmethod
183 def _get_safe_threshold(value: object, min_val: float, default: float) -> float:
184 """Return the threshold if valid, otherwise return the default."""
185 if CircuitBreaker._is_valid_metric(value, min_val):
186 return float(value)
187 return default
189 @staticmethod
190 def _check_finite_val(value: float, min_val: float, err_msg: str) -> None:
191 if (
192 not isinstance(value, (int, float))
193 or not math.isfinite(value)
194 or value < min_val
195 ):
196 raise ValueError(err_msg)
198 @staticmethod
199 def _validate_thresholds(
200 timeout: float,
201 failure_threshold: int,
202 success_threshold: int,
203 ) -> None:
204 CircuitBreaker._check_finite_val(
205 timeout,
206 0,
207 "timeout must be a finite non-negative number",
208 )
209 CircuitBreaker._check_finite_val(
210 failure_threshold,
211 1,
212 "failure_threshold must be a finite number >= 1",
213 )
214 CircuitBreaker._check_finite_val(
215 success_threshold,
216 1,
217 "success_threshold must be a finite number >= 1",
218 )
220 def __init__(
221 self,
222 *,
223 failure_threshold: int = 5,
224 success_threshold: int = 2,
225 timeout: float = 30.0,
226 excluded_exceptions: tuple[type[Exception], ...] = (),
227 failure_exceptions: tuple[type[Exception], ...] = (Exception,),
228 name: str = "default",
229 on_state_change: Callable[[CircuitState, CircuitState], None] | None = None,
230 ) -> None:
231 """Initialize CircuitBreaker.
233 Args:
234 failure_threshold: Failures before opening circuit.
235 success_threshold: Successes to close from half-open.
236 timeout: Seconds before attempting half-open.
237 excluded_exceptions: Exceptions that don't trip circuit.
238 failure_exceptions: Exceptions that count as failures.
239 name: Name for logging/identification.
240 on_state_change: Optional callback invoked on state transitions
241 with (old_state, new_state). Useful for custom monitoring.
243 """
244 CircuitBreaker._validate_thresholds(
245 timeout,
246 failure_threshold,
247 success_threshold,
248 )
250 self.config = CircuitBreakerConfig(
251 failure_threshold=failure_threshold,
252 success_threshold=success_threshold,
253 timeout=timeout,
254 excluded_exceptions=excluded_exceptions,
255 failure_exceptions=failure_exceptions,
256 )
257 self.name = name
258 self._state = CircuitBreakerState()
259 self._on_state_change = on_state_change
261 @property
262 def state(self) -> CircuitState:
263 """Get current circuit state."""
264 return self._state.state
266 @property
267 def failure_count(self) -> int:
268 """Get current failure count."""
269 return self._state.failure_count
271 @property
272 def is_closed(self) -> bool:
273 """Check if circuit is closed."""
274 return self._state.state == CircuitState.CLOSED
276 @property
277 def is_open(self) -> bool:
278 """Check if circuit is open."""
279 return self._state.state == CircuitState.OPEN
281 @property
282 def is_half_open(self) -> bool:
283 """Check if circuit is half-open."""
284 return self._state.state == CircuitState.HALF_OPEN
286 def _log_callback_failure(
287 self,
288 old_state: CircuitState,
289 new_state: CircuitState,
290 e: Exception,
291 ) -> None:
292 if _HAS_STRUCTLOG and _structlog_logger is not None:
293 _structlog_logger.error(
294 "circuit_state_change_callback_failed",
295 circuit=self.name,
296 old_state=old_state.value,
297 new_state=new_state.value,
298 error=_safe_str(e),
299 )
300 else:
301 logger.error(
302 "Circuit %s state change callback failed: %s",
303 self.name,
304 _safe_str(e),
305 )
307 def _log_structlog_warning(
308 self,
309 old_state: CircuitState,
310 new_state: CircuitState,
311 ) -> None:
312 if _HAS_STRUCTLOG and _structlog_logger is not None:
313 _structlog_logger.warning(
314 "circuit_state_changed",
315 circuit=self.name,
316 old_state=old_state.value,
317 new_state=new_state.value,
318 failure_count=self._state.failure_count,
319 )
321 def _notify_state_change(
322 self,
323 old_state: CircuitState,
324 new_state: CircuitState,
325 ) -> None:
326 """Notify callback of state transition if registered.
328 Emit a structured log via structlog when no callback is provided
329 and structlog is available.
330 """
331 if self._on_state_change is not None:
332 try:
333 self._on_state_change(old_state, new_state)
334 except Exception as e:
335 self._log_callback_failure(old_state, new_state, e)
336 return
338 self._log_structlog_warning(old_state, new_state)
340 def _get_safe_timeout(self) -> float:
341 try:
342 return float(self.config.timeout)
343 except (TypeError, ValueError):
344 return 30.0
346 def _calculate_safe_elapsed(
347 self, parsed_failure: float | int, safe_timeout: float, now: float
348 ) -> float:
349 try:
350 val = float(parsed_failure)
351 if not math.isfinite(val):
352 return safe_timeout
353 elapsed = now - val
354 if elapsed < 0:
355 return safe_timeout
356 return elapsed
357 except Exception:
358 return safe_timeout
360 def _compute_elapsed(
361 self, last_failure: float | None, safe_timeout: float, now: float
362 ) -> float | None:
363 if not isinstance(last_failure, (int, float)):
364 return None
365 return self._calculate_safe_elapsed(last_failure, safe_timeout, now)
367 def _calculate_elapsed_time(self, now: float) -> float | None:
368 """Calculate time elapsed since last failure."""
369 return self._compute_elapsed(
370 self._state.last_failure_time, self._get_safe_timeout(), now
371 )
373 def _transition_to_half_open(
374 self,
375 elapsed: float,
376 ) -> tuple[bool, tuple[CircuitState, CircuitState] | None]:
377 """Transition the circuit to half-open state."""
378 # Before transitioning, verify if we can make an attempt
379 # This happens in a lock, so it's thread-safe. However, once
380 # the state changes to HALF_OPEN, subsequent threads in the
381 # same lock block will hit the HALF_OPEN case.
382 self._state.state = CircuitState.HALF_OPEN
383 self._state.success_count = 0
384 # Initialize half_open_attempts to 1 because this first call
385 # that transitions the state is also an attempt.
386 self._state.half_open_attempts = 1
387 logger.info(
388 "Circuit %s entering half-open state (was open for %.1fs, failures=%d)",
389 self.name,
390 elapsed,
391 self._state.failure_count,
392 )
393 return True, (CircuitState.OPEN, CircuitState.HALF_OPEN)
395 def _evaluate_open_timeout(
396 self,
397 elapsed: float,
398 ) -> tuple[bool, tuple[CircuitState, CircuitState] | None]:
399 timeout = self._get_safe_threshold(self.config.timeout, 0, 30.0)
400 if elapsed >= timeout:
401 return self._transition_to_half_open(elapsed)
402 return False, None
404 def _get_valid_elapsed(self) -> float | None:
405 try:
406 now = time.monotonic()
407 except Exception:
408 return None
409 if not isinstance(now, (int, float)) or not math.isfinite(now):
410 return None
411 return self._calculate_elapsed_time(now)
413 def _handle_open_state(
414 self,
415 ) -> tuple[bool, tuple[CircuitState, CircuitState] | None]:
416 """Handle logic for OPEN state in _should_attempt."""
417 elapsed = self._get_valid_elapsed()
418 if elapsed is None:
419 return False, None
420 return self._evaluate_open_timeout(elapsed)
422 def _handle_attempt_half_open(self) -> bool:
423 if not self._is_valid_metric(self._state.half_open_attempts):
424 return False
426 success_threshold = self._get_safe_threshold(
427 self.config.success_threshold,
428 1,
429 2,
430 )
432 if self._state.half_open_attempts < success_threshold:
433 self._state.half_open_attempts += 1
434 return True
435 return False
437 def _acquire_lock(self) -> bool:
438 """Safely attempt to acquire the lock."""
439 try:
440 return self._state.lock.acquire(timeout=0.1)
441 except Exception:
442 return False
444 def _safe_release(self) -> None:
445 with contextlib.suppress(Exception):
446 self._state.lock.release()
448 def _evaluate_state_for_attempt(
449 self,
450 ) -> tuple[bool, tuple[CircuitState, CircuitState] | None]:
451 state = self._state.state
452 if state is CircuitState.CLOSED:
453 return True, None
454 if state is CircuitState.OPEN:
455 return self._handle_open_state()
456 if state is CircuitState.HALF_OPEN:
457 return self._handle_attempt_half_open(), None
458 return False, None # type: ignore[unreachable]
460 def _should_attempt(self) -> bool:
461 """Check if a call should be attempted."""
462 if not self._acquire_lock():
463 return False
464 try:
465 should_attempt, state_change = self._evaluate_state_for_attempt()
466 finally:
467 self._safe_release()
469 if state_change:
470 self._notify_state_change(*state_change)
472 return should_attempt
474 def _handle_success_half_open(self) -> tuple[CircuitState, CircuitState] | None:
475 if not self._is_valid_metric(self._state.success_count):
476 # Type corruption detected, reset and increment
477 self._state.success_count = 1
478 else:
479 self._state.success_count += 1
481 success_threshold = self._get_safe_threshold(
482 self.config.success_threshold,
483 1,
484 2,
485 )
487 if self._state.success_count >= success_threshold:
488 self._state.state = CircuitState.CLOSED
489 self._state.failure_count = 0
490 self._state.half_open_attempts = 0
491 logger.info(
492 "Circuit %s closed after recovery (%d consecutive successes)",
493 self.name,
494 self._state.success_count,
495 )
496 return (CircuitState.HALF_OPEN, CircuitState.CLOSED)
497 return None
499 def _get_success_state_change(self) -> tuple[CircuitState, CircuitState] | None:
500 state = self._state.state
501 if state is CircuitState.HALF_OPEN:
502 return self._handle_success_half_open()
503 if state is CircuitState.CLOSED:
504 # Reset failure count on success
505 self._state.failure_count = 0
506 return None
507 return None
509 def _record_success(self) -> None:
510 """Record a successful call."""
511 if not self._acquire_lock():
512 return
513 try:
514 state_change = self._get_success_state_change()
515 finally:
516 self._safe_release()
518 if state_change:
519 self._notify_state_change(*state_change)
521 def _handle_failure_half_open(self) -> tuple[CircuitState, CircuitState] | None:
522 """Handle failure when in HALF_OPEN state."""
523 self._state.state = CircuitState.OPEN
524 self._state.half_open_attempts = 0
525 logger.warning(
526 "Circuit %s reopened after failure in half-open",
527 self.name,
528 )
529 return (CircuitState.HALF_OPEN, CircuitState.OPEN)
531 def _handle_failure_closed(self) -> tuple[CircuitState, CircuitState] | None:
532 """Handle failure when in CLOSED state."""
533 # Check against corrupted NaN/Inf failure_count
534 if not self._is_valid_metric(self._state.failure_count):
535 self._state.state = CircuitState.OPEN
536 logger.warning(
537 "Circuit %s opened due to state/type corruption in failure_count",
538 self.name,
539 )
540 return (CircuitState.CLOSED, CircuitState.OPEN)
542 failure_threshold = self._get_safe_threshold(
543 self.config.failure_threshold,
544 1,
545 5,
546 )
548 if self._state.failure_count >= failure_threshold:
549 self._state.state = CircuitState.OPEN
550 logger.warning(
551 "Circuit %s opened after %d failures (threshold=%d)",
552 self.name,
553 self._state.failure_count,
554 failure_threshold,
555 )
556 return (CircuitState.CLOSED, CircuitState.OPEN)
558 return None
560 def _increment_failure_count(self) -> None:
561 if not self._is_valid_metric(self._state.failure_count):
562 # Handle type mutation (e.g. failure_count became string) or Inf/NaN
563 # Safe degradation: reset to max so it opens immediately
564 self._state.failure_count = self.config.failure_threshold
565 else:
566 self._state.failure_count += 1
568 def _update_failure_metrics(self) -> None:
569 self._increment_failure_count()
571 try:
572 now = time.monotonic()
573 except Exception:
574 now = float("nan")
576 if isinstance(now, (int, float)) and math.isfinite(now):
577 self._state.last_failure_time = now
579 def _get_failure_state_change(self) -> tuple[CircuitState, CircuitState] | None:
580 """Get state change for a failure."""
581 if self._state.state is CircuitState.HALF_OPEN:
582 return self._handle_failure_half_open()
583 if self._state.state is CircuitState.CLOSED:
584 return self._handle_failure_closed()
585 return None
587 def _is_excluded_exception(self, exc: Exception) -> bool:
588 try:
589 return isinstance(exc, self.config.excluded_exceptions)
590 except TypeError:
591 return False
593 def _record_failure(self, exc: Exception) -> None:
594 """Record a failed call."""
595 if self._is_excluded_exception(exc):
596 return
598 state_change: tuple[CircuitState, CircuitState] | None = None
600 if not self._acquire_lock():
601 return
602 try:
603 self._update_failure_metrics()
604 state_change = self._get_failure_state_change()
605 finally:
606 self._safe_release()
608 if state_change:
609 self._notify_state_change(*state_change)
611 def reset(self) -> None:
612 """Reset circuit breaker to closed state."""
613 state_change: tuple[CircuitState, CircuitState] | None = None
614 if not self._acquire_lock():
615 return
616 try:
617 old_state = self._state.state
618 if old_state is not CircuitState.CLOSED:
619 state_change = (old_state, CircuitState.CLOSED)
621 self._state.state = CircuitState.CLOSED
622 self._state.failure_count = 0
623 self._state.success_count = 0
624 self._state.half_open_attempts = 0
625 logger.info("Circuit %s manually reset", self.name)
626 finally:
627 self._safe_release()
629 if state_change:
630 self._notify_state_change(*state_change)
632 def _is_failure_exception(self, exc: Exception) -> bool:
633 try:
634 return isinstance(exc, self.config.failure_exceptions)
635 except TypeError:
636 return True
638 def _process_result(self, result: R) -> R:
639 """Process Result outcome and record success/failure.
641 Args:
642 result: The result to process.
644 Returns:
645 The original result.
647 """
648 if isinstance(result, Err):
649 err_val = result.unwrap_err()
650 if self._is_failure_exception(err_val):
651 self._record_failure(err_val)
652 return result
653 # Ignored exception in Result monad
654 return result
655 self._record_success()
656 return result
658 def _is_valid_half_open_attempts(self) -> bool:
659 """Validate half-open attempts value against corruption."""
660 val = self._state.half_open_attempts
661 if not isinstance(val, (int, float)):
662 return False # type: ignore[unreachable]
663 try:
664 return math.isfinite(val) and val >= 0
665 except Exception:
666 return False
668 def _safe_decrement_half_open_attempts(self) -> None:
669 """Safely decrement half-open attempts."""
670 if self._state.state is not CircuitState.HALF_OPEN:
671 return
673 if not self._is_valid_half_open_attempts():
674 # Reset if state is corrupted to prevent crash
675 self._state.half_open_attempts = 0
676 return
678 if self._state.half_open_attempts > 0:
679 self._state.half_open_attempts -= 1
681 def _decrement_half_open(self, is_half_open: bool) -> None:
682 """Decrement half-open attempt count if applicable.
684 Args:
685 is_half_open: Whether the circuit was half-open before attempt.
687 """
688 if is_half_open:
689 try:
690 acquired = self._state.lock.acquire(timeout=0.1)
691 except Exception:
692 acquired = False
694 if not acquired:
695 return
696 try:
697 self._safe_decrement_half_open_attempts()
698 finally:
699 self._safe_release()
701 def _handle_exception_in_call(self, e: Exception) -> None:
702 try:
703 is_failure = isinstance(e, self.config.failure_exceptions)
704 except TypeError:
705 is_failure = True
706 if is_failure:
707 self._record_failure(e)
709 def _execute_async_wrapper(
710 self,
711 func_coro: Callable[P, Awaitable[R]],
712 ) -> Callable[P, Awaitable[R]]:
713 @functools.wraps(func_coro)
714 async def async_wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
715 if not self._should_attempt():
716 raise CircuitBreakerError(
717 f"Circuit {self.name} is open",
718 state=self._state.state,
719 )
721 is_half_open = self._state.state is CircuitState.HALF_OPEN
723 try:
724 result = await func_coro(*args, **kwargs)
725 return self._process_result(result)
726 except Exception as e:
727 self._handle_exception_in_call(e)
728 raise
729 finally:
730 self._decrement_half_open(is_half_open)
732 return async_wrapper
734 def _execute_sync_wrapper(
735 self,
736 func_sync: Callable[P, R],
737 ) -> Callable[P, R]:
738 @functools.wraps(func_sync)
739 def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
740 if not self._should_attempt():
741 raise CircuitBreakerError(
742 f"Circuit {self.name} is open",
743 state=self._state.state,
744 )
746 is_half_open = self._state.state is CircuitState.HALF_OPEN
748 try:
749 result = func_sync(*args, **kwargs)
750 return self._process_result(result)
751 except Exception as e:
752 self._handle_exception_in_call(e)
753 raise
754 finally:
755 self._decrement_half_open(is_half_open)
757 return wrapper
759 def __call__(
760 self,
761 func: Callable[P, R] | Callable[P, Awaitable[R]],
762 ) -> Callable[P, R] | Callable[P, Awaitable[R]]:
763 """Decorate a sync or async function with circuit breaker protection."""
764 if inspect.iscoroutinefunction(func):
765 func_coro = cast(Callable[P, Awaitable[R]], func)
766 return self._execute_async_wrapper(func_coro)
768 func_sync = cast(Callable[P, R], func)
769 return self._execute_sync_wrapper(func_sync)
772def circuit_breaker(
773 *,
774 failure_threshold: int = 5,
775 success_threshold: int = 2,
776 timeout: float = 30.0,
777 excluded_exceptions: tuple[type[Exception], ...] = (),
778 failure_exceptions: tuple[type[Exception], ...] = (Exception,),
779 name: str | None = None,
780 on_state_change: Callable[[CircuitState, CircuitState], None] | None = None,
781) -> CircuitBreakerDecorator:
782 """Decorate a sync or async function with circuit breaker pattern.
784 Args:
785 failure_threshold: Failures before opening circuit.
786 success_threshold: Successes to close from half-open.
787 timeout: Seconds before attempting half-open.
788 excluded_exceptions: Exceptions that don't trip circuit.
789 failure_exceptions: Exceptions that count as failures.
790 name: Optional name for the circuit.
791 on_state_change: Optional callback invoked on state transitions
792 with (old_state, new_state).
794 Returns:
795 Decorated function with circuit breaker protection.
797 Example:
798 >>> @circuit_breaker(failure_threshold=3, timeout=60)
799 ... def call_api(endpoint: str) -> dict:
800 ... return requests.get(endpoint, timeout=10).json()
802 >>> @circuit_breaker(
803 ... failure_threshold=3,
804 ... on_state_change=lambda old, new: print(f"{old} -> {new}"),
805 ... )
806 ... def monitored_call() -> str:
807 ... return service.call()
809 """
811 def decorator(
812 func: Callable[P, R] | Callable[P, Awaitable[R]],
813 ) -> Callable[P, R] | Callable[P, Awaitable[R]]:
814 breaker = CircuitBreaker(
815 failure_threshold=failure_threshold,
816 success_threshold=success_threshold,
817 timeout=timeout,
818 excluded_exceptions=excluded_exceptions,
819 failure_exceptions=failure_exceptions,
820 name=name or cast(str, getattr(func, "__name__", "unknown")),
821 on_state_change=on_state_change,
822 )
823 return breaker(func)
825 return cast(CircuitBreakerDecorator, decorator)