Skip to main content

error_forge/recovery/
circuit_breaker.rs

1use crate::recovery::RecoveryResult;
2use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
3use std::time::{Duration, Instant};
4
5/// Represents the current state of a circuit breaker.
6///
7/// Marked `#[non_exhaustive]` so future minor releases can add new
8/// states (e.g. `Disabled`, `ForcedOpen`) without breaking callers
9/// that exhaustively `match` on the enum.
10#[derive(Debug, Clone, Copy, PartialEq)]
11#[non_exhaustive]
12pub enum CircuitState {
13    /// Circuit is closed and operations are allowed to execute
14    Closed,
15
16    /// Circuit is open and operations will fail fast
17    Open,
18
19    /// Circuit is partially open: the reset timeout has elapsed and
20    /// a single probe request is admitted. Other calls fail fast
21    /// until the probe resolves.
22    HalfOpen,
23}
24
25/// Configuration for a circuit breaker.
26///
27/// Marked `#[non_exhaustive]` so future minor releases can add new
28/// tuning knobs without breaking callers. Construct via
29/// [`CircuitBreakerConfig::default`] then mutate the fields you
30/// care about.
31#[derive(Clone)]
32#[non_exhaustive]
33pub struct CircuitBreakerConfig {
34    /// Number of failures required to open the circuit
35    pub failure_threshold: usize,
36
37    /// Time window in milliseconds to count failures
38    pub failure_window_ms: u64,
39
40    /// Time in milliseconds that the circuit stays open before trying again
41    pub reset_timeout_ms: u64,
42}
43
44impl Default for CircuitBreakerConfig {
45    fn default() -> Self {
46        Self {
47            failure_threshold: 5,
48            failure_window_ms: 60000, // 1 minute
49            reset_timeout_ms: 30000,  // 30 seconds
50        }
51    }
52}
53
54impl CircuitBreakerConfig {
55    /// Construct a [`CircuitBreakerConfig`] from its three core knobs.
56    ///
57    /// Provided so external callers (tests, custom circuit-breaker
58    /// wiring) can build the struct without depending on its field
59    /// list, which may grow over the `1.x` line. For tuning only a
60    /// subset, start from [`Self::default`] and use the
61    /// `with_*` builder methods.
62    pub fn new(failure_threshold: usize, failure_window_ms: u64, reset_timeout_ms: u64) -> Self {
63        Self {
64            failure_threshold,
65            failure_window_ms,
66            reset_timeout_ms,
67        }
68    }
69
70    /// Override the failure-count threshold.
71    #[must_use]
72    pub fn with_failure_threshold(mut self, threshold: usize) -> Self {
73        self.failure_threshold = threshold;
74        self
75    }
76
77    /// Override the failure-counting window in milliseconds.
78    #[must_use]
79    pub fn with_failure_window_ms(mut self, window_ms: u64) -> Self {
80        self.failure_window_ms = window_ms;
81        self
82    }
83
84    /// Override the reset-timeout in milliseconds.
85    #[must_use]
86    pub fn with_reset_timeout_ms(mut self, reset_ms: u64) -> Self {
87        self.reset_timeout_ms = reset_ms;
88        self
89    }
90}
91
92/// Lock the breaker state, ignoring poisoning.
93///
94/// The protected closure never runs while the lock is held; the lock
95/// only covers short updates of the breaker's own fields, each of which
96/// leaves the state valid. Taking a poisoned lock anyway keeps every
97/// method panic-free, as the non-poisoning `parking_lot` lock used up to
98/// 1.0.2 did.
99fn lock(inner: &Mutex<CircuitBreakerInner>) -> MutexGuard<'_, CircuitBreakerInner> {
100    inner.lock().unwrap_or_else(PoisonError::into_inner)
101}
102
103struct CircuitBreakerInner {
104    config: CircuitBreakerConfig,
105    state: CircuitState,
106    failures: Vec<Instant>,
107    last_state_change: Instant,
108    /// Set while the single half-open probe call is running.
109    probe_in_flight: bool,
110    /// Bumped on every state change. A call records the generation it
111    /// was admitted under, and its outcome only counts while that
112    /// generation is still current. A slow call admitted while the
113    /// circuit was closed therefore cannot close or reopen it after it
114    /// has tripped; only the probe admitted in half-open can move the
115    /// circuit out of half-open.
116    generation: u64,
117}
118
119impl CircuitBreakerInner {
120    /// The state the breaker is in once the reset timeout is taken into
121    /// account, without recording the transition.
122    fn effective_state(&self, now: Instant) -> CircuitState {
123        if self.state == CircuitState::Open
124            && now.duration_since(self.last_state_change)
125                >= Duration::from_millis(self.config.reset_timeout_ms)
126        {
127            CircuitState::HalfOpen
128        } else {
129            self.state
130        }
131    }
132
133    /// Move to `state` and start a new generation.
134    fn transition(&mut self, state: CircuitState, now: Instant) {
135        self.state = state;
136        self.last_state_change = now;
137        self.generation = self.generation.wrapping_add(1);
138    }
139
140    /// Whether a call admitted under `admission` is the probe of the
141    /// current half-open period.
142    fn is_current_probe(&self, admission: Admission) -> bool {
143        admission.is_probe
144            && admission.generation == self.generation
145            && self.state == CircuitState::HalfOpen
146    }
147}
148
149/// How a call was let through: as the half-open probe or as a normal
150/// call in the closed state, and under which generation.
151#[derive(Clone, Copy)]
152struct Admission {
153    is_probe: bool,
154    generation: u64,
155}
156
157/// Releases the half-open probe slot if the protected closure unwinds.
158///
159/// A panicking probe counts as a failed probe: the circuit reopens and
160/// the reset timeout starts again. Without this the slot would stay
161/// taken and the breaker would reject every later call.
162struct ProbeGuard<'a> {
163    inner: &'a Mutex<CircuitBreakerInner>,
164    admission: Admission,
165    armed: bool,
166}
167
168impl Drop for ProbeGuard<'_> {
169    fn drop(&mut self) {
170        if self.armed {
171            let mut inner = lock(self.inner);
172            if inner.is_current_probe(self.admission) {
173                inner.probe_in_flight = false;
174                inner.transition(CircuitState::Open, Instant::now());
175            }
176        }
177    }
178}
179
180/// Circuit breaker implementation to prevent cascading failures
181///
182/// The circuit breaker tracks failures and "trips" after a threshold is reached,
183/// preventing further calls and allowing the system to recover.
184pub struct CircuitBreaker {
185    /// Shared with every `CircuitOpenError` this breaker returns, so the
186    /// fail-fast path does not copy the name.
187    name: Arc<str>,
188    inner: Arc<Mutex<CircuitBreakerInner>>,
189}
190
191impl CircuitBreaker {
192    /// Create a new circuit breaker with the given name and default configuration
193    pub fn new(name: impl Into<String>) -> Self {
194        Self::with_config(name, CircuitBreakerConfig::default())
195    }
196
197    /// Create a new circuit breaker with custom configuration
198    pub fn with_config(name: impl Into<String>, config: CircuitBreakerConfig) -> Self {
199        Self {
200            name: Arc::from(name.into()),
201            inner: Arc::new(Mutex::new(CircuitBreakerInner {
202                config,
203                state: CircuitState::Closed,
204                failures: Vec::new(),
205                last_state_change: Instant::now(),
206                probe_in_flight: false,
207                generation: 0,
208            })),
209        }
210    }
211
212    /// Get the current state of the circuit breaker.
213    ///
214    /// An open circuit whose reset timeout has elapsed reports
215    /// [`CircuitState::HalfOpen`]: the next [`execute`](Self::execute)
216    /// call is admitted as the probe. Reading the state does not
217    /// change it.
218    pub fn state(&self) -> CircuitState {
219        let inner = lock(&self.inner);
220        inner.effective_state(Instant::now())
221    }
222
223    /// Get the name of the circuit breaker
224    pub fn name(&self) -> &str {
225        &self.name
226    }
227
228    /// Execute a function protected by the circuit breaker.
229    ///
230    /// While the circuit is open the call fails fast with
231    /// [`CircuitOpenError`]. Once the reset timeout elapses exactly one
232    /// call is admitted as a half-open probe; concurrent calls fail fast
233    /// until it resolves. A successful probe closes the circuit, and a
234    /// failed or panicking probe reopens it.
235    ///
236    /// Only the probe decides how the circuit leaves half-open. A call
237    /// that was admitted while the circuit was still closed and finishes
238    /// after it tripped does not affect the new state.
239    ///
240    /// The closure's error is boxed into [`RecoveryResult`]; downcast it
241    /// to tell a fail-fast rejection from the closure's own error.
242    ///
243    /// # Example
244    ///
245    /// ```
246    /// use error_forge::recovery::{CircuitBreaker, CircuitOpenError};
247    ///
248    /// let breaker = CircuitBreaker::new("inventory-service");
249    ///
250    /// let value = breaker.execute(|| Ok::<u32, std::io::Error>(42));
251    /// assert_eq!(value.unwrap(), 42);
252    ///
253    /// let failed = breaker.execute(|| Err::<u32, _>(std::io::Error::other("down")));
254    /// let error = failed.unwrap_err();
255    /// assert!(error.downcast_ref::<CircuitOpenError>().is_none());
256    /// assert!(error.downcast_ref::<std::io::Error>().is_some());
257    /// ```
258    pub fn execute<F, T, E>(&self, f: F) -> RecoveryResult<T>
259    where
260        F: FnOnce() -> Result<T, E>,
261        E: std::error::Error + Send + Sync + 'static,
262    {
263        // First check if we can proceed with the call
264        let admission = {
265            let mut inner = lock(&self.inner);
266            self.update_state(&mut inner);
267            let is_probe = match inner.state {
268                CircuitState::Closed => false,
269                CircuitState::HalfOpen if !inner.probe_in_flight => {
270                    inner.probe_in_flight = true;
271                    true
272                }
273                // Open, or half-open with the probe already running.
274                _ => return Err(Box::new(CircuitOpenError::new(Arc::clone(&self.name)))),
275            };
276            Admission {
277                is_probe,
278                generation: inner.generation,
279            }
280        };
281
282        let mut guard = ProbeGuard {
283            inner: &self.inner,
284            admission,
285            armed: admission.is_probe,
286        };
287
288        // Execute the function
289        let outcome = f();
290        guard.armed = false;
291
292        match outcome {
293            Ok(value) => {
294                // Success, potentially reset circuit breaker
295                self.on_success(admission);
296                Ok(value)
297            }
298            Err(err) => {
299                // Failure, record it and potentially trip circuit
300                self.on_failure(admission);
301                Err(Box::new(err))
302            }
303        }
304    }
305
306    /// Manually reset the circuit breaker to closed state
307    pub fn reset(&self) {
308        let mut inner = lock(&self.inner);
309        inner.transition(CircuitState::Closed, Instant::now());
310        inner.failures.clear();
311        inner.probe_in_flight = false;
312    }
313
314    /// Called when an operation succeeds
315    fn on_success(&self, admission: Admission) {
316        // Only the half-open probe changes state on success, so a normal
317        // call returns without taking the lock a second time.
318        if !admission.is_probe {
319            return;
320        }
321        let mut inner = lock(&self.inner);
322        if inner.is_current_probe(admission) {
323            // Successful test request, close the circuit
324            inner.probe_in_flight = false;
325            inner.failures.clear();
326            inner.transition(CircuitState::Closed, Instant::now());
327        }
328    }
329
330    /// Called when an operation fails
331    fn on_failure(&self, admission: Admission) {
332        let mut inner = lock(&self.inner);
333
334        if admission.is_probe {
335            if inner.is_current_probe(admission) {
336                // Failed during test request, reopen the circuit
337                inner.probe_in_flight = false;
338                inner.transition(CircuitState::Open, Instant::now());
339            }
340            return;
341        }
342
343        // A call admitted under an earlier generation (before the
344        // circuit tripped, or before a reset) no longer counts.
345        if inner.state != CircuitState::Closed || admission.generation != inner.generation {
346            return;
347        }
348
349        // Add the failure
350        let now = Instant::now();
351        inner.failures.push(now);
352
353        // Remove old failures outside the window. When the window
354        // reaches back past the start of the monotonic clock (a very
355        // large `failure_window_ms`), every recorded failure is inside
356        // it and nothing is dropped. Plain `Instant - Duration` panics
357        // in that case.
358        let window = Duration::from_millis(inner.config.failure_window_ms);
359        if let Some(window_start) = now.checked_sub(window) {
360            inner.failures.retain(|&time| time >= window_start);
361        }
362
363        // Check if threshold is reached
364        if inner.failures.len() >= inner.config.failure_threshold {
365            // Trip the circuit
366            inner.transition(CircuitState::Open, now);
367        }
368    }
369
370    /// Update the circuit state based on timing
371    fn update_state(&self, inner: &mut CircuitBreakerInner) {
372        let now = Instant::now();
373        if inner.state == CircuitState::Open && inner.effective_state(now) == CircuitState::HalfOpen
374        {
375            // Reset timeout has elapsed, try half-open state
376            inner.transition(CircuitState::HalfOpen, now);
377            inner.probe_in_flight = false;
378        }
379    }
380}
381
382/// Error returned when circuit is open
383#[derive(Debug)]
384pub struct CircuitOpenError {
385    circuit_name: Arc<str>,
386}
387
388impl CircuitOpenError {
389    fn new(circuit_name: Arc<str>) -> Self {
390        Self { circuit_name }
391    }
392}
393
394impl std::fmt::Display for CircuitOpenError {
395    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
396        write!(f, "Circuit '{}' is open, failing fast", self.circuit_name)
397    }
398}
399
400impl std::error::Error for CircuitOpenError {}