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