marathon-engine 0.1.1

The part of Marathon that runs: keeps the Mac awake, keeps time, answers the command
//! Files Marathon keeps in its support directory: the triggers
//! (`rules.json`), the live state to come back to after a crash
//! (`state.json`) and recent launches, to spot a crash loop
//! (`launches.json`). Every write replaces the file in one step.

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")
}

/// The value saved at `path`; `None` if the file is missing or unreadable.
pub fn load<T: DeserializeOwned>(path: &Path) -> Option<T> {
    fs::read(path)
        .ok()
        .and_then(|bytes| serde_json::from_slice(&bytes).ok())
}

/// Saves `value` to `path`, replacing the file in one step, so a crash
/// mid-write leaves the old file or the new one, never half of each.
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)
}

/// Removes the file at `path`; a missing file is fine.
pub fn remove(path: &Path) -> io::Result<()> {
    match fs::remove_file(path) {
        Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e),
        _ => Ok(()),
    }
}

/// How far back launches count towards a crash loop.
const LOOP_WINDOW: jiff::SignedDuration = jiff::SignedDuration::from_mins(5);

/// Records a launch at `now` and returns how many launches, this one
/// included, came within the last few minutes without a clean run in
/// between. The app clears the record once it has run for a while or
/// exits in an orderly way, so only crashes add up.
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);
        // Ten minutes later the old ones no longer count.
        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();
    }
}