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}
101
102impl CircuitBreakerInner {
103    /// The state the breaker is in once the reset timeout is taken into
104    /// account, without recording the transition.
105    fn effective_state(&self, now: Instant) -> CircuitState {
106        if self.state == CircuitState::Open
107            && now.duration_since(self.last_state_change)
108                >= Duration::from_millis(self.config.reset_timeout_ms)
109        {
110            CircuitState::HalfOpen
111        } else {
112            self.state
113        }
114    }
115}
116
117/// Releases the half-open probe slot if the protected closure unwinds.
118///
119/// A panicking probe counts as a failed probe: the circuit reopens and
120/// the reset timeout starts again. Without this the slot would stay
121/// taken and the breaker would reject every later call.
122struct ProbeGuard<'a> {
123    inner: &'a Mutex<CircuitBreakerInner>,
124    armed: bool,
125}
126
127impl Drop for ProbeGuard<'_> {
128    fn drop(&mut self) {
129        if self.armed {
130            let mut inner = self.inner.lock();
131            inner.probe_in_flight = false;
132            inner.state = CircuitState::Open;
133            inner.last_state_change = Instant::now();
134        }
135    }
136}
137
138/// Circuit breaker implementation to prevent cascading failures
139///
140/// The circuit breaker tracks failures and "trips" after a threshold is reached,
141/// preventing further calls and allowing the system to recover.
142pub struct CircuitBreaker {
143    name: String,
144    inner: Arc<Mutex<CircuitBreakerInner>>,
145}
146
147impl CircuitBreaker {
148    /// Create a new circuit breaker with the given name and default configuration
149    pub fn new(name: impl Into<String>) -> Self {
150        Self::with_config(name, CircuitBreakerConfig::default())
151    }
152
153    /// Create a new circuit breaker with custom configuration
154    pub fn with_config(name: impl Into<String>, config: CircuitBreakerConfig) -> Self {
155        Self {
156            name: name.into(),
157            inner: Arc::new(Mutex::new(CircuitBreakerInner {
158                config,
159                state: CircuitState::Closed,
160                failures: Vec::new(),
161                last_state_change: Instant::now(),
162                probe_in_flight: false,
163            })),
164        }
165    }
166
167    /// Get the current state of the circuit breaker.
168    ///
169    /// An open circuit whose reset timeout has elapsed reports
170    /// [`CircuitState::HalfOpen`]: the next [`execute`](Self::execute)
171    /// call is admitted as the probe. Reading the state does not
172    /// change it.
173    pub fn state(&self) -> CircuitState {
174        let inner = self.inner.lock();
175        inner.effective_state(Instant::now())
176    }
177
178    /// Get the name of the circuit breaker
179    pub fn name(&self) -> &str {
180        &self.name
181    }
182
183    /// Execute a function protected by the circuit breaker.
184    ///
185    /// While the circuit is open the call fails fast with
186    /// [`CircuitOpenError`]. Once the reset timeout elapses exactly one
187    /// call is admitted as a half-open probe; concurrent calls fail fast
188    /// until it resolves. A successful probe closes the circuit, and a
189    /// failed or panicking probe reopens it.
190    pub fn execute<F, T, E>(&self, f: F) -> RecoveryResult<T>
191    where
192        F: FnOnce() -> Result<T, E>,
193        E: std::error::Error + Send + Sync + 'static,
194    {
195        // First check if we can proceed with the call
196        let is_probe = {
197            let mut inner = self.inner.lock();
198            self.update_state(&mut inner);
199            match inner.state {
200                CircuitState::Closed => false,
201                CircuitState::HalfOpen if !inner.probe_in_flight => {
202                    inner.probe_in_flight = true;
203                    true
204                }
205                // Open, or half-open with the probe already running.
206                _ => return Err(Box::new(CircuitOpenError::new(&self.name))),
207            }
208        };
209
210        let mut guard = ProbeGuard {
211            inner: &self.inner,
212            armed: is_probe,
213        };
214
215        // Execute the function
216        let outcome = f();
217        guard.armed = false;
218
219        match outcome {
220            Ok(value) => {
221                // Success, potentially reset circuit breaker
222                self.on_success(is_probe);
223                Ok(value)
224            }
225            Err(err) => {
226                // Failure, record it and potentially trip circuit
227                self.on_failure(is_probe);
228                Err(Box::new(err))
229            }
230        }
231    }
232
233    /// Manually reset the circuit breaker to closed state
234    pub fn reset(&self) {
235        let mut inner = self.inner.lock();
236        inner.state = CircuitState::Closed;
237        inner.failures.clear();
238        inner.last_state_change = Instant::now();
239        inner.probe_in_flight = false;
240    }
241
242    /// Called when an operation succeeds
243    fn on_success(&self, was_probe: bool) {
244        let mut inner = self.inner.lock();
245        if was_probe {
246            inner.probe_in_flight = false;
247        }
248        if inner.state == CircuitState::HalfOpen {
249            // Successful test request, close the circuit
250            inner.state = CircuitState::Closed;
251            inner.failures.clear();
252            inner.last_state_change = Instant::now();
253        }
254    }
255
256    /// Called when an operation fails
257    fn on_failure(&self, was_probe: bool) {
258        let mut inner = self.inner.lock();
259        if was_probe {
260            inner.probe_in_flight = false;
261        }
262
263        if inner.state == CircuitState::HalfOpen {
264            // Failed during test request, reopen the circuit
265            inner.state = CircuitState::Open;
266            inner.last_state_change = Instant::now();
267            return;
268        }
269
270        // Add the failure
271        let now = Instant::now();
272        inner.failures.push(now);
273
274        // Remove old failures outside the window. When the window
275        // reaches back past the start of the monotonic clock (a very
276        // large `failure_window_ms`), every recorded failure is inside
277        // it and nothing is dropped. Plain `Instant - Duration` panics
278        // in that case.
279        let window = Duration::from_millis(inner.config.failure_window_ms);
280        if let Some(window_start) = now.checked_sub(window) {
281            inner.failures.retain(|&time| time >= window_start);
282        }
283
284        // Check if threshold is reached
285        if inner.state == CircuitState::Closed
286            && inner.failures.len() >= inner.config.failure_threshold
287        {
288            // Trip the circuit
289            inner.state = CircuitState::Open;
290            inner.last_state_change = now;
291        }
292    }
293
294    /// Update the circuit state based on timing
295    fn update_state(&self, inner: &mut CircuitBreakerInner) {
296        let now = Instant::now();
297        if inner.state == CircuitState::Open && inner.effective_state(now) == CircuitState::HalfOpen
298        {
299            // Reset timeout has elapsed, try half-open state
300            inner.state = CircuitState::HalfOpen;
301            inner.last_state_change = now;
302        }
303    }
304}
305
306/// Error returned when circuit is open
307#[derive(Debug)]
308pub struct CircuitOpenError {
309    circuit_name: String,
310}
311
312impl CircuitOpenError {
313    fn new(circuit_name: &str) -> Self {
314        Self {
315            circuit_name: circuit_name.to_string(),
316        }
317    }
318}
319
320impl std::fmt::Display for CircuitOpenError {
321    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
322        write!(f, "Circuit '{}' is open, failing fast", self.circuit_name)
323    }
324}
325
326impl std::error::Error for CircuitOpenError {}