zc2 0.0.45

P2P compute broker with credit-based billing, WAL, and broker mesh support
//! Spaces v1, producer side: this broker claims batches from the hub, runs
//! each Space's container (pulled by digest), serves the in-container worker
//! over a Unix socket, and sends signed receipts.
//!
//! Opt-in: `zc spaces enable [--min-price-per-hour N]` PUTs the hub settings
//! and writes `<state_dir>/spaces/settings.json`, which the scheduler polls.

pub mod client;
pub mod receipt;
pub mod runner;
pub mod schedule;
pub mod socket;
pub mod worker;

use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicUsize};
use std::sync::{Arc, Mutex, OnceLock};

use serde::{Deserialize, Serialize};

/// Raised by the idle benchmark while it measures; the Spaces scheduler sends
/// no claims meanwhile.
pub fn bench_running() -> Arc<AtomicBool> {
    static F: OnceLock<Arc<AtomicBool>> = OnceLock::new();
    F.get_or_init(Arc::default).clone()
}

/// Number of Space containers currently running; the idle benchmark treats
/// any as busy so it never measures a saturated node.
pub fn space_containers() -> Arc<AtomicUsize> {
    static C: OnceLock<Arc<AtomicUsize>> = OnceLock::new();
    C.get_or_init(Arc::default).clone()
}

/// Local, scheduler-visible copy of the provider settings.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct Settings {
    pub enabled: bool,
    #[serde(default)]
    pub min_price_per_hour: Option<f64>,
}

fn settings_path(dir: &Path) -> PathBuf {
    dir.join("spaces").join("settings.json")
}

fn status_path(dir: &Path) -> PathBuf {
    dir.join("spaces").join("status.json")
}

pub fn read_settings(dir: &Path) -> Settings {
    std::fs::read_to_string(settings_path(dir))
        .ok()
        .and_then(|t| serde_json::from_str(&t).ok())
        .unwrap_or_default()
}

pub fn write_settings(dir: &Path, s: &Settings) -> Result<(), String> {
    let p = settings_path(dir);
    if let Some(d) = p.parent() {
        std::fs::create_dir_all(d).map_err(|e| e.to_string())?;
    }
    std::fs::write(&p, serde_json::to_string_pretty(s).unwrap()).map_err(|e| e.to_string())
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct ActiveSpace {
    pub space_id: String,
    pub queued: usize,
    pub running: usize,
}

/// What `zc spaces status` shows; written by the broker process.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct StatusFile {
    #[serde(default)]
    pub day: String,
    #[serde(default)]
    pub completed_today: u64,
    #[serde(default)]
    pub earned_today: f64,
    #[serde(default)]
    pub active: Vec<ActiveSpace>,
}

fn today() -> String {
    chrono::Utc::now().format("%Y-%m-%d").to_string()
}

pub struct Stats {
    path: PathBuf,
    inner: Mutex<StatusFile>,
}

impl Stats {
    pub fn new(dir: &Path) -> Stats {
        Stats {
            path: status_path(dir),
            inner: Mutex::new(read_status(dir)),
        }
    }

    fn save(&self, s: &StatusFile) {
        if let Some(d) = self.path.parent() {
            let _ = std::fs::create_dir_all(d);
        }
        let _ = std::fs::write(&self.path, serde_json::to_string_pretty(s).unwrap());
    }

    fn roll(s: &mut StatusFile) {
        let t = today();
        if s.day != t {
            s.day = t;
            s.completed_today = 0;
            s.earned_today = 0.0;
        }
    }

    pub fn record_paid(&self, paid: f64) {
        let mut s = self.inner.lock().unwrap();
        Self::roll(&mut s);
        s.completed_today += 1;
        s.earned_today += paid;
        self.save(&s);
    }

    pub fn set_active(&self, active: Vec<ActiveSpace>) {
        let mut s = self.inner.lock().unwrap();
        Self::roll(&mut s);
        s.active = active;
        self.save(&s);
    }
}

pub fn read_status(dir: &Path) -> StatusFile {
    let mut s: StatusFile = std::fs::read_to_string(status_path(dir))
        .ok()
        .and_then(|t| serde_json::from_str(&t).ok())
        .unwrap_or_default();
    if s.day != today() {
        s.completed_today = 0;
        s.earned_today = 0.0;
    }
    s
}

/// `zc spaces enable|disable|status`. Returns the exit code.
pub fn run_cli(args: &[String]) -> i32 {
    let Some(dir) = crate::credentials::dir() else {
        eprintln!("Error: no state directory (set HOME or ZAKURO_HOME)");
        return 1;
    };
    let hub = || -> Result<client::Hub, String> {
        let key = std::env::var("ZAKURO_API_KEY")
            .ok()
            .filter(|k| !k.trim().is_empty())
            .ok_or("not signed in (run `zc login` or set ZAKURO_API_KEY)")?;
        let node_key = crate::broker::node_identity::NodeKey::load_or_create();
        Ok(client::Hub::new(
            &crate::credentials::default_api_url(),
            &key,
            &node_key.public_b64(),
        ))
    };
    match args.first().map(String::as_str).unwrap_or("status") {
        "enable" => {
            let price = match parse_price(&args[1..]) {
                Ok(p) => p,
                Err(e) => {
                    eprintln!("Error: {e}");
                    return 2;
                }
            };
            match hub().and_then(|h| enable(&h, &dir, price)) {
                Ok(()) => {
                    println!("Spaces enabled. Restart the broker if it is not running.");
                    0
                }
                Err(e) => {
                    eprintln!("Error: {e}");
                    1
                }
            }
        }
        "disable" => match hub().and_then(|h| disable(&h, &dir)) {
            Ok(()) => {
                println!("Spaces disabled. Running batches finish; no new work is claimed.");
                0
            }
            Err(e) => {
                eprintln!("Error: {e}");
                1
            }
        },
        "status" => {
            print_status(&dir);
            0
        }
        other => {
            eprintln!(
                "usage: zc spaces [enable [--min-price-per-hour N]|disable|status] (got '{other}')"
            );
            2
        }
    }
}

pub fn parse_price(args: &[String]) -> Result<Option<f64>, String> {
    let mut it = args.iter();
    let mut price = None;
    while let Some(a) = it.next() {
        if a == "--min-price-per-hour" {
            let v = it.next().ok_or("--min-price-per-hour needs a value")?;
            let p: f64 = v.parse().map_err(|_| format!("bad price '{v}'"))?;
            if p.is_nan() || p < 0.0 {
                return Err("price must be >= 0".into());
            }
            price = Some(p);
        } else {
            return Err(format!("unknown argument '{a}'"));
        }
    }
    Ok(price)
}

/// PUT the settings, then record them locally for the scheduler.
pub fn enable(hub: &client::Hub, dir: &Path, min_price: Option<f64>) -> Result<(), String> {
    // An omitted flag keeps the stored price: the hub replaces the column
    // with whatever the PUT carries, and `None` would clear it.
    let min_price = min_price.or(read_settings(dir).min_price_per_hour);
    hub.put_settings(true, min_price)?;
    write_settings(
        dir,
        &Settings {
            enabled: true,
            min_price_per_hour: min_price,
        },
    )
}

pub fn disable(hub: &client::Hub, dir: &Path) -> Result<(), String> {
    // Send the stored price so disabling never clears the hub's minimum.
    hub.put_settings(false, read_settings(dir).min_price_per_hour)?;
    let mut s = read_settings(dir);
    s.enabled = false;
    write_settings(dir, &s)
}

fn print_status(dir: &Path) {
    let s = read_settings(dir);
    let st = read_status(dir);
    println!("Spaces: {}", if s.enabled { "enabled" } else { "disabled" });
    if let Some(p) = s.min_price_per_hour {
        println!("Min price per hour: {p}");
    }
    if st.active.is_empty() {
        println!("Active Spaces: none");
    } else {
        println!("Active Spaces:");
        for a in &st.active {
            println!(
                "  {}  queued={} running={}",
                a.space_id, a.queued, a.running
            );
        }
    }
    println!(
        "Today: {} batches completed, {:.4} zkcr earned",
        st.completed_today, st.earned_today
    );
}

#[cfg(test)]
pub(crate) mod testutil {
    //! A stub hub on 127.0.0.1 that records requests and answers by path.
    use std::sync::{Arc, Mutex};

    pub struct StubHub {
        pub url: String,
        pub requests: Arc<Mutex<Vec<(String, String, String)>>>, // method, path, body
    }

    /// `respond(method, path, body) -> (status, json body)`.
    pub fn stub_hub<F>(respond: F) -> StubHub
    where
        F: Fn(&str, &str, &str) -> (u16, String) + Send + 'static,
    {
        let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
        let url = format!("http://{}", server.server_addr().to_ip().unwrap());
        let requests = Arc::new(Mutex::new(Vec::new()));
        let reqs = requests.clone();
        std::thread::spawn(move || {
            for mut rq in server.incoming_requests() {
                let mut body = String::new();
                let _ = std::io::Read::read_to_string(rq.as_reader(), &mut body);
                let method = rq.method().to_string();
                let path = rq.url().to_string();
                reqs.lock()
                    .unwrap()
                    .push((method.clone(), path.clone(), body.clone()));
                let (code, out) = respond(&method, &path, &body);
                let resp = tiny_http::Response::from_string(out)
                    .with_status_code(code)
                    .with_header(
                        tiny_http::Header::from_bytes("Content-Type", "application/json").unwrap(),
                    );
                let _ = rq.respond(resp);
            }
        });
        StubHub { url, requests }
    }

    impl StubHub {
        /// Assert every recorded request whose path contains `needle` (and at
        /// least one exists) carries `"node_pubkey": pk` in its JSON body.
        pub fn assert_pubkey(&self, needle: &str, pk: &str) {
            let reqs = self.requests.lock().unwrap();
            let hits: Vec<_> = reqs.iter().filter(|(_, p, _)| p.contains(needle)).collect();
            assert!(!hits.is_empty(), "no request matching {needle}");
            for (_, p, b) in hits {
                let v: serde_json::Value = serde_json::from_str(b).unwrap();
                assert_eq!(v["node_pubkey"], pk, "node_pubkey missing on {p}");
            }
        }

        pub fn count(&self, needle: &str) -> usize {
            self.requests
                .lock()
                .unwrap()
                .iter()
                .filter(|(_, p, _)| p.contains(needle))
                .count()
        }
    }
}

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

    #[test]
    fn spaces_enable_puts_settings() {
        let hub = stub_hub(|_, _, _| (200, "{}".to_string()));
        let dir = std::env::temp_dir().join(format!("zk-spaces-en-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let h = client::Hub::new(&hub.url, "zk_test", "PK_TEST");
        enable(&h, &dir, Some(1.5)).unwrap();
        {
            let reqs = hub.requests.lock().unwrap();
            let (m, p, b) = &reqs[0];
            assert_eq!(m, "PUT");
            assert_eq!(p, "/api/broker/spaces/settings");
            let v: serde_json::Value = serde_json::from_str(b).unwrap();
            assert_eq!(v["enabled"], true);
            assert_eq!(v["node_pubkey"], "PK_TEST");
            assert_eq!(v["min_price_per_hour"], 1.5);
        }
        assert!(read_settings(&dir).enabled);
        disable(&h, &dir).unwrap();
        {
            let reqs = hub.requests.lock().unwrap();
            let v: serde_json::Value = serde_json::from_str(&reqs[1].2).unwrap();
            assert_eq!(v["enabled"], false);
            assert_eq!(v["min_price_per_hour"], 1.5, "disable keeps the price");
        }
        enable(&h, &dir, None).unwrap();
        {
            let reqs = hub.requests.lock().unwrap();
            let v: serde_json::Value = serde_json::from_str(&reqs[2].2).unwrap();
            assert_eq!(v["min_price_per_hour"], 1.5, "re-enable keeps the price");
        }
        disable(&h, &dir).unwrap();
        assert!(!read_settings(&dir).enabled);
        assert_eq!(read_settings(&dir).min_price_per_hour, Some(1.5));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn parse_price_flag() {
        let a = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
        assert_eq!(parse_price(&a(&[])).unwrap(), None);
        assert_eq!(
            parse_price(&a(&["--min-price-per-hour", "2"])).unwrap(),
            Some(2.0)
        );
        assert!(parse_price(&a(&["--min-price-per-hour"])).is_err());
        assert!(parse_price(&a(&["--x"])).is_err());
    }
}