recloser
A concurrent circuit breaker implemented with ring buffers.
The Recloser
struct provides a call(...)
method to wrap function calls that may fail,
it will eagerly reject them when some failure_rate
is reached, and it will allow them
again after some time.
A future aware version of call(...)
is also available through an AsyncRecloser
wrapper.
The API is largely based on failsafe and the ring buffer implementation on resilient4j.
Usage
The Recloser
can be in three states:
Closed(RingBuffer(len))
: The initialRecloser
's state. At leastlen
calls will be performed before calculating afailure_rate
based on which transitions toOpen(_)
state may happen.Open(duration)
: All calls will returnErr(Error::Rejected)
untilduration
has elapsed, then transition toHalfOpen(_)
state will happen.HalfOpen(RingBuffer(len))
: At leastlen
calls will be performed before calculating afailure_rate
based on which transitions to eitherClosed(_)
orOpen(_)
states will happen.
The state transition settings can be customized as follows:
use Duration;
use Recloser;
// Equivalent to Recloser::default()
let recloser = custom
.error_rate
.closed_len
.half_open_len
.open_wait
.build;
Wrapping dangerous function calls in order to control failure propagation:
use ;
// Performs 1 call before calculating failure_rate
let recloser = custom.closed_len.build;
let f1 = ;
// First call, just recorded as an error
let res = recloser.call;
assert!;
// Now also computes failure_rate, that is 100% here
// Will transition to State::Open afterward
let res = recloser.call;
assert!;
let f2 = ;
// All calls are rejected (while in State::Open)
let res = recloser.call;
assert!;
It is also possible to discard some errors on a per call basis.
This behavior is controlled by the ErrorPredicate<E>
trait, which is already
implemented for all Fn(&E) -> bool
.
use ;
let recloser = default;
let f = ;
// Custom predicate that doesn't consider usize values as errors
let p = ;
// Will not record resulting Err(1) as an error
let res = recloser.call_with;
assert!;
Wrapping functions that return Future
s requires to use an AsyncRecloser
that just
wraps a regular Recloser
.
use future;
use ;
let recloser = from;
let future = lazy;
let future = recloser.call;
Performances
Benchmarks for Recloser
and failsafe::CircuitBreaker
- Single threaded workload: same performances
- Multi threaded workload:
Recloser
has 10x better performances
These benchmarks were run on a Intel Core i7-6700HQ @ 8x 3.5GHz
CPU.