1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
use std::sync::atomic::{AtomicUsize, Ordering};
use thiserror::Error as DeriveError;
#[derive(DeriveError, Debug)]
pub enum BusyBreakerError {
#[error("Number of allowed breaker trips exceeds configuration")]
BreakerTripsExceeded,
}
pub struct BusyBreaker {
max: AtomicUsize,
unit: AtomicUsize,
}
impl Default for BusyBreaker {
fn default() -> Self {
Self::new(7)
}
}
impl Clone for BusyBreaker {
fn clone(&self) -> Self {
Self {
unit: AtomicUsize::new(self.unit.load(Ordering::Acquire)),
max: AtomicUsize::new(self.max.load(Ordering::Acquire)),
}
}
}
impl BusyBreaker {
pub fn new(max_trips: usize) -> Self {
Self {
unit: AtomicUsize::new(0),
max: AtomicUsize::new(max_trips),
}
}
pub fn spin(&self) -> Result<(), BusyBreakerError> {
match self.unit.load(Ordering::Acquire) {
unit if unit <= self.max.load(Ordering::Acquire) => {
for _ in 0..(1 << unit) {
core::hint::spin_loop();
}
self.unit.store(unit + 1, Ordering::Release);
Ok(())
}
_ => Err(BusyBreakerError::BreakerTripsExceeded),
}
}
pub fn reset(&self) {
self.unit.store(0, Ordering::Release);
}
}