Skip to main content

zero_headless/
state.rs

1//! Persistent supervisor state under the operator-local
2//! `state/headless.json`.
3//!
4//! # Why persist
5//!
6//! Without persistence, a daemon crash-and-respawn would default
7//! to "off" — silently reverting the operator's stated intent.
8//! The M2 spec rejects that: if the operator asked for the
9//! supervisor to be armed, a restart must reinstate that posture
10//! and the operator's next `/headless status` must show
11//! "started", not "stopped".
12//!
13//! # Atomic writes
14//!
15//! Every state mutation is written via the classic
16//! *write-to-tempfile + `fsync` + `rename`* dance. Partial writes
17//! on power loss would otherwise leave the daemon with
18//! unparseable state, and the honest response to unparseable
19//! state is to refuse to start — not a great experience when
20//! the alternative is "safely lose the last change".
21//!
22//! # Wire format
23//!
24//! The on-disk format is deliberately the same JSON shape as
25//! the IPC protocol's state envelope. An operator who wants to
26//! see why the daemon started the way it did can just
27//! inspect the operator-local state file instead of learning a
28//! second schema.
29
30use std::fs;
31use std::io::{self, Write};
32use std::path::{Path, PathBuf};
33
34use chrono::{DateTime, Utc};
35use serde::{Deserialize, Serialize};
36use thiserror::Error;
37
38use crate::protocol::{ActionKind, ActionRecord, SupervisorState};
39
40/// How many recent actions to keep on disk. Spec wants
41/// `/headless status` to be able to show the last 3 under
42/// `headless_recent_actions`; we keep one extra slot as cheap
43/// context for debugging without turning the state file into
44/// an append-only log.
45pub const MAX_RECENT_ACTIONS: usize = 4;
46
47/// Persistent state shape. Kept intentionally small so the
48/// file is human-grippable under `cat`. Additions that don't
49/// alter the supervisor's recovery behaviour should stay out
50/// of this struct and into a sibling file.
51#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
52pub struct State {
53    /// Operator-intent: should the supervisor consider itself
54    /// "armed" on boot.
55    pub intent: SupervisorState,
56    /// Monotonically-updated bookkeeping timestamps.
57    pub last_updated: DateTime<Utc>,
58    /// Ring buffer of the most recent decisions, newest first.
59    /// Capped at [`MAX_RECENT_ACTIONS`] on every write.
60    pub recent_actions: Vec<ActionRecord>,
61}
62
63impl Default for State {
64    fn default() -> Self {
65        Self {
66            intent: SupervisorState::Off,
67            last_updated: Utc::now(),
68            recent_actions: Vec::new(),
69        }
70    }
71}
72
73#[derive(Debug, Error)]
74pub enum PersistError {
75    #[error("state i/o error at {path}: {source}")]
76    Io {
77        path: PathBuf,
78        #[source]
79        source: io::Error,
80    },
81    #[error("state file at {path} is unparseable: {source}")]
82    Parse {
83        path: PathBuf,
84        #[source]
85        source: serde_json::Error,
86    },
87}
88
89impl State {
90    /// Load from disk, or return `Default` if the file does not
91    /// exist yet. An *unparseable* file is an error, not a
92    /// silent reset — the daemon refuses to run rather than
93    /// forget the operator's intent.
94    pub fn load(path: &Path) -> Result<Self, PersistError> {
95        match fs::read(path) {
96            Ok(bytes) => serde_json::from_slice(&bytes).map_err(|source| PersistError::Parse {
97                path: path.to_path_buf(),
98                source,
99            }),
100            Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(Self::default()),
101            Err(source) => Err(PersistError::Io {
102                path: path.to_path_buf(),
103                source,
104            }),
105        }
106    }
107
108    /// Persist atomically. Creates parent directories if
109    /// missing; the daemon's lifecycle doesn't include a
110    /// separate "install" step that would create them.
111    pub fn save(&self, path: &Path) -> Result<(), PersistError> {
112        if let Some(parent) = path.parent() {
113            fs::create_dir_all(parent).map_err(|source| PersistError::Io {
114                path: parent.to_path_buf(),
115                source,
116            })?;
117        }
118
119        let tmp = sibling_tempfile(path);
120        let bytes = serde_json::to_vec_pretty(self).map_err(|source| PersistError::Parse {
121            path: path.to_path_buf(),
122            source,
123        })?;
124
125        {
126            let mut f = fs::File::create(&tmp).map_err(|source| PersistError::Io {
127                path: tmp.clone(),
128                source,
129            })?;
130            f.write_all(&bytes).map_err(|source| PersistError::Io {
131                path: tmp.clone(),
132                source,
133            })?;
134            f.sync_all().map_err(|source| PersistError::Io {
135                path: tmp.clone(),
136                source,
137            })?;
138        }
139
140        fs::rename(&tmp, path).map_err(|source| PersistError::Io {
141            path: path.to_path_buf(),
142            source,
143        })?;
144        Ok(())
145    }
146
147    /// Record an action, pushing it to the front of
148    /// `recent_actions` and trimming to cap. `note` must be
149    /// non-empty — the protocol forbids empty reasons and we
150    /// enforce it at the persistence boundary too.
151    pub fn push_action(&mut self, kind: ActionKind, note: impl Into<String>) {
152        let note = note.into();
153        debug_assert!(!note.is_empty(), "empty action note is a protocol lie");
154        let record = ActionRecord {
155            kind,
156            at: Utc::now(),
157            note,
158        };
159        self.recent_actions.insert(0, record);
160        if self.recent_actions.len() > MAX_RECENT_ACTIONS {
161            self.recent_actions.truncate(MAX_RECENT_ACTIONS);
162        }
163        self.last_updated = Utc::now();
164    }
165
166    /// Flip the intent flag and bump `last_updated`. Does not
167    /// push an action — the caller decides whether that edge
168    /// deserves a record (e.g. `Stop` during boot might not).
169    pub fn set_intent(&mut self, intent: SupervisorState) {
170        self.intent = intent;
171        self.last_updated = Utc::now();
172    }
173}
174
175fn sibling_tempfile(path: &Path) -> PathBuf {
176    let mut name = path
177        .file_name()
178        .map(std::ffi::OsStr::to_os_string)
179        .unwrap_or_default();
180    // Suffix rather than prefix so fs tools that sort by name
181    // still group the tempfile with its target.
182    name.push(".tmp");
183    match path.parent() {
184        Some(p) => p.join(name),
185        None => PathBuf::from(name),
186    }
187}
188
189#[cfg(test)]
190mod tests {
191    use super::*;
192    use tempfile::TempDir;
193
194    #[test]
195    fn load_missing_yields_default() {
196        let dir = TempDir::new().unwrap();
197        let path = dir.path().join("state/headless.json");
198        let s = State::load(&path).unwrap();
199        assert_eq!(s.intent, SupervisorState::Off);
200        assert!(s.recent_actions.is_empty());
201    }
202
203    #[test]
204    fn save_then_load_round_trips() {
205        let dir = TempDir::new().unwrap();
206        let path = dir.path().join("state/headless.json");
207        let mut s = State::default();
208        s.set_intent(SupervisorState::On);
209        s.push_action(ActionKind::Started, "boot");
210        s.save(&path).unwrap();
211
212        let back = State::load(&path).unwrap();
213        assert_eq!(back.intent, SupervisorState::On);
214        assert_eq!(back.recent_actions.len(), 1);
215        assert_eq!(back.recent_actions[0].kind, ActionKind::Started);
216        assert_eq!(back.recent_actions[0].note, "boot");
217    }
218
219    #[test]
220    fn recent_actions_cap_is_enforced() {
221        let mut s = State::default();
222        for i in 0..MAX_RECENT_ACTIONS + 3 {
223            s.push_action(ActionKind::Probed, format!("probe {i}"));
224        }
225        assert_eq!(s.recent_actions.len(), MAX_RECENT_ACTIONS);
226        assert_eq!(
227            s.recent_actions[0].note,
228            format!("probe {}", MAX_RECENT_ACTIONS + 2)
229        );
230    }
231
232    #[test]
233    fn unparseable_state_is_error_not_reset() {
234        let dir = TempDir::new().unwrap();
235        let path = dir.path().join("headless.json");
236        fs::write(&path, "{not json").unwrap();
237        let err = State::load(&path).unwrap_err();
238        assert!(matches!(err, PersistError::Parse { .. }));
239    }
240
241    #[test]
242    fn atomic_write_leaves_no_tempfile_behind() {
243        let dir = TempDir::new().unwrap();
244        let path = dir.path().join("state/headless.json");
245        State::default().save(&path).unwrap();
246        let tmp = path.with_file_name("headless.json.tmp");
247        assert!(!tmp.exists(), "tempfile not cleaned up: {tmp:?}");
248        assert!(path.exists());
249    }
250}