Expand description
CircuitBreaker is used to detect failures and encapsulates the logic of preventing a failure from constantly recurring, during maintenance, temporary external system failure or unexpected system difficulties.
§Links
- Future aware circuit breaker’s interface futures::CircuitBreaker.
- The state machine which is used StateMachine.
- More about circuit breakers https://martinfowler.com/bliki/CircuitBreaker.html
§Example
Using default backoff strategy and failure accrual policy.
use rand::{thread_rng, Rng};
use failsafe::{Config, CircuitBreaker, Error};
// A function that sometimes failed.
fn dangerous_call() -> Result<(), ()> {
if thread_rng().gen_range(0..2) == 0 {
return Err(())
}
Ok(())
}
// Create a circuit breaker which configured by reasonable default backoff and
// failure accrual policy.
let circuit_breaker = Config::new().build();
// Call the function in a loop, after some iterations the circuit breaker will
// be in a open state and reject next calls.
for n in 0..100 {
match circuit_breaker.call(|| dangerous_call()) {
Err(Error::Inner(_)) => {
eprintln!("{}: fail", n);
},
Err(Error::Rejected) => {
eprintln!("{}: rejected", n);
break;
},
_ => {}
}
}
Or configure custom backoff and policy:
use std::time::Duration;
use failsafe::{backoff, failure_policy, Config, CircuitBreaker};
fn circuit_breaker() -> impl CircuitBreaker {
// Create an exponential growth backoff which starts from 10s and ends with 60s.
let backoff = backoff::exponential(Duration::from_secs(10), Duration::from_secs(60));
// Create a policy which failed when three consecutive failures were made.
let policy = failure_policy::consecutive_failures(3, backoff);
// Creates a circuit breaker with given policy.
Config::new()
.failure_policy(policy)
.build()
}
Re-exports§
pub use self::failure_policy::FailurePolicy;
Modules§
- backoff
- Contains various backoff strategies.
- failure_
policy - Contains various failure accrual policies, which are used for the failure rate detection.
- futures
- Futures aware circuit breaker.
Structs§
- Any
- the Any predicate always returns true
- Config
- A
CircuitBreaker
’s configuration. - State
Machine - A circuit breaker implementation backed by state machine.
- Windowed
Adder - Time windowed counter.
Enums§
- Error
- A
CircuitBreaker
’s error.
Traits§
- Circuit
Breaker - A circuit breaker’s public interface.
- Failure
Predicate - Evaluates if an error should be recorded as a failure and thus increase the failure rate.
- Instrument
- Consumes the state machine events. May used for metrics and/or logs.