Skip to main content

error_forge/recovery/
circuit_breaker.rs

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