1use 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
40pub const MAX_RECENT_ACTIONS: usize = 4;
46
47#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
52pub struct State {
53 pub intent: SupervisorState,
56 pub last_updated: DateTime<Utc>,
58 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 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 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 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 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 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}