Tower-Based Circuit Breaker (Recap)
From Phase 2 Week 2 Day 13, extended with time-window metrics:
struct CircuitBreakerState {
state: RwLock<State>,
window: Mutex<VecDeque<(Instant, bool)>>,
config: Config,
}
impl CircuitBreakerState {
fn record(&self, success: bool) {
let now = Instant::now();
let mut window = self.window.lock().unwrap();
window.retain(|(t, _)| now.duration_since(*t) < self.config.window_size);
window.push_back((now, success));
if !success { self.maybe_open(&window); }
else if matches!(*self.state.read().unwrap(), State::HalfOpen) {
*self.state.write().unwrap() = State::Closed;
}
}
}