When a tool or API is down, an agent that keeps calling it wastes time and money, and may hammer a service that is trying to recover. A circuit breaker wraps the calls and tracks failures. In the closed state calls pass through. After failure_threshold consecutive failures it opens: calls are rejected immediately without being attempted. After a cooldown period it moves to half-open and allows a single trial call. If the trial succeeds the circuit closes again, and if it fails the circuit reopens for another cooldown. For testability the class takes the current time as an argument instead of reading a clock.
Implement the class CircuitBreaker.
CircuitBreaker(failure_threshold, cooldown) starts closed with zero consecutive failures.allow(now) returns True if a call may be attempted. Closed: True. Open: False until now - opened_at >= cooldown, at which point the state becomes half-open and it returns True. Half-open: True only for the first call; while that trial is outstanding return False.record_success(now) resets the failure count and closes the circuit. record_failure(now): in half-open state it reopens immediately with opened_at = now; in closed state it increments the failure count and opens (with opened_at = now) when the count reaches failure_threshold.state is an attribute holding 'closed', 'open' or 'half_open'.Track failures, opened_at and whether the half-open trial has been handed out.
A success in the closed state simply resets the counter, so only consecutive failures count.
No results yet
Run your code to check it against the examples, or submit to run every test.