mouser_mode_api/
supervisor.rs1use std::time::{Duration, Instant};
9
10pub const WINDOW: Duration = Duration::from_secs(30);
12pub const DEFAULT_MAX_RESTARTS: u32 = 3;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum Decision {
16 Restart(Duration),
18 GiveUp,
20}
21
22#[derive(Debug, Clone)]
23pub struct Restarts {
24 max: u32,
25 unit: Duration,
27 crashes: Vec<Instant>,
28 gave_up: bool,
29}
30
31impl Restarts {
32 pub fn new(max_restarts: u32) -> Self {
33 Self::with_unit(max_restarts, Duration::from_secs(1))
34 }
35
36 pub fn with_unit(max_restarts: u32, unit: Duration) -> Self {
38 Self { max: max_restarts, unit, crashes: Vec::new(), gave_up: false }
39 }
40
41 pub fn crashed(&mut self, now: Instant) -> Decision {
43 if self.gave_up {
44 return Decision::GiveUp;
45 }
46 self.crashes.retain(|t| now.duration_since(*t) < WINDOW);
47 self.crashes.push(now);
48 let n = self.crashes.len() as u32;
49 if n > self.max {
50 self.gave_up = true;
51 return Decision::GiveUp;
52 }
53 Decision::Restart(self.unit * (1u32 << (n - 1).min(6)))
54 }
55
56 pub fn gave_up(&self) -> bool {
57 self.gave_up
58 }
59
60 pub fn reset(&mut self) {
62 self.crashes.clear();
63 self.gave_up = false;
64 }
65}
66
67impl Default for Restarts {
68 fn default() -> Self {
69 Self::new(DEFAULT_MAX_RESTARTS)
70 }
71}