pub struct CircuitBreaker { /* private fields */ }Expand description
Circuit breaker implementation to prevent cascading failures
The circuit breaker tracks failures and “trips” after a threshold is reached, preventing further calls and allowing the system to recover.
Implementations§
Source§impl CircuitBreaker
impl CircuitBreaker
Sourcepub fn new(name: impl Into<String>) -> Self
pub fn new(name: impl Into<String>) -> Self
Create a new circuit breaker with the given name and default configuration
Sourcepub fn with_config(
name: impl Into<String>,
config: CircuitBreakerConfig,
) -> Self
pub fn with_config( name: impl Into<String>, config: CircuitBreakerConfig, ) -> Self
Create a new circuit breaker with custom configuration
Sourcepub fn state(&self) -> CircuitState
pub fn state(&self) -> CircuitState
Get the current state of the circuit breaker.
An open circuit whose reset timeout has elapsed reports
CircuitState::HalfOpen: the next execute
call is admitted as the probe. Reading the state does not
change it.
Sourcepub fn execute<F, T, E>(&self, f: F) -> RecoveryResult<T>
pub fn execute<F, T, E>(&self, f: F) -> RecoveryResult<T>
Execute a function protected by the circuit breaker.
While the circuit is open the call fails fast with
CircuitOpenError. Once the reset timeout elapses exactly one
call is admitted as a half-open probe; concurrent calls fail fast
until it resolves. A successful probe closes the circuit, and a
failed or panicking probe reopens it.
Only the probe decides how the circuit leaves half-open. A call that was admitted while the circuit was still closed and finishes after it tripped does not affect the new state.
The closure’s error is boxed into RecoveryResult; downcast it
to tell a fail-fast rejection from the closure’s own error.
§Example
use error_forge::recovery::{CircuitBreaker, CircuitOpenError};
let breaker = CircuitBreaker::new("inventory-service");
let value = breaker.execute(|| Ok::<u32, std::io::Error>(42));
assert_eq!(value.unwrap(), 42);
let failed = breaker.execute(|| Err::<u32, _>(std::io::Error::other("down")));
let error = failed.unwrap_err();
assert!(error.downcast_ref::<CircuitOpenError>().is_none());
assert!(error.downcast_ref::<std::io::Error>().is_some());