zc2 0.0.51

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! `zc policy [show|set k=v ...]`, `zc budget [--cpu --memory --gpu --disk]`
//! and `zc ledger`. Verbs that change local state go through the agent when it
//! runs (ADR ZC-0019 ยง5) and otherwise do the same work here under the same
//! lock, so behaviour never depends on whether the app is open.

use crate::sandbox::HostResources;
use serde_json::{json, Value};

/// Keys whose value is always text, even when it looks like a number.
const TEXT_KEYS: [&str; 6] = [
    "sharing.when",
    "budget.cpu",
    "budget.memory",
    "budget.vram",
    "budget.disk",
    "cleanup.idle_ttl",
];
/// Keys that hold a list: a bare word or `a,b` is a list.
const LIST_KEYS: [&str; 4] = [
    "sharing.squads",
    "sharing.schedule",
    "runtime.prefer",
    "upstreams.peers",
];

/// One `key=value` as `(dotted key, JSON value)`.
pub fn parse_pair(arg: &str) -> Result<(String, Value), String> {
    let (k, v) = arg
        .split_once('=')
        .ok_or_else(|| format!("{arg:?}: expected key=value (zc policy show lists the keys)"))?;
    let (k, v) = (k.trim(), v.trim());
    if !k.contains('.') {
        return Err(format!("{k:?}: name a section, as in sharing.when"));
    }
    let val = if TEXT_KEYS.contains(&k) {
        json!(v)
    } else if LIST_KEYS.contains(&k) || k == "workloads.atelier" {
        if v.starts_with('[') {
            serde_json::from_str(v).map_err(|e| format!("{k}: {e}"))?
        } else if k == "workloads.atelier" && matches!(v, "true" | "false" | "gpu-only") {
            match v {
                "gpu-only" => json!("gpu-only"),
                b => json!(b == "true"),
            }
        } else {
            json!(v
                .split(',')
                .map(str::trim)
                .filter(|s| !s.is_empty())
                .collect::<Vec<_>>())
        }
    } else if let Ok(b) = v.parse::<bool>() {
        json!(b)
    } else if let Ok(n) = v.parse::<i64>() {
        json!(n)
    } else if let Ok(f) = v.parse::<f64>() {
        json!(f)
    } else {
        json!(v)
    };
    Ok((k.to_string(), val))
}

/// The nested patch for `k=v` arguments.
pub fn patch_from(args: &[String]) -> Result<Value, String> {
    let mut root = json!({});
    for a in args {
        let (k, v) = parse_pair(a)?;
        let mut cur = &mut root;
        let parts: Vec<&str> = k.split('.').collect();
        for (i, p) in parts.iter().enumerate() {
            if i + 1 == parts.len() {
                cur[*p] = v.clone();
            } else {
                if !cur[*p].is_object() {
                    cur[*p] = json!({});
                }
                cur = &mut cur[*p];
            }
        }
    }
    Ok(root)
}

/// `zc budget` flags as a patch (`--gpu` alone is on; `--gpu off`, `--no-gpu`).
pub fn budget_patch(args: &[String]) -> Result<Value, String> {
    let mut pairs = Vec::new();
    let mut it = args.iter().peekable();
    while let Some(a) = it.next() {
        let (flag, inline) = match a.split_once('=') {
            Some((f, v)) => (f, Some(v.to_string())),
            None => (a.as_str(), None),
        };
        let key = match flag {
            "--cpu" => "budget.cpu",
            "--memory" => "budget.memory",
            "--disk" => "budget.disk",
            "--vram" => "budget.vram",
            "--gpu" => "budget.gpu",
            "--no-gpu" => {
                pairs.push("budget.gpu=false".to_string());
                continue;
            }
            other => return Err(format!("unknown argument {other:?}")),
        };
        let val = match (inline, key) {
            (Some(v), _) => v,
            (None, "budget.gpu") => match it.peek().map(|s| s.as_str()) {
                Some("on" | "true" | "yes") => {
                    it.next();
                    "true".into()
                }
                Some("off" | "false" | "no") => {
                    it.next();
                    "false".into()
                }
                _ => "true".into(),
            },
            (None, _) => it
                .next()
                .cloned()
                .ok_or_else(|| format!("{flag} needs a value"))?,
        };
        let val = match val.as_str() {
            "on" | "yes" if key == "budget.gpu" => "true".into(),
            "off" | "no" if key == "budget.gpu" => "false".into(),
            _ => val,
        };
        pairs.push(format!("{key}={val}"));
    }
    patch_from(&pairs)
}

/// Apply `patch`: through the agent when it runs, else directly.
fn apply(patch: Value) -> Result<Value, String> {
    #[cfg(unix)]
    if let Some(c) = crate::agent::client::AgentClient::running() {
        return c.put("/v2/policy", patch, std::time::Duration::from_secs(10));
    }
    let home = crate::credentials::dir().ok_or("no HOME or ZAKURO_HOME")?;
    let (p, changed) = crate::policy::update_partial(&home, &patch, Some(&HostResources::detect()))
        .map_err(|e| e.to_string())?;
    Ok(json!({"policy": p, "revision": p.revision, "changed": changed}))
}

fn read() -> Result<Value, String> {
    #[cfg(unix)]
    if let Some(c) = crate::agent::client::AgentClient::running() {
        return c.get("/v2/policy", std::time::Duration::from_secs(10));
    }
    let home = crate::credentials::dir().ok_or("no HOME or ZAKURO_HOME")?;
    let p = crate::policy::load(&home)?;
    Ok(json!({"policy": p, "revision": p.revision}))
}

fn show(v: &Value, json_out: bool) {
    if json_out {
        println!("{}", serde_json::to_string_pretty(v).unwrap_or_default());
        return;
    }
    let p: Option<crate::policy::Policy> = serde_json::from_value(v["policy"].clone()).ok();
    match p {
        Some(p) => {
            print!("{}", toml::to_string_pretty(&p).unwrap_or_default());
            if let Some(b) = v["effective"]["budget"].as_object() {
                println!("\n# effective budget: {}", Value::Object(b.clone()));
            }
            if let Some(o) = v["effective"]["env_overrides"]
                .as_array()
                .filter(|o| !o.is_empty())
            {
                println!(
                    "# still overridden by deprecated variables: {}",
                    Value::Array(o.clone())
                );
            }
        }
        None => println!("{v}"),
    }
}

pub fn run_policy(args: &[String], json_out: bool) -> i32 {
    let r = match args.first().map(String::as_str).unwrap_or("show") {
        "show" => read().map(|v| show(&v, json_out)),
        "set" if args.len() > 1 => patch_from(&args[1..]).and_then(apply).map(|v| {
            if json_out {
                show(&v, true);
            } else if v["changed"] == false {
                println!("policy unchanged (revision {})", v["revision"]);
            } else {
                println!("policy updated (revision {})", v["revision"]);
            }
        }),
        _ => Err("usage: zc policy [show | set <section.key>=<value> ...]".into()),
    };
    match r {
        Ok(()) => 0,
        Err(e) => {
            eprintln!("zc: {e}");
            1
        }
    }
}

pub fn run_budget(args: &[String], json_out: bool) -> i32 {
    if args.is_empty() {
        return run_policy(&["show".into()], json_out);
    }
    match budget_patch(args).and_then(apply) {
        Ok(v) => {
            println!(
                "budget {} (revision {})",
                if v["changed"] == false {
                    "unchanged"
                } else {
                    "updated"
                },
                v["revision"]
            );
            0
        }
        Err(e) => {
            eprintln!("zc: {e}");
            1
        }
    }
}

/// `zc ledger [--by day|product|node] [--from D] [--to D] [--json]`.
pub fn run_ledger(args: &[String], json_out: bool) -> i32 {
    let (mut by, mut from, mut to) = ("day".to_string(), None, None);
    let mut it = args.iter();
    while let Some(a) = it.next() {
        let (f, inline) = match a.split_once('=') {
            Some((f, v)) => (f, Some(v.to_string())),
            None => (a.as_str(), None),
        };
        let mut val = || inline.clone().or_else(|| it.next().cloned());
        match f {
            "--by" => by = val().unwrap_or_default(),
            "--from" => from = val(),
            "--to" => to = val(),
            "--json" => {}
            o => {
                eprintln!("zc: unknown argument {o:?}");
                return 2;
            }
        }
    }
    let mut path = format!("/v2/ledger?by={by}");
    if let Some(f) = from {
        path += &format!("&from={f}");
    }
    if let Some(t) = to {
        path += &format!("&to={t}");
    }
    #[cfg(unix)]
    let res = match crate::agent::client::AgentClient::running() {
        Some(c) => c.get(&path, std::time::Duration::from_secs(20)),
        None => Err("the ledger comes from the hub through the zc agent: start it with `zc agent run` (or the app)".into()),
    };
    #[cfg(not(unix))]
    let res: Result<Value, String> =
        Err("zc ledger needs the zc agent, not built on this platform".into());
    match res {
        Ok(v) if json_out => {
            println!("{}", serde_json::to_string_pretty(&v).unwrap_or_default());
            0
        }
        Ok(v) => {
            println!("by {} (yen)", v["by"].as_str().unwrap_or(&by));
            for g in v["groups"].as_array().cloned().unwrap_or_default() {
                let key = g[&by[..]].as_str().unwrap_or("-");
                println!(
                    "  {key:<24} earned {:>10.2}  spent {:>10.2}",
                    g["earned"].as_f64().unwrap_or(0.0),
                    g["spent"].as_f64().unwrap_or(0.0)
                );
            }
            println!(
                "  {:<24} earned {:>10.2}  spent {:>10.2}",
                "total",
                v["totals"]["earned"].as_f64().unwrap_or(0.0),
                v["totals"]["spent"].as_f64().unwrap_or(0.0)
            );
            0
        }
        Err(e) => {
            eprintln!("zc: {e}");
            1
        }
    }
}

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

    fn s(v: &[&str]) -> Vec<String> {
        v.iter().map(|x| x.to_string()).collect()
    }

    #[test]
    fn set_pairs_become_a_typed_nested_patch() {
        let p = patch_from(&s(&[
            "sharing.when=always",
            "sharing.min_price=2.5",
            "sharing.squads=public,lab",
            "workloads.spaces=false",
            "workloads.atelier=gpu-only",
            "budget.cpu=4",
            "budget.memory=50%",
        ]))
        .unwrap();
        assert_eq!(p["sharing"]["when"], "always");
        assert_eq!(p["sharing"]["min_price"], 2.5);
        assert_eq!(p["sharing"]["squads"], json!(["public", "lab"]));
        assert_eq!(p["workloads"]["spaces"], false);
        assert_eq!(p["workloads"]["atelier"], "gpu-only");
        assert_eq!(p["budget"]["cpu"], "4", "budget values are text");
        assert_eq!(
            patch_from(&s(&["sharing.squads=[]"])).unwrap()["sharing"]["squads"],
            json!([])
        );
        assert_eq!(
            patch_from(&s(&["sharing.min_price=-1"])).unwrap()["sharing"]["min_price"],
            -1
        );
        assert_eq!(
            patch_from(&s(&["workloads.atelier=peft,ludwig"])).unwrap()["workloads"]["atelier"],
            json!(["peft", "ludwig"])
        );
        assert!(patch_from(&s(&["nope"])).is_err());
        assert!(patch_from(&s(&["when=idle"])).is_err());
    }

    #[test]
    fn budget_flags_become_budget_keys() {
        let p = budget_patch(&s(&[
            "--cpu",
            "4",
            "--memory=8G",
            "--gpu",
            "--disk",
            "100G",
        ]))
        .unwrap();
        assert_eq!(
            p["budget"],
            json!({"cpu": "4", "memory": "8G", "gpu": true, "disk": "100G"})
        );
        assert_eq!(
            budget_patch(&s(&["--gpu", "off"])).unwrap()["budget"]["gpu"],
            false
        );
        assert_eq!(
            budget_patch(&s(&["--no-gpu"])).unwrap()["budget"]["gpu"],
            false
        );
        assert!(budget_patch(&s(&["--cores", "2"])).is_err());
        assert!(budget_patch(&s(&["--cpu"])).is_err());
    }

    #[test]
    fn the_direct_path_applies_a_patch_under_the_store_rules() {
        let home = crate::policy::test_home();
        let patch = patch_from(&s(&["sharing.when=always", "budget.gpu=true"])).unwrap();
        let (p, changed) = crate::policy::update_partial(&home, &patch, None).unwrap();
        assert!(changed && p.budget.gpu && p.sharing.when == "always");
        let bad = patch_from(&s(&["sharing.when=never"])).unwrap();
        assert!(crate::policy::update_partial(&home, &bad, None).is_err());
    }
}