error_forge/recovery/circuit_breaker.rs
1use crate::recovery::RecoveryResult;
2use std::collections::VecDeque;
3use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
4use std::time::{Duration, Instant};
5
6/// Represents the current state of a circuit breaker.
7///
8/// Marked `#[non_exhaustive]` so future minor releases can add new
9/// states (e.g. `Disabled`, `ForcedOpen`) without breaking callers
10/// that exhaustively `match` on the enum.
11#[derive(Debug, Clone, Copy, PartialEq)]
12#[non_exhaustive]
13pub enum CircuitState {
14 /// Circuit is closed and operations are allowed to execute
15 Closed,
16
17 /// Circuit is open and operations will fail fast
18 Open,
19
20 /// Circuit is partially open: the reset timeout has elapsed and
21 /// a single probe request is admitted. Other calls fail fast
22 /// until the probe resolves. Use
23 /// [`CircuitBreaker::is_probing`] to tell whether the probe is
24 /// already running (calls fail fast) or the next call will be the
25 /// probe.
26 HalfOpen,
27}
28
29/// Configuration for a circuit breaker.
30///
31/// Marked `#[non_exhaustive]` so future minor releases can add new
32/// tuning knobs without breaking callers. Construct via
33/// [`CircuitBreakerConfig::default`] then mutate the fields you
34/// care about.
35///
36/// The breaker counts failures, not a failure rate: it opens once
37/// `failure_threshold` calls have failed within the last
38/// `failure_window_ms`, however many calls succeeded in between. Every
39/// `Err` returned by the protected closure counts as a failure.
40#[derive(Clone)]
41#[non_exhaustive]
42pub struct CircuitBreakerConfig {
43 /// Number of failures required to open the circuit
44 pub failure_threshold: usize,
45
46 /// Time window in milliseconds to count failures
47 pub failure_window_ms: u64,
48
49 /// Time in milliseconds that the circuit stays open before trying again
50 pub reset_timeout_ms: u64,
51
52 /// Longest time in milliseconds a half-open probe may run before it
53 /// counts as failed. `None` (the default) uses `reset_timeout_ms`.
54 ///
55 /// While the probe runs every other call fails fast, so a probe that
56 /// never returns (a dependency that accepts connections but never
57 /// answers) would otherwise keep the circuit failing until
58 /// [`CircuitBreaker::reset`]. Once the probe is older than this, the
59 /// circuit reopens as if the probe had failed, and a new probe is
60 /// admitted after the next reset timeout. The late result of the old
61 /// probe is then ignored. Closures should still set their own I/O
62 /// timeouts: the breaker cannot interrupt a call that hangs.
63 pub probe_timeout_ms: Option<u64>,
64}
65
66impl Default for CircuitBreakerConfig {
67 fn default() -> Self {
68 Self {
69 failure_threshold: 5,
70 failure_window_ms: 60000, // 1 minute
71 reset_timeout_ms: 30000, // 30 seconds
72 probe_timeout_ms: None,
73 }
74 }
75}
76
77impl CircuitBreakerConfig {
78 /// Construct a [`CircuitBreakerConfig`] from its three core knobs.
79 ///
80 /// Provided so external callers (tests, custom circuit-breaker
81 /// wiring) can build the struct without depending on its field
82 /// list, which may grow over the `1.x` line. For tuning only a
83 /// subset, start from [`Self::default`] and use the
84 /// `with_*` builder methods.
85 pub fn new(failure_threshold: usize, failure_window_ms: u64, reset_timeout_ms: u64) -> Self {
86 Self {
87 failure_threshold,
88 failure_window_ms,
89 reset_timeout_ms,
90 probe_timeout_ms: None,
91 }
92 }
93
94 /// Override the failure-count threshold.
95 #[must_use]
96 pub fn with_failure_threshold(mut self, threshold: usize) -> Self {
97 self.failure_threshold = threshold;
98 self
99 }
100
101 /// Override the failure-counting window in milliseconds.
102 #[must_use]
103 pub fn with_failure_window_ms(mut self, window_ms: u64) -> Self {
104 self.failure_window_ms = window_ms;
105 self
106 }
107
108 /// Override the reset-timeout in milliseconds.
109 #[must_use]
110 pub fn with_reset_timeout_ms(mut self, reset_ms: u64) -> Self {
111 self.reset_timeout_ms = reset_ms;
112 self
113 }
114
115 /// Override the longest time a half-open probe may run before it
116 /// counts as failed (see [`Self::probe_timeout_ms`]).
117 ///
118 /// # Example
119 ///
120 /// ```
121 /// use error_forge::recovery::CircuitBreakerConfig;
122 ///
123 /// let config = CircuitBreakerConfig::default().with_probe_timeout_ms(2_000);
124 /// assert_eq!(config.probe_timeout_ms, Some(2_000));
125 /// ```
126 #[must_use]
127 pub fn with_probe_timeout_ms(mut self, probe_ms: u64) -> Self {
128 self.probe_timeout_ms = Some(probe_ms);
129 self
130 }
131
132 /// The probe timeout in effect.
133 fn probe_timeout(&self) -> Duration {
134 Duration::from_millis(self.probe_timeout_ms.unwrap_or(self.reset_timeout_ms))
135 }
136}
137
138/// Lock the breaker state, ignoring poisoning.
139///
140/// The protected closure never runs while the lock is held; the lock
141/// only covers short updates of the breaker's own fields, each of which
142/// leaves the state valid. Taking a poisoned lock anyway keeps every
143/// method panic-free, as the non-poisoning `parking_lot` lock used up to
144/// 1.0.2 did.
145fn lock(inner: &Mutex<CircuitBreakerInner>) -> MutexGuard<'_, CircuitBreakerInner> {
146 inner.lock().unwrap_or_else(PoisonError::into_inner)
147}
148
149struct CircuitBreakerInner {
150 config: CircuitBreakerConfig,
151 state: CircuitState,
152 /// Failure times inside the window, oldest first, at most
153 /// `failure_threshold` of them.
154 failures: VecDeque<Instant>,
155 last_state_change: Instant,
156 /// Set while the single half-open probe call is running.
157 probe_in_flight: bool,
158 /// When the running probe was admitted.
159 probe_started: Instant,
160 /// Bumped on every state change. A call records the generation it
161 /// was admitted under, and its outcome only counts while that
162 /// generation is still current. A slow call admitted while the
163 /// circuit was closed therefore cannot close or reopen it after it
164 /// has tripped; only the probe admitted in half-open can move the
165 /// circuit out of half-open.
166 generation: u64,
167}
168
169impl CircuitBreakerInner {
170 /// The state the breaker is in once the reset timeout is taken into
171 /// account, without recording the transition.
172 fn effective_state(&self, now: Instant) -> CircuitState {
173 let reset = Duration::from_millis(self.config.reset_timeout_ms);
174 match self.state {
175 CircuitState::Open if now.duration_since(self.last_state_change) >= reset => {
176 CircuitState::HalfOpen
177 }
178 CircuitState::HalfOpen => match self.probe_expired_at(now) {
179 // The probe timed out: it failed then, so the circuit
180 // reopened then.
181 Some(failed_at) if now.duration_since(failed_at) < reset => CircuitState::Open,
182 _ => CircuitState::HalfOpen,
183 },
184 state => state,
185 }
186 }
187
188 /// If the running probe has run out of time, count it as failed: the
189 /// circuit reopened at its deadline, under a new generation, so the
190 /// probe's late result counts for nothing.
191 fn expire_stale_probe(&mut self, now: Instant) {
192 if self.state == CircuitState::HalfOpen {
193 if let Some(failed_at) = self.probe_expired_at(now) {
194 self.probe_in_flight = false;
195 self.transition(CircuitState::Open, failed_at);
196 }
197 }
198 }
199
200 /// When the running probe ran out of time, if it has.
201 fn probe_expired_at(&self, now: Instant) -> Option<Instant> {
202 if !self.probe_in_flight {
203 return None;
204 }
205 let deadline = self
206 .probe_started
207 .checked_add(self.config.probe_timeout())?;
208 (now >= deadline).then_some(deadline)
209 }
210
211 /// Move to `state` and start a new generation.
212 fn transition(&mut self, state: CircuitState, now: Instant) {
213 self.state = state;
214 self.last_state_change = now;
215 self.generation = self.generation.wrapping_add(1);
216 }
217
218 /// Records a failed call admitted in the closed state, opening the
219 /// circuit once the threshold is reached within the window.
220 fn record_failure(&mut self, admission: Admission, now: Instant) {
221 // A call admitted under an earlier generation (before the
222 // circuit tripped, or before a reset) no longer counts.
223 if admission.is_probe
224 || self.state != CircuitState::Closed
225 || admission.generation != self.generation
226 {
227 return;
228 }
229
230 self.failures.push_back(now);
231
232 // Drop failures outside the window, oldest first. When the
233 // window reaches back past the start of the monotonic clock (a
234 // very large `failure_window_ms`), every recorded failure is
235 // inside it and nothing is dropped. Plain `Instant - Duration`
236 // panics in that case.
237 let window = Duration::from_millis(self.config.failure_window_ms);
238 if let Some(window_start) = now.checked_sub(window) {
239 while self
240 .failures
241 .front()
242 .is_some_and(|&time| time < window_start)
243 {
244 let _expired = self.failures.pop_front();
245 }
246 }
247 // Only the newest `failure_threshold` failures can ever matter,
248 // so the list never grows past it.
249 while self.failures.len() > self.config.failure_threshold.max(1) {
250 let _oldest = self.failures.pop_front();
251 }
252
253 if self.failures.len() >= self.config.failure_threshold {
254 self.transition(CircuitState::Open, now);
255 }
256 }
257
258 /// Whether a call admitted under `admission` is the probe of the
259 /// current half-open period.
260 fn is_current_probe(&self, admission: Admission) -> bool {
261 admission.is_probe
262 && admission.generation == self.generation
263 && self.state == CircuitState::HalfOpen
264 }
265}
266
267/// How a call was let through: as the half-open probe or as a normal
268/// call in the closed state, and under which generation.
269#[derive(Clone, Copy)]
270struct Admission {
271 is_probe: bool,
272 generation: u64,
273}
274
275/// Records a failure if the protected closure unwinds.
276///
277/// A panicking probe counts as a failed probe: the circuit reopens and
278/// the reset timeout starts again. Without this the slot would stay
279/// taken and the breaker would reject every later call. A panicking
280/// call in the closed state counts as a failure like any `Err`.
281struct ProbeGuard<'a> {
282 inner: &'a Mutex<CircuitBreakerInner>,
283 admission: Admission,
284 armed: bool,
285}
286
287impl Drop for ProbeGuard<'_> {
288 fn drop(&mut self) {
289 if self.armed {
290 let mut inner = lock(self.inner);
291 if self.admission.is_probe {
292 inner.expire_stale_probe(Instant::now());
293 if inner.is_current_probe(self.admission) {
294 inner.probe_in_flight = false;
295 inner.transition(CircuitState::Open, Instant::now());
296 }
297 } else {
298 inner.record_failure(self.admission, Instant::now());
299 }
300 }
301 }
302}
303
304/// Circuit breaker implementation to prevent cascading failures
305///
306/// The circuit breaker tracks failures and "trips" after a threshold is reached,
307/// preventing further calls and allowing the system to recover.
308pub struct CircuitBreaker {
309 /// Shared with every `CircuitOpenError` this breaker returns, so the
310 /// fail-fast path does not copy the name.
311 name: Arc<str>,
312 inner: Arc<Mutex<CircuitBreakerInner>>,
313}
314
315impl CircuitBreaker {
316 /// Create a new circuit breaker with the given name and default configuration
317 pub fn new(name: impl Into<String>) -> Self {
318 Self::with_config(name, CircuitBreakerConfig::default())
319 }
320
321 /// Create a new circuit breaker with custom configuration
322 pub fn with_config(name: impl Into<String>, config: CircuitBreakerConfig) -> Self {
323 Self {
324 name: Arc::from(name.into()),
325 inner: Arc::new(Mutex::new(CircuitBreakerInner {
326 config,
327 state: CircuitState::Closed,
328 failures: VecDeque::new(),
329 last_state_change: Instant::now(),
330 probe_in_flight: false,
331 probe_started: Instant::now(),
332 generation: 0,
333 })),
334 }
335 }
336
337 /// Get the current state of the circuit breaker.
338 ///
339 /// An open circuit whose reset timeout has elapsed reports
340 /// [`CircuitState::HalfOpen`]: the next [`execute`](Self::execute)
341 /// call is admitted as the probe. Reading the state does not
342 /// change it.
343 ///
344 /// A half-open probe that has run longer than the probe timeout
345 /// (see [`CircuitBreakerConfig::probe_timeout_ms`]) counts as failed,
346 /// so the state reads [`CircuitState::Open`] again until the next
347 /// reset timeout elapses.
348 pub fn state(&self) -> CircuitState {
349 let inner = lock(&self.inner);
350 inner.effective_state(Instant::now())
351 }
352
353 /// Whether a half-open probe is running right now, so every other
354 /// call fails fast until it returns or times out.
355 ///
356 /// [`state`](Self::state) reports [`CircuitState::HalfOpen`] both
357 /// while the probe runs and when the next call will be admitted as
358 /// the probe; this tells the two apart.
359 ///
360 /// # Example
361 ///
362 /// ```
363 /// use error_forge::recovery::CircuitBreaker;
364 ///
365 /// let breaker = CircuitBreaker::new("db");
366 /// assert!(!breaker.is_probing());
367 /// ```
368 pub fn is_probing(&self) -> bool {
369 let inner = lock(&self.inner);
370 inner.state == CircuitState::HalfOpen
371 && inner.probe_in_flight
372 && inner.probe_expired_at(Instant::now()).is_none()
373 }
374
375 /// Get the name of the circuit breaker
376 pub fn name(&self) -> &str {
377 &self.name
378 }
379
380 /// Execute a function protected by the circuit breaker.
381 ///
382 /// While the circuit is open the call fails fast with
383 /// [`CircuitOpenError`]. Once the reset timeout elapses exactly one
384 /// call is admitted as a half-open probe; concurrent calls fail fast
385 /// until it resolves. A successful probe closes the circuit, and a
386 /// failed or panicking probe reopens it.
387 ///
388 /// Only the probe decides how the circuit leaves half-open. A call
389 /// that was admitted while the circuit was still closed and finishes
390 /// after it tripped does not affect the new state. A probe that runs
391 /// longer than the probe timeout counts as failed: the circuit
392 /// reopens, and the probe's own result, when it comes, is ignored.
393 ///
394 /// The closure runs on the calling thread and the breaker cannot
395 /// interrupt it, so give it its own I/O timeouts. A panic in the
396 /// closure counts as a failure.
397 ///
398 /// The closure's error is boxed into [`RecoveryResult`]; downcast it
399 /// to tell a fail-fast rejection from the closure's own error.
400 ///
401 /// # Example
402 ///
403 /// ```
404 /// use error_forge::recovery::{CircuitBreaker, CircuitOpenError};
405 ///
406 /// let breaker = CircuitBreaker::new("inventory-service");
407 ///
408 /// let value = breaker.execute(|| Ok::<u32, std::io::Error>(42));
409 /// assert_eq!(value.unwrap(), 42);
410 ///
411 /// let failed = breaker.execute(|| Err::<u32, _>(std::io::Error::other("down")));
412 /// let error = failed.unwrap_err();
413 /// assert!(error.downcast_ref::<CircuitOpenError>().is_none());
414 /// assert!(error.downcast_ref::<std::io::Error>().is_some());
415 /// ```
416 pub fn execute<F, T, E>(&self, f: F) -> RecoveryResult<T>
417 where
418 F: FnOnce() -> Result<T, E>,
419 E: std::error::Error + Send + Sync + 'static,
420 {
421 // First check if we can proceed with the call
422 let admission = {
423 let mut inner = lock(&self.inner);
424 self.update_state(&mut inner);
425 let is_probe = match inner.state {
426 CircuitState::Closed => false,
427 CircuitState::HalfOpen if !inner.probe_in_flight => {
428 inner.probe_in_flight = true;
429 inner.probe_started = Instant::now();
430 true
431 }
432 // Open, or half-open with the probe already running.
433 _ => return Err(Box::new(CircuitOpenError::new(Arc::clone(&self.name)))),
434 };
435 Admission {
436 is_probe,
437 generation: inner.generation,
438 }
439 };
440
441 // Armed for every call: a panicking probe reopens the circuit,
442 // and a panicking call in the closed state counts as a failure.
443 let mut guard = ProbeGuard {
444 inner: &self.inner,
445 admission,
446 armed: true,
447 };
448
449 // Execute the function
450 let outcome = f();
451 guard.armed = false;
452
453 match outcome {
454 Ok(value) => {
455 // Success, potentially reset circuit breaker
456 self.on_success(admission);
457 Ok(value)
458 }
459 Err(err) => {
460 // Failure, record it and potentially trip circuit
461 self.on_failure(admission);
462 Err(Box::new(err))
463 }
464 }
465 }
466
467 /// Manually reset the circuit breaker to closed state
468 pub fn reset(&self) {
469 let mut inner = lock(&self.inner);
470 inner.transition(CircuitState::Closed, Instant::now());
471 inner.failures.clear();
472 inner.probe_in_flight = false;
473 }
474
475 /// Called when an operation succeeds
476 fn on_success(&self, admission: Admission) {
477 // Only the half-open probe changes state on success, so a normal
478 // call returns without taking the lock a second time.
479 if !admission.is_probe {
480 return;
481 }
482 let mut inner = lock(&self.inner);
483 inner.expire_stale_probe(Instant::now());
484 if inner.is_current_probe(admission) {
485 // Successful test request, close the circuit
486 inner.probe_in_flight = false;
487 inner.failures.clear();
488 inner.transition(CircuitState::Closed, Instant::now());
489 }
490 }
491
492 /// Called when an operation fails
493 fn on_failure(&self, admission: Admission) {
494 let mut inner = lock(&self.inner);
495
496 if admission.is_probe {
497 inner.expire_stale_probe(Instant::now());
498 if inner.is_current_probe(admission) {
499 // Failed during test request, reopen the circuit
500 inner.probe_in_flight = false;
501 inner.transition(CircuitState::Open, Instant::now());
502 }
503 return;
504 }
505
506 inner.record_failure(admission, Instant::now());
507 }
508
509 /// Update the circuit state based on timing
510 fn update_state(&self, inner: &mut CircuitBreakerInner) {
511 let now = Instant::now();
512 inner.expire_stale_probe(now);
513 if inner.state == CircuitState::Open && inner.effective_state(now) == CircuitState::HalfOpen
514 {
515 // Reset timeout has elapsed, try half-open state
516 inner.transition(CircuitState::HalfOpen, now);
517 inner.probe_in_flight = false;
518 }
519 }
520}
521
522/// Error returned when circuit is open
523#[derive(Debug)]
524pub struct CircuitOpenError {
525 circuit_name: Arc<str>,
526}
527
528impl CircuitOpenError {
529 fn new(circuit_name: Arc<str>) -> Self {
530 Self { circuit_name }
531 }
532}
533
534impl std::fmt::Display for CircuitOpenError {
535 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
536 write!(f, "Circuit '{}' is open, failing fast", self.circuit_name)
537 }
538}
539
540impl std::error::Error for CircuitOpenError {}