Crates.io | failsafe |
lib.rs | failsafe |
version | 1.3.0 |
source | src |
created_at | 2018-09-03 20:56:59.325229 |
updated_at | 2024-07-05 19:46:23.082774 |
description | A circuit breaker implementation |
homepage | |
repository | https://github.com/dmexe/failsafe-rs |
max_upload_size | |
id | 82835 |
size | 85,962 |
A circuit breaker implementation which 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.
Fn() -> Result
and Future
(optional via default
futures-support
feature).constant
, exponential
, equal_jittered
, full_jittered
consecutive_failures
, success_rate_over_time_window
Add this to your Cargo.toml:
failsafe = "1.3.0"
Using default backoff strategy and failure accrual policy.
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, 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.
let circuit_breaker = Config::new()
.failure_policy(policy)
.build();