zc2 0.0.47

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! `GET /v2/policy` and `PUT /v2/policy` (ADR ZC-0019 ยง2) as plain functions
//! over the policy store, so they are tested without a server.

use crate::agent::hosting_api::ApiErr;
use crate::policy::{self, UpdateError};
use crate::sandbox::HostResources;
use serde_json::{json, Value};
use std::path::Path;

fn err(status: u16, code: &'static str, message: impl Into<String>) -> ApiErr {
    ApiErr {
        status,
        code,
        message: message.into(),
    }
}

/// The effective policy: the document with its revision, what the budget
/// comes to on this machine (the deprecated `ZAKURO_BUDGET_*` variables still
/// win over the file, and are listed), and whether a resize is pending.
pub fn view(
    home: &Path,
    host: &HostResources,
    env: &dyn Fn(&str) -> Option<String>,
) -> Result<Value, ApiErr> {
    let p = policy::load(home).map_err(|e| err(500, "policy_file", e))?;
    let effective = match p
        .effective_budget(env)
        .and_then(|b| b.total(host).map(|t| (b, t)))
    {
        Ok((b, total)) => json!({
            "cpu_millis": total.cpu_millis,
            "memory_bytes": total.memory_bytes,
            "disk_bytes": b.disk_bytes,
            "gpu": b.gpu.flag_value().is_some(),
        }),
        Err(e) => json!({ "error": e }),
    };
    Ok(json!({
        "policy": p,
        "revision": p.revision,
        "effective": { "budget": effective, "env_overrides": policy::env_budget_overrides(env) },
        // The sandbox's resize (ZC-0018) is not built yet (zc#510).
        "resize_pending": false,
    }))
}

/// `PUT /v2/policy`: a partial document merged over the stored one, checked
/// against this hardware. A `revision` in it must be the current one (409
/// otherwise). Answers the new view plus `changed`.
pub fn put(
    home: &Path,
    body: &Value,
    host: &HostResources,
    env: &dyn Fn(&str) -> Option<String>,
) -> Result<Value, ApiErr> {
    if !body.is_object() {
        return Err(err(400, "invalid_input", "the body must be a JSON object"));
    }
    match policy::update_partial(home, body, Some(host)) {
        Ok((_, changed)) => {
            let mut v = view(home, host, env)?;
            v["changed"] = json!(changed);
            Ok(v)
        }
        Err(e @ UpdateError::Stale { .. }) => Err(err(409, "stale_revision", e.to_string())),
        Err(UpdateError::Invalid(m)) => Err(err(400, "invalid_input", m)),
        Err(UpdateError::Io(m)) => Err(err(500, "policy_file", m)),
    }
}

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

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

    fn none(_: &str) -> Option<String> {
        None
    }

    #[test]
    fn get_returns_the_policy_the_revision_and_the_budget_in_numbers() {
        let home = policy::test_home();
        let v = view(&home, &host(), &none).unwrap();
        assert_eq!(v["revision"], 1);
        assert_eq!(v["policy"]["sharing"]["squads"], json!(["public"]));
        assert_eq!(v["policy"]["workloads"]["atelier"], true);
        assert_eq!(v["effective"]["budget"]["cpu_millis"], 4000);
        assert_eq!(v["effective"]["budget"]["memory_bytes"], 8u64 << 30);
        assert_eq!(
            v["effective"]["budget"]["gpu"], true,
            "design D2: on by default"
        );
        assert_eq!(v["resize_pending"], false);
        assert_eq!(v["effective"]["env_overrides"], json!([]));
    }

    #[test]
    fn get_lists_the_environment_variables_that_still_win() {
        let home = policy::test_home();
        let env = |k: &str| (k == "ZAKURO_BUDGET_CPU").then(|| "2".to_string());
        let v = view(&home, &host(), &env).unwrap();
        assert_eq!(v["effective"]["budget"]["cpu_millis"], 2000);
        assert_eq!(
            v["effective"]["env_overrides"],
            json!(["ZAKURO_BUDGET_CPU"])
        );
        assert_eq!(
            v["policy"]["budget"]["cpu"], "50%",
            "the file itself is unchanged"
        );
    }

    #[test]
    fn put_merges_validates_and_bumps_the_revision() {
        let home = policy::test_home();
        let v = put(
            &home,
            &json!({"revision": 1, "sharing": {"min_price": 3.5}, "budget": {"gpu": true}}),
            &host(),
            &none,
        )
        .unwrap();
        assert_eq!(v["changed"], true);
        assert_eq!(v["revision"], 2);
        assert_eq!(v["policy"]["sharing"]["min_price"], 3.5);
        assert_eq!(v["effective"]["budget"]["gpu"], true);
        // The same document again: nothing changes, the revision stays.
        let v = put(
            &home,
            &json!({"sharing": {"min_price": 3.5}}),
            &host(),
            &none,
        )
        .unwrap();
        assert_eq!(
            (v["changed"].as_bool(), v["revision"].as_u64()),
            (Some(false), Some(2))
        );
    }

    #[test]
    fn put_with_a_stale_revision_is_409_and_changes_nothing() {
        let home = policy::test_home();
        put(
            &home,
            &json!({"sharing": {"when": "always"}}),
            &host(),
            &none,
        )
        .unwrap();
        let e = put(
            &home,
            &json!({"revision": 1, "sharing": {"when": "idle"}}),
            &host(),
            &none,
        )
        .unwrap_err();
        assert_eq!((e.status, e.code), (409, "stale_revision"));
        assert!(e.message.contains("revision is now 2"), "{}", e.message);
        assert_eq!(policy::load(&home).unwrap().sharing.when, "always");
    }

    #[test]
    fn put_refuses_unknown_keys_bad_values_and_a_budget_past_the_hardware() {
        let home = policy::test_home();
        let e = put(&home, &json!({"sharing": {"squad": []}}), &host(), &none).unwrap_err();
        assert_eq!((e.status, e.code), (400, "invalid_input"));
        assert!(e.message.contains("squad"), "{}", e.message);
        let e = put(
            &home,
            &json!({"sharing": {"when": "never"}}),
            &host(),
            &none,
        )
        .unwrap_err();
        assert!(e.message.contains("sharing.when"), "{}", e.message);
        let e = put(&home, &json!({"budget": {"cpu": "64"}}), &host(), &none).unwrap_err();
        assert!(e.message.contains("8 logical"), "{}", e.message);
        let e = put(&home, &json!([1]), &host(), &none).unwrap_err();
        assert_eq!(e.status, 400);
        assert_eq!(
            policy::load(&home).unwrap().revision,
            1,
            "nothing was written"
        );
    }
}