|
| 1 | +"""Circuit breaker pattern for fault tolerance.""" |
| 2 | + |
| 3 | +import time |
| 4 | +from typing import Literal |
| 5 | + |
| 6 | + |
| 7 | +CircuitState = Literal["closed", "open", "half_open"] |
| 8 | + |
| 9 | + |
| 10 | +class CircuitBreaker: |
| 11 | + """Circuit breaker to prevent cascading failures. |
| 12 | +
|
| 13 | + Implements the circuit breaker pattern with three states: |
| 14 | + - closed: Normal operation, requests pass through |
| 15 | + - open: Failure threshold exceeded, requests fail fast |
| 16 | + - half_open: Recovery attempt, limited requests allowed |
| 17 | +
|
| 18 | + Example: |
| 19 | + >>> breaker = CircuitBreaker(failure_threshold=0.5, recovery_timeout=30) |
| 20 | + >>> if breaker.is_open(): |
| 21 | + ... raise Exception("Circuit breaker is open") |
| 22 | + >>> try: |
| 23 | + ... result = make_request() |
| 24 | + ... breaker.record_success() |
| 25 | + >>> except Exception: |
| 26 | + ... breaker.record_failure() |
| 27 | + """ |
| 28 | + |
| 29 | + def __init__(self, failure_threshold: float = 0.5, recovery_timeout: int = 30): |
| 30 | + """Initialize circuit breaker. |
| 31 | +
|
| 32 | + Args: |
| 33 | + failure_threshold: Failure rate (0.0-1.0) that triggers open state |
| 34 | + recovery_timeout: Seconds to wait before attempting recovery |
| 35 | + """ |
| 36 | + self.failure_threshold = failure_threshold |
| 37 | + self.recovery_timeout = recovery_timeout |
| 38 | + self.failures = 0 |
| 39 | + self.successes = 0 |
| 40 | + self.state: CircuitState = "closed" |
| 41 | + self.last_failure_time: float | None = None |
| 42 | + |
| 43 | + def record_success(self): |
| 44 | + """Record a successful request.""" |
| 45 | + self.successes += 1 |
| 46 | + |
| 47 | + # If in half_open state and we have enough successes, close the circuit |
| 48 | + if self.state == "half_open" and self.successes >= 3: |
| 49 | + self.state = "closed" |
| 50 | + self.failures = 0 |
| 51 | + self.successes = 0 |
| 52 | + |
| 53 | + def record_failure(self): |
| 54 | + """Record a failed request.""" |
| 55 | + self.failures += 1 |
| 56 | + self.last_failure_time = time.monotonic() |
| 57 | + |
| 58 | + total = self.failures + self.successes |
| 59 | + |
| 60 | + # Need minimum sample size before opening circuit |
| 61 | + if total >= 10: |
| 62 | + failure_rate = self.failures / total |
| 63 | + if failure_rate >= self.failure_threshold: |
| 64 | + self.state = "open" |
| 65 | + |
| 66 | + def is_open(self) -> bool: |
| 67 | + """Check if circuit breaker is open. |
| 68 | +
|
| 69 | + Returns: |
| 70 | + bool: True if circuit is open and requests should be blocked |
| 71 | + """ |
| 72 | + if self.state == "open": |
| 73 | + # Check if we should attempt recovery |
| 74 | + if self.last_failure_time is not None: |
| 75 | + if time.monotonic() - self.last_failure_time > self.recovery_timeout: |
| 76 | + self.state = "half_open" |
| 77 | + # Reset counters for half-open state |
| 78 | + self.failures = 0 |
| 79 | + self.successes = 0 |
| 80 | + return False |
| 81 | + return True |
| 82 | + |
| 83 | + return False |
| 84 | + |
| 85 | + def get_state(self) -> CircuitState: |
| 86 | + """Get current circuit breaker state. |
| 87 | +
|
| 88 | + Returns: |
| 89 | + CircuitState: Current state (closed, open, or half_open) |
| 90 | + """ |
| 91 | + return self.state |
| 92 | + |
| 93 | + def get_failure_rate(self) -> float: |
| 94 | + """Get current failure rate. |
| 95 | +
|
| 96 | + Returns: |
| 97 | + float: Failure rate (0.0-1.0), or 0.0 if no requests recorded |
| 98 | + """ |
| 99 | + total = self.failures + self.successes |
| 100 | + if total == 0: |
| 101 | + return 0.0 |
| 102 | + return self.failures / total |
| 103 | + |
| 104 | + def reset(self): |
| 105 | + """Reset circuit breaker to initial state.""" |
| 106 | + self.failures = 0 |
| 107 | + self.successes = 0 |
| 108 | + self.state = "closed" |
| 109 | + self.last_failure_time = None |
0 commit comments