error_forge/recovery/
circuit_breaker.rs1use crate::recovery::RecoveryResult;
2use parking_lot::Mutex;
3use std::sync::Arc;
4use std::time::{Duration, Instant};
5
6#[derive(Debug, Clone, Copy, PartialEq)]
12#[non_exhaustive]
13pub enum CircuitState {
14 Closed,
16
17 Open,
19
20 HalfOpen,
24}
25
26#[derive(Clone)]
33#[non_exhaustive]
34pub struct CircuitBreakerConfig {
35 pub failure_threshold: usize,
37
38 pub failure_window_ms: u64,
40
41 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, reset_timeout_ms: 30000, }
52 }
53}
54
55impl CircuitBreakerConfig {
56 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 #[must_use]
73 pub fn with_failure_threshold(mut self, threshold: usize) -> Self {
74 self.failure_threshold = threshold;
75 self
76 }
77
78 #[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 #[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 probe_in_flight: bool,
100}
101
102impl CircuitBreakerInner {
103 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
117struct 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
138pub struct CircuitBreaker {
143 name: String,
144 inner: Arc<Mutex<CircuitBreakerInner>>,
145}
146
147impl CircuitBreaker {
148 pub fn new(name: impl Into<String>) -> Self {
150 Self::with_config(name, CircuitBreakerConfig::default())
151 }
152
153 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 pub fn state(&self) -> CircuitState {
174 let inner = self.inner.lock();
175 inner.effective_state(Instant::now())
176 }
177
178 pub fn name(&self) -> &str {
180 &self.name
181 }
182
183 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 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 _ => 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 let outcome = f();
217 guard.armed = false;
218
219 match outcome {
220 Ok(value) => {
221 self.on_success(is_probe);
223 Ok(value)
224 }
225 Err(err) => {
226 self.on_failure(is_probe);
228 Err(Box::new(err))
229 }
230 }
231 }
232
233 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 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 inner.state = CircuitState::Closed;
251 inner.failures.clear();
252 inner.last_state_change = Instant::now();
253 }
254 }
255
256 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 inner.state = CircuitState::Open;
266 inner.last_state_change = Instant::now();
267 return;
268 }
269
270 let now = Instant::now();
272 inner.failures.push(now);
273
274 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 if inner.state == CircuitState::Closed
286 && inner.failures.len() >= inner.config.failure_threshold
287 {
288 inner.state = CircuitState::Open;
290 inner.last_state_change = now;
291 }
292 }
293
294 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 inner.state = CircuitState::HalfOpen;
301 inner.last_state_change = now;
302 }
303 }
304}
305
306#[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 {}