Skip to main content

mouser_mode_api/
supervisor.rs

1//! Crash restarts for a mode plugin. The host respawns a plugin that exited
2//! or broke its pipe after a back-off of 1 s, 2 s, then 4 s. More than
3//! `max_restarts` crashes (preference, default 3) within [`WINDOW`] and it
4//! gives up: the plugin stays disabled and the status bar offers a restart
5//! ([`Restarts::reset`]). Shells never depend on this: they live in the
6//! session/PTY server.
7
8use std::time::{Duration, Instant};
9
10/// Crashes older than this are forgotten.
11pub 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    /// Respawn after this wait.
17    Restart(Duration),
18    /// Leave it disabled until the user restarts it.
19    GiveUp,
20}
21
22#[derive(Debug, Clone)]
23pub struct Restarts {
24    max: u32,
25    /// The first wait; each next one doubles (1 s, 2 s, 4 s).
26    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    /// Shorter waits (tests).
37    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    /// The plugin crashed at `now`: wait and restart, or give up.
42    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    /// The user pressed restart: start counting again.
61    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}