relay_server/utils/
retry.rsuse std::time::{Duration, Instant};
use backoff::backoff::Backoff;
use backoff::ExponentialBackoff;
const DEFAULT_MULTIPLIER: f64 = 1.5;
const DEFAULT_RANDOMIZATION: f64 = 0.0;
const INITIAL_INTERVAL: u64 = 1000;
#[derive(Debug)]
pub struct RetryBackoff {
backoff: ExponentialBackoff,
attempt: usize,
}
impl RetryBackoff {
pub fn new(max_interval: Duration) -> Self {
let backoff = ExponentialBackoff {
current_interval: Duration::from_millis(INITIAL_INTERVAL),
initial_interval: Duration::from_millis(INITIAL_INTERVAL),
randomization_factor: DEFAULT_RANDOMIZATION,
multiplier: DEFAULT_MULTIPLIER,
max_interval,
max_elapsed_time: None,
clock: Default::default(),
start_time: Instant::now(),
};
RetryBackoff {
backoff,
attempt: 0,
}
}
pub fn reset(&mut self) {
self.backoff.reset();
self.attempt = 0;
}
pub fn started(&self) -> bool {
self.attempt > 0
}
pub fn attempt(&self) -> usize {
self.attempt
}
pub fn next_backoff(&mut self) -> Duration {
let duration = match self.attempt {
0 => Duration::new(0, 0),
_ => self.backoff.next_backoff().unwrap(),
};
self.attempt += 1;
duration
}
}