Skip to main content

subc_daemon/
terminal_ring.rs

1use std::{collections::VecDeque, sync::Arc};
2
3use crate::{
4    child_roster::DaemonShutdownFlag,
5    terminal_journal::{ring_history, TerminalJournal},
6};
7
8use subc_control::{TerminalDisposition, TerminalExitKind};
9
10const DEFAULT_MAX_ENTRIES: usize = 32;
11
12/// Fixed-size retention policy for one module's terminal exits.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub struct TerminalRingConfig {
15    max_entries: usize,
16}
17
18impl TerminalRingConfig {
19    /// A zero-sized history cannot answer whether an exit was observed, so clamp it
20    /// to one record instead of constructing a ring that lies by omission.
21    pub const fn new(max_entries: usize) -> Self {
22        Self {
23            max_entries: if max_entries == 0 { 1 } else { max_entries },
24        }
25    }
26}
27
28impl Default for TerminalRingConfig {
29    fn default() -> Self {
30        Self::new(DEFAULT_MAX_ENTRIES)
31    }
32}
33
34/// One observed child exit and the disposition chosen by its supervisor.
35#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
36pub struct TerminalRecord {
37    pub exit_code: Option<i32>,
38    pub exit_signal: Option<i32>,
39    pub at_ms: u64,
40    pub disposition: TerminalDisposition,
41    pub exit_kind: TerminalExitKind,
42    /// Why the supervisor chose this disposition, when the disposition alone
43    /// does not say. `failed` records the exhausted crash budget here, naming
44    /// the limit AND the window it was counted over, because a module stopped
45    /// by three crashes in ten minutes and one stopped by three crashes in a
46    /// week are the same `failed` and call for different reactions.
47    pub disposition_detail: Option<String>,
48}
49
50/// The retained terminal suffix for one module.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct TerminalHistorySnapshot {
53    pub daemon_started_at_ms: u64,
54    pub entries: Vec<TerminalRecord>,
55    pub dropped: u64,
56}
57
58/// A durable history read captured under the ring lock and finished after it.
59pub(crate) enum DurableHistoryRead {
60    RingOnly(TerminalHistorySnapshot),
61    Journal(Arc<TerminalJournal>, TerminalHistorySnapshot, u64),
62}
63
64impl DurableHistoryRead {
65    /// Blocking when a journal is configured: it reads journal files.
66    pub(crate) fn read(self, module_id: &str) -> subc_control::TerminalHistory {
67        match self {
68            Self::RingOnly(snapshot) => ring_history(snapshot, None),
69            Self::Journal(journal, snapshot, sequence) => {
70                journal.capture_read(snapshot, sequence).read(module_id)
71            }
72        }
73    }
74}
75
76/// Bounded terminal-exit history for one supervised module.
77///
78/// This belongs to the module rather than an individual child so a replacement
79/// process retains the exits that caused it to exist.
80#[derive(Debug)]
81pub struct TerminalRing {
82    journal: Option<Arc<TerminalJournal>>,
83    daemon_shutdown: Option<DaemonShutdownFlag>,
84    config: TerminalRingConfig,
85    daemon_started_at_ms: u64,
86    start_clock: Option<crate::clock::StartClock>,
87    entries: VecDeque<TerminalRecord>,
88    dropped: u64,
89}
90
91impl TerminalRing {
92    pub fn new(config: TerminalRingConfig, daemon_started_at_ms: u64) -> Self {
93        Self {
94            journal: None,
95            daemon_shutdown: None,
96            config,
97            daemon_started_at_ms,
98            start_clock: None,
99            entries: VecDeque::new(),
100            dropped: 0,
101        }
102    }
103
104    pub(crate) fn with_start_clock(mut self, clock: crate::clock::StartClock) -> Self {
105        self.start_clock = Some(clock);
106        self
107    }
108
109    pub(crate) fn with_journal(mut self, journal: Option<Arc<TerminalJournal>>) -> Self {
110        self.journal = journal;
111        self
112    }
113
114    pub(crate) fn with_daemon_shutdown(mut self, flag: DaemonShutdownFlag) -> Self {
115        self.daemon_shutdown = Some(flag);
116        self
117    }
118
119    /// Whether the daemon has begun its announced shutdown.
120    pub(crate) fn daemon_shutting_down(&self) -> bool {
121        self.daemon_shutdown
122            .as_ref()
123            .is_some_and(DaemonShutdownFlag::is_set)
124    }
125
126    /// Journal and retain one observed exit.
127    ///
128    /// An exit observed after the daemon began shutting down is recorded as
129    /// `daemon_shutdown` whichever path observed it (the reap after a crash, an
130    /// operator stop or restart in flight, a swap retiring its incumbent), so
131    /// no exit caused by the daemon going away reads as a module crash or a
132    /// pending restart. Any detail the caller gave is kept.
133    pub(crate) fn record_exit(&mut self, module_id: &str, mut entry: TerminalRecord) {
134        if self.daemon_shutting_down() {
135            entry.disposition = TerminalDisposition::DaemonShutdown;
136        }
137        self.append_journal(module_id, &entry);
138        self.push(entry);
139    }
140
141    pub(crate) fn append_journal(&self, module_id: &str, entry: &TerminalRecord) {
142        if let Some(journal) = &self.journal {
143            journal.append(module_id, entry);
144        }
145    }
146
147    /// Capture and read in one step, for tests that own the ring directly.
148    #[cfg(test)]
149    pub(crate) fn durable_history(&self, module_id: &str) -> subc_control::TerminalHistory {
150        if let Some(journal) = &self.journal {
151            journal.flush_for_test();
152        }
153        self.capture_durable_history().read(module_id)
154    }
155
156    /// Copy the ring and its journal cutoff without touching the filesystem.
157    pub(crate) fn capture_durable_history(&self) -> DurableHistoryRead {
158        match &self.journal {
159            Some(journal) => {
160                DurableHistoryRead::Journal(journal.clone(), self.snapshot(), journal.sequence())
161            }
162            None => DurableHistoryRead::RingOnly(self.snapshot()),
163        }
164    }
165
166    pub fn push(&mut self, entry: TerminalRecord) {
167        self.entries.push_back(entry);
168        while self.entries.len() > self.config.max_entries {
169            self.entries.pop_front();
170            self.dropped = self.dropped.saturating_add(1);
171        }
172    }
173
174    pub fn snapshot(&self) -> TerminalHistorySnapshot {
175        TerminalHistorySnapshot {
176            daemon_started_at_ms: self
177                .start_clock
178                .map_or(self.daemon_started_at_ms, |clock| clock.started_at_ms()),
179            entries: self.entries.iter().cloned().collect(),
180            dropped: self.dropped,
181        }
182    }
183}
184
185#[cfg(test)]
186mod tests {
187    use super::{TerminalRecord, TerminalRing, TerminalRingConfig};
188    use subc_control::{TerminalDisposition, TerminalExitKind};
189
190    fn record(at_ms: u64) -> TerminalRecord {
191        TerminalRecord {
192            exit_code: Some(1),
193            exit_signal: None,
194            at_ms,
195            disposition: TerminalDisposition::Restarting,
196            exit_kind: TerminalExitKind::Crash,
197            disposition_detail: None,
198        }
199    }
200
201    #[test]
202    fn the_ring_evicts_oldest_exits_and_counts_them() {
203        let mut ring = TerminalRing::new(TerminalRingConfig::new(2), 10);
204        ring.push(record(11));
205        ring.push(record(12));
206        ring.push(record(13));
207
208        let snapshot = ring.snapshot();
209        assert_eq!(snapshot.daemon_started_at_ms, 10);
210        assert_eq!(snapshot.dropped, 1);
211        assert_eq!(
212            snapshot
213                .entries
214                .iter()
215                .map(|entry| entry.at_ms)
216                .collect::<Vec<_>>(),
217            vec![12, 13]
218        );
219    }
220
221    #[test]
222    fn an_incoherent_zero_capacity_keeps_one_terminal() {
223        let mut ring = TerminalRing::new(TerminalRingConfig::new(0), 10);
224        ring.push(record(11));
225        ring.push(record(12));
226
227        let snapshot = ring.snapshot();
228        assert_eq!(snapshot.dropped, 1);
229        assert_eq!(snapshot.entries.len(), 1);
230        assert_eq!(snapshot.entries[0].at_ms, 12);
231    }
232}