Skip to main content

CommonLibrary/Transport/
CircuitBreaker.rs

1#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals)]
2//! # Circuit Breaker Pattern
3//!
4//! Circuit breaker implementation for transport fault tolerance.
5//! `CircuitBreakerState` lives in [`super::TransportStrategy`].
6
7use std::time::Duration;
8
9/// Configuration for the circuit breaker.
10#[derive(Debug, Clone)]
11pub struct CircuitBreakerConfiguration {
12	/// Number of consecutive failures before the circuit opens.
13	pub FailureThreshold:u32,
14	/// Duration to wait before transitioning to half-open.
15	pub ResetTimeout:Duration,
16	/// Successful requests in half-open state required to close the circuit.
17	pub SuccessThreshold:u32,
18}
19
20impl Default for CircuitBreakerConfiguration {
21	fn default() -> Self { Self { FailureThreshold:5, ResetTimeout:Duration::from_secs(60), SuccessThreshold:2 } }
22}
23
24/// Circuit breaker that wraps a transport to add fault-tolerance.
25///
26/// Tracks consecutive failures and opens the circuit when the
27/// `FailureThreshold` is exceeded, preventing cascading failures.
28#[derive(Debug, Clone)]
29pub struct CircuitBreaker {
30	Configuration:CircuitBreakerConfiguration,
31	FailureCount:u32,
32	IsOpen:bool,
33}
34
35impl CircuitBreaker {
36	/// Creates a new circuit breaker with the given configuration.
37	pub fn New(Configuration:CircuitBreakerConfiguration) -> Self {
38		Self { Configuration, FailureCount:0, IsOpen:false }
39	}
40
41	/// Returns `true` if the circuit allows requests through.
42	pub fn IsClosed(&self) -> bool { !self.IsOpen }
43
44	/// Records a successful request, resetting the failure counter.
45	pub fn RecordSuccess(&mut self) {
46		self.FailureCount = 0;
47		self.IsOpen = false;
48	}
49
50	/// Records a failed request, potentially opening the circuit.
51	pub fn RecordFailure(&mut self) {
52		self.FailureCount += 1;
53		if self.FailureCount >= self.Configuration.FailureThreshold {
54			self.IsOpen = true;
55		}
56	}
57}