zc2 0.0.53

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! The hub round trip (ADR ZC-0017 ยง4): the node is the source of truth and
//! the hub mirrors it.
//!
//! - Every register carries `policy`, the document with its `revision`
//!   (absent when the policy cannot be read: absent means "unchanged" there).
//! - The reply may carry `policy` too: the owner's hub-side edit, staged with
//!   a higher revision. It is validated against this hardware, saved, and
//!   reported back on the next register, which is what clears it at the hub.
//!   An equal or lower revision is ignored. A node that cannot reach the hub
//!   never gets here and keeps enforcing its local file.

use super::{apply_desired, load};
use crate::sandbox::HostResources;
use serde_json::Value;
use std::path::Path;

/// The `policy` value of the register payload.
pub fn payload(home: &Path) -> Option<Value> {
    match load(home) {
        Ok(p) => Some(p.to_hub_json()),
        Err(e) => {
            eprintln!("  [POLICY] not reporting a policy to the hub: {e}");
            None
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum Applied {
    /// The reply carried no policy.
    None,
    /// Not newer than the local one.
    Ignored,
    /// Saved at this revision.
    Saved(u64),
    /// Newer, but refused (the reason names the key).
    Refused(String),
}

/// Apply the `policy` of a register reply body.
pub fn apply_reply(home: &Path, body: &str, host: &HostResources) -> Applied {
    let Some(v) = serde_json::from_str::<Value>(body).ok() else {
        return Applied::None;
    };
    let Some(desired) = v.get("policy").filter(|p| p.is_object()) else {
        return Applied::None;
    };
    match apply_desired(home, desired, host) {
        Ok(None) => Applied::Ignored,
        Ok(Some(p)) => Applied::Saved(p.revision),
        Err(e) => Applied::Refused(e),
    }
}

/// [`apply_reply`], logged the way the broker's sync loop reports it.
pub fn apply_reply_logged(home: &Path, body: &str) {
    match apply_reply(home, body, &HostResources::detect()) {
        Applied::Saved(rev) => {
            println!("  [POLICY] applied the policy staged on the hub (revision {rev})")
        }
        Applied::Refused(e) => {
            eprintln!("  [POLICY] ignoring the policy staged on the hub: {e}")
        }
        Applied::None | Applied::Ignored => {}
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::policy::{test_home, MinPrice};

    fn host() -> HostResources {
        HostResources {
            logical_cpus: 8,
            memory_bytes: Some(16 << 30),
        }
    }

    #[test]
    fn the_payload_is_the_hub_object_with_the_revision() {
        let home = test_home();
        let v = payload(&home).unwrap();
        assert_eq!(v["revision"], 1);
        assert_eq!(v["sharing"]["squads"], serde_json::json!(["public"]));
    }

    #[test]
    fn an_unreadable_policy_is_left_out_of_the_payload() {
        let home = test_home();
        std::fs::write(crate::policy::path(&home), "version = [").unwrap();
        assert!(payload(&home).is_none());
    }

    #[test]
    fn a_higher_staged_revision_is_applied_and_reported_back_on_the_next_register() {
        let home = test_home();
        load(&home).unwrap();
        let body = r#"{"default_placement": null,
            "policy": {"revision": 4, "sharing": {"min_price": 3.0}, "workloads": {"spaces": false}}}"#;
        assert_eq!(apply_reply(&home, body, &host()), Applied::Saved(4));
        let p = load(&home).unwrap();
        assert_eq!(p.sharing.min_price, MinPrice::PerHour(3.0));
        assert!(!p.workloads.spaces);
        // The next register reports revision 4, which clears the hub's copy.
        assert_eq!(payload(&home).unwrap()["revision"], 4);
        assert_eq!(payload(&home).unwrap()["workloads"]["spaces"], false);
    }

    #[test]
    fn an_equal_or_lower_revision_and_a_missing_policy_change_nothing() {
        let home = test_home();
        crate::policy::update(&home, None, None, |p| {
            p.sharing.when = "always".into();
            Ok(())
        })
        .unwrap(); // revision 2
        for rev in [1, 2] {
            let body =
                format!(r#"{{"policy": {{"revision": {rev}, "sharing": {{"when": "idle"}}}}}}"#);
            assert_eq!(apply_reply(&home, &body, &host()), Applied::Ignored);
        }
        assert_eq!(load(&home).unwrap().sharing.when, "always");
        assert_eq!(
            apply_reply(&home, r#"{"policy": null}"#, &host()),
            Applied::None
        );
        assert_eq!(apply_reply(&home, "not json", &host()), Applied::None);
        assert_eq!(apply_reply(&home, "{}", &host()), Applied::None);
    }

    #[test]
    fn a_staged_policy_the_hardware_cannot_give_is_refused_and_the_local_one_kept() {
        let home = test_home();
        let before = load(&home).unwrap();
        let body = r#"{"policy": {"revision": 9, "budget": {"cpu": "64"}}}"#;
        match apply_reply(&home, body, &host()) {
            Applied::Refused(e) => assert!(e.contains("budget.cpu"), "{e}"),
            other => panic!("{other:?}"),
        }
        assert_eq!(load(&home).unwrap(), before);
    }
}