use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use marathon_core::Timestamp;
use serde::Serialize;
use serde::de::DeserializeOwned;
use crate::ipc::support_dir;
pub fn rules_path() -> PathBuf {
support_dir().join("rules.json")
}
pub fn state_path() -> PathBuf {
support_dir().join("state.json")
}
pub fn launches_path() -> PathBuf {
support_dir().join("launches.json")
}
pub fn load<T: DeserializeOwned>(path: &Path) -> Option<T> {
fs::read(path)
.ok()
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
}
pub fn save<T: Serialize>(path: &Path, value: &T) -> io::Result<()> {
if let Some(dir) = path.parent() {
fs::create_dir_all(dir)?;
}
let tmp = path.with_extension("json.tmp");
fs::write(
&tmp,
serde_json::to_vec_pretty(value).map_err(io::Error::other)?,
)?;
fs::rename(tmp, path)
}
pub fn remove(path: &Path) -> io::Result<()> {
match fs::remove_file(path) {
Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e),
_ => Ok(()),
}
}
const LOOP_WINDOW: jiff::SignedDuration = jiff::SignedDuration::from_mins(5);
pub fn record_launch(path: &Path, now: Timestamp) -> usize {
let mut launches: Vec<Timestamp> = load(path).unwrap_or_default();
launches.retain(|&t| t <= now && now.duration_since(t) < LOOP_WINDOW);
launches.push(now);
let _ = save(path, &launches);
launches.len()
}
#[cfg(test)]
mod tests {
use super::*;
use marathon_core::rules::Rules;
fn scratch(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("marathon-{name}-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
dir
}
#[test]
fn round_trip_and_missing_file() {
let dir = scratch("store");
let path = dir.join("rules.json");
assert_eq!(load::<Rules>(&path), None);
let rules = Rules {
apps: vec!["Zoom".into()],
on_ac_power: true,
..Rules::default()
};
save(&path, &rules).unwrap();
assert_eq!(load(&path), Some(rules));
fs::write(&path, "not json").unwrap();
assert_eq!(load::<Rules>(&path), None);
remove(&path).unwrap();
remove(&path).unwrap();
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn launches_count_only_recent_ones() {
let dir = scratch("launches");
let path = dir.join("launches.json");
let t = |s: &str| s.parse::<Timestamp>().unwrap();
assert_eq!(record_launch(&path, t("2026-12-03T10:00:00Z")), 1);
assert_eq!(record_launch(&path, t("2026-12-03T10:00:15Z")), 2);
assert_eq!(record_launch(&path, t("2026-12-03T10:00:30Z")), 3);
assert_eq!(record_launch(&path, t("2026-12-03T10:10:30Z")), 1);
remove(&path).unwrap();
assert_eq!(record_launch(&path, t("2026-12-03T10:10:45Z")), 1);
fs::remove_dir_all(dir).unwrap();
}
}