marathon-core 0.1.3

Marathon's rules: sessions, timers, triggers and time parsing
Documentation
//! The local IPC protocol: one JSON request line, one JSON reply line.

use jiff::Timestamp;
use serde::{Deserialize, Serialize};

use crate::{Keeper, Mode, Session};

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "cmd", rename_all = "lowercase")]
pub enum Request {
    On {
        mode: Mode,
        until: Option<Timestamp>,
        source: String,
    },
    Off,
    Status,
    /// Stop and reply with the status from just before stopping, so the
    /// app can take the session over. Only the CLI's helper agrees.
    Release,
    /// The saved triggers changed (`marathon ai on`): the app reloads them.
    RulesChanged,
}

/// Which kind of process holds the assertion.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Holder {
    App,
    Cli,
}

/// What is keeping the Mac awake. Every key is always present in JSON
/// (`null` when unknown), so scripts can rely on the shape.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Status {
    pub active: bool,
    pub session: Option<Session>,
    /// Why a trigger keeps the Mac awake, e.g. "Xcode is running".
    pub trigger: Option<String>,
    /// A trigger the user turned off; it stays off until its reason changes.
    pub paused_trigger: Option<String>,
    /// The battery level Marathon turned off at, while still below the line.
    #[serde(default)]
    pub battery_low: Option<u8>,
    pub remaining_secs: Option<u64>,
    /// Who serves, or `None` when nothing is running.
    pub holder: Option<Holder>,
    pub pid: Option<u32>,
}

impl Status {
    /// The status of a running server.
    pub fn of(keeper: &Keeper, now: Timestamp, holder: Holder) -> Self {
        let session = keeper.session().cloned();
        Status {
            active: keeper.wanted().is_some(),
            trigger: keeper.rule().map(|r| r.reason()),
            paused_trigger: keeper.paused(),
            battery_low: keeper.battery_low(),
            remaining_secs: session
                .as_ref()
                .and_then(|s| s.remaining(now))
                // Whole seconds, rounded up like every countdown shown.
                .map(|d| d.as_millis().div_ceil(1000) as u64),
            session,
            holder: Some(holder),
            pid: Some(std::process::id()),
        }
    }

    /// "1h 23m left, until 17:30", or "no end time". `None` when off.
    pub fn time_left(&self, tz: &jiff::tz::TimeZone) -> Option<String> {
        let session = self.session.as_ref()?;
        Some(match (self.remaining_secs, session.until) {
            (Some(secs), Some(until)) => format!(
                "{} left, until {}",
                crate::format_remaining(std::time::Duration::from_secs(secs)),
                crate::format_clock(until, tz)
            ),
            _ => "no end time".into(),
        })
    }

    /// The status when nothing is serving.
    pub fn idle() -> Self {
        Status {
            active: false,
            session: None,
            trigger: None,
            paused_trigger: None,
            battery_low: None,
            remaining_secs: None,
            holder: None,
            pid: None,
        }
    }
}

/// A reply: the status after the request, or an error message.
pub type Reply = Result<Status, String>;

/// Encodes a message as one line of JSON, newline included.
pub fn to_line<T: Serialize>(msg: &T) -> String {
    let mut s = serde_json::to_string(msg).expect("protocol types always serialize");
    s.push('\n');
    s
}

/// Decodes one line of JSON.
pub fn from_line<T: for<'de> Deserialize<'de>>(line: &str) -> Result<T, String> {
    serde_json::from_str(line.trim()).map_err(|e| format!("bad message: {e}"))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn request_wire_format() {
        let r = Request::On {
            mode: Mode::System,
            until: None,
            source: "cli".into(),
        };
        let line = to_line(&r);
        assert_eq!(
            line,
            "{\"cmd\":\"on\",\"mode\":\"system\",\"until\":null,\"source\":\"cli\"}\n"
        );
        assert_eq!(from_line::<Request>(&line).unwrap(), r);
        assert_eq!(
            from_line::<Request>(r#"{"cmd":"off"}"#).unwrap(),
            Request::Off
        );
        assert!(from_line::<Request>("{").is_err());
    }

    #[test]
    fn status_round_trips_with_and_without_session() {
        let mut k = Keeper::default();
        let now: Timestamp = "2026-12-03T10:00:00Z".parse().unwrap();
        for st in [Status::of(&k, now, Holder::App), Status::idle()] {
            assert_eq!(from_line::<Status>(&to_line(&st)).unwrap(), st);
        }
        k.start(
            Session {
                mode: Mode::System,
                started: now,
                until: Some("2026-12-03T11:00:00Z".parse().unwrap()),
                source: "cli".into(),
            },
            now,
        );
        let st = Status::of(&k, now, Holder::Cli);
        let line = to_line(&st);
        assert!(line.contains("\"session\":{\"mode\":\"system\""), "{line}");
        assert_eq!(st.remaining_secs, Some(3600));
        assert_eq!(from_line::<Status>(&line).unwrap(), st);
    }
}