use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use crate::protocol::{ActionKind, ActionRecord, SupervisorState};
pub const MAX_RECENT_ACTIONS: usize = 4;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct State {
pub intent: SupervisorState,
pub last_updated: DateTime<Utc>,
pub recent_actions: Vec<ActionRecord>,
}
impl Default for State {
fn default() -> Self {
Self {
intent: SupervisorState::Off,
last_updated: Utc::now(),
recent_actions: Vec::new(),
}
}
}
#[derive(Debug, Error)]
pub enum PersistError {
#[error("state i/o error at {path}: {source}")]
Io {
path: PathBuf,
#[source]
source: io::Error,
},
#[error("state file at {path} is unparseable: {source}")]
Parse {
path: PathBuf,
#[source]
source: serde_json::Error,
},
}
impl State {
pub fn load(path: &Path) -> Result<Self, PersistError> {
match fs::read(path) {
Ok(bytes) => serde_json::from_slice(&bytes).map_err(|source| PersistError::Parse {
path: path.to_path_buf(),
source,
}),
Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(Self::default()),
Err(source) => Err(PersistError::Io {
path: path.to_path_buf(),
source,
}),
}
}
pub fn save(&self, path: &Path) -> Result<(), PersistError> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(|source| PersistError::Io {
path: parent.to_path_buf(),
source,
})?;
}
let tmp = sibling_tempfile(path);
let bytes = serde_json::to_vec_pretty(self).map_err(|source| PersistError::Parse {
path: path.to_path_buf(),
source,
})?;
{
let mut f = fs::File::create(&tmp).map_err(|source| PersistError::Io {
path: tmp.clone(),
source,
})?;
f.write_all(&bytes).map_err(|source| PersistError::Io {
path: tmp.clone(),
source,
})?;
f.sync_all().map_err(|source| PersistError::Io {
path: tmp.clone(),
source,
})?;
}
fs::rename(&tmp, path).map_err(|source| PersistError::Io {
path: path.to_path_buf(),
source,
})?;
Ok(())
}
pub fn push_action(&mut self, kind: ActionKind, note: impl Into<String>) {
let note = note.into();
debug_assert!(!note.is_empty(), "empty action note is a protocol lie");
let record = ActionRecord {
kind,
at: Utc::now(),
note,
};
self.recent_actions.insert(0, record);
if self.recent_actions.len() > MAX_RECENT_ACTIONS {
self.recent_actions.truncate(MAX_RECENT_ACTIONS);
}
self.last_updated = Utc::now();
}
pub fn set_intent(&mut self, intent: SupervisorState) {
self.intent = intent;
self.last_updated = Utc::now();
}
}
fn sibling_tempfile(path: &Path) -> PathBuf {
let mut name = path
.file_name()
.map(std::ffi::OsStr::to_os_string)
.unwrap_or_default();
name.push(".tmp");
match path.parent() {
Some(p) => p.join(name),
None => PathBuf::from(name),
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
#[test]
fn load_missing_yields_default() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("state/headless.json");
let s = State::load(&path).unwrap();
assert_eq!(s.intent, SupervisorState::Off);
assert!(s.recent_actions.is_empty());
}
#[test]
fn save_then_load_round_trips() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("state/headless.json");
let mut s = State::default();
s.set_intent(SupervisorState::On);
s.push_action(ActionKind::Started, "boot");
s.save(&path).unwrap();
let back = State::load(&path).unwrap();
assert_eq!(back.intent, SupervisorState::On);
assert_eq!(back.recent_actions.len(), 1);
assert_eq!(back.recent_actions[0].kind, ActionKind::Started);
assert_eq!(back.recent_actions[0].note, "boot");
}
#[test]
fn recent_actions_cap_is_enforced() {
let mut s = State::default();
for i in 0..MAX_RECENT_ACTIONS + 3 {
s.push_action(ActionKind::Probed, format!("probe {i}"));
}
assert_eq!(s.recent_actions.len(), MAX_RECENT_ACTIONS);
assert_eq!(
s.recent_actions[0].note,
format!("probe {}", MAX_RECENT_ACTIONS + 2)
);
}
#[test]
fn unparseable_state_is_error_not_reset() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("headless.json");
fs::write(&path, "{not json").unwrap();
let err = State::load(&path).unwrap_err();
assert!(matches!(err, PersistError::Parse { .. }));
}
#[test]
fn atomic_write_leaves_no_tempfile_behind() {
let dir = TempDir::new().unwrap();
let path = dir.path().join("state/headless.json");
State::default().save(&path).unwrap();
let tmp = path.with_file_name("headless.json.tmp");
assert!(!tmp.exists(), "tempfile not cleaned up: {tmp:?}");
assert!(path.exists());
}
}