use std::time::{Duration, Instant};
pub const WINDOW: Duration = Duration::from_secs(30);
pub const DEFAULT_MAX_RESTARTS: u32 = 3;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Decision {
Restart(Duration),
GiveUp,
}
#[derive(Debug, Clone)]
pub struct Restarts {
max: u32,
unit: Duration,
crashes: Vec<Instant>,
gave_up: bool,
}
impl Restarts {
pub fn new(max_restarts: u32) -> Self {
Self::with_unit(max_restarts, Duration::from_secs(1))
}
pub fn with_unit(max_restarts: u32, unit: Duration) -> Self {
Self { max: max_restarts, unit, crashes: Vec::new(), gave_up: false }
}
pub fn crashed(&mut self, now: Instant) -> Decision {
if self.gave_up {
return Decision::GiveUp;
}
self.crashes.retain(|t| now.duration_since(*t) < WINDOW);
self.crashes.push(now);
let n = self.crashes.len() as u32;
if n > self.max {
self.gave_up = true;
return Decision::GiveUp;
}
Decision::Restart(self.unit * (1u32 << (n - 1).min(6)))
}
pub fn gave_up(&self) -> bool {
self.gave_up
}
pub fn reset(&mut self) {
self.crashes.clear();
self.gave_up = false;
}
}
impl Default for Restarts {
fn default() -> Self {
Self::new(DEFAULT_MAX_RESTARTS)
}
}