zc2 0.0.51

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! The owner-activity signal (ADR ZC-0017 amendment, `when = "idle"`).
//!
//! The agent computes it once (`agent::owner`: HID idle, AC power and memory
//! pressure on macOS; the logind idle hint and PSI on Linux) and mirrors it to
//! `owner.json` under the zakuro home. The broker is another process: its
//! admission check reads the file here, so every job source (peer offers,
//! Spaces, hub allocation, environment guests) honours the same signal.
//!
//! Fail safe: a file that is older than the staleness bound means the agent
//! stopped publishing, and the owner is assumed active. No file at all means no
//! agent has ever published here (a broker on a server or in a pod): there is
//! nothing to honour, so the node behaves as before.

use serde::{Deserialize, Serialize};
use std::path::Path;

pub const FILE: &str = "owner.json";
/// The agent publishes every watchdog tick (15 s); six missed ticks is stale.
pub const DEFAULT_STALE_SECS: u64 = 90;

/// What the agent last saw of the machine's owner.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Snapshot {
    /// No keyboard or mouse (or no local login session in use) for the idle
    /// window.
    pub idle: bool,
    /// On battery while `budget.on_ac_only` is set.
    #[serde(default)]
    pub on_battery: bool,
    #[serde(default)]
    pub memory_pressure: bool,
    /// The CPU is contended by something other than lending (Linux PSI).
    #[serde(default)]
    pub cpu_pressure: bool,
    /// Unix seconds when it was computed.
    pub at: u64,
    /// Which probe produced it (`macos`, `linux`).
    #[serde(default)]
    pub source: String,
}

/// What the admission check makes of the signal.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Owner {
    /// Nobody publishes a signal here: nothing to honour.
    NoSignal,
    Calm,
    /// The owner is at the machine (or the signal went stale): refuses foreign
    /// work only when `when = "idle"`.
    Active(&'static str),
    /// On battery or under memory pressure: refuses foreign work whatever
    /// `when` says, as the host-runner watchdog yields on them.
    Yielding(&'static str),
}

impl Owner {
    /// Why foreign work is refused now under `when`, if it is.
    pub fn blocks(&self, when: &str) -> Option<&'static str> {
        match self {
            Owner::Yielding(r) => Some(r),
            Owner::Active(r) if when == "idle" => Some(r),
            _ => None,
        }
    }
}

impl Snapshot {
    pub fn owner(&self) -> Owner {
        if self.on_battery {
            Owner::Yielding("on-battery")
        } else if self.memory_pressure {
            Owner::Yielding("memory-pressure")
        } else if self.cpu_pressure {
            Owner::Yielding("cpu-pressure")
        } else if !self.idle {
            Owner::Active("owner-active")
        } else {
            Owner::Calm
        }
    }
}

/// `ZAKURO_OWNER_STALE_SECS` (default 90).
pub fn stale_secs() -> u64 {
    std::env::var("ZAKURO_OWNER_STALE_SECS")
        .ok()
        .and_then(|v| v.trim().parse().ok())
        .filter(|s| *s > 0)
        .unwrap_or(DEFAULT_STALE_SECS)
}

/// The signal at `home` as of `now_secs`.
pub fn read(home: &Path, now_secs: u64, stale_secs: u64) -> Owner {
    let Ok(text) = std::fs::read_to_string(home.join(FILE)) else {
        return Owner::NoSignal;
    };
    // A file that exists but does not parse is as good as a stale one.
    let Ok(s) = serde_json::from_str::<Snapshot>(&text) else {
        return Owner::Active("signal-stale");
    };
    if now_secs.saturating_sub(s.at) > stale_secs {
        return Owner::Active("signal-stale");
    }
    s.owner()
}

/// Why foreign work must yield to the owner at `home` right now under `when`
/// (read live, no cache): what the desktop shows as "Paused: you're using
/// this Mac". `None` when it need not.
pub fn live_yield(home: &Path, when: &str) -> Option<&'static str> {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    read(home, now, stale_secs()).blocks(when)
}

pub fn write(home: &Path, s: &Snapshot) -> std::io::Result<()> {
    std::fs::create_dir_all(home)?;
    let tmp = home.join(".owner.json.tmp");
    std::fs::write(&tmp, serde_json::to_string(s).unwrap_or_default())?;
    std::fs::rename(&tmp, home.join(FILE))
}

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

    fn snap(idle: bool, at: u64) -> Snapshot {
        Snapshot {
            idle,
            on_battery: false,
            memory_pressure: false,
            cpu_pressure: false,
            at,
            source: "test".into(),
        }
    }

    #[test]
    fn no_file_means_no_signal_not_an_active_owner() {
        let d = crate::policy::test_home();
        assert_eq!(read(&d, 1000, 90), Owner::NoSignal);
    }

    #[test]
    fn a_fresh_snapshot_is_read_and_a_stale_one_means_active() {
        let d = crate::policy::test_home();
        write(&d, &snap(true, 1000)).unwrap();
        assert_eq!(read(&d, 1060, 90), Owner::Calm);
        assert_eq!(read(&d, 1090, 90), Owner::Calm, "at the bound is fresh");
        assert_eq!(read(&d, 1091, 90), Owner::Active("signal-stale"));
        write(&d, &snap(false, 1000)).unwrap();
        assert_eq!(read(&d, 1001, 90), Owner::Active("owner-active"));
    }

    #[test]
    fn a_torn_file_fails_safe() {
        let d = crate::policy::test_home();
        std::fs::write(d.join(FILE), "{not json").unwrap();
        assert_eq!(read(&d, 5, 90), Owner::Active("signal-stale"));
    }

    #[test]
    fn battery_and_pressure_yield_whatever_when_says_and_activity_only_for_idle() {
        let mut s = snap(true, 0);
        s.on_battery = true;
        assert_eq!(s.owner().blocks("always"), Some("on-battery"));
        let mut s = snap(true, 0);
        s.memory_pressure = true;
        assert_eq!(s.owner().blocks("schedule"), Some("memory-pressure"));
        let busy = snap(false, 0).owner();
        assert_eq!(busy.blocks("idle"), Some("owner-active"));
        assert_eq!(busy.blocks("always"), None);
        assert_eq!(busy.blocks("schedule"), None);
        assert_eq!(Owner::NoSignal.blocks("idle"), None);
        assert_eq!(Owner::Calm.blocks("idle"), None);
    }
}