zc2 0.0.49

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! Hub round-trips for Spaces: claim, heartbeat, output presign, complete,
//! and the provider settings PUT. Same ureq style and `X-Broker-Api-Key`
//! header as `broker::node_sync`.

use std::time::Duration;

use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use super::receipt::SignedReceipt;

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct ImageRef {
    pub mirror_ref: String,
    pub digest: String,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct PullCreds {
    pub registry: String,
    pub username: String,
    pub token: String,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct Input {
    pub name: String,
    pub url: String,
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Default)]
pub struct Requirements {
    #[serde(default)]
    pub cpus: f64,
    #[serde(default)]
    pub memory_gb: f64,
    #[serde(default)]
    pub gpus: u32,
    #[serde(default)]
    pub min_vram_gb: f64,
    #[serde(default)]
    pub max_runtime_s: u64,
    #[serde(default)]
    pub est_runtime_s: u64,
}

/// One element of the claim response's `leases` (plan "Contracts").
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct Lease {
    pub lease_id: String,
    pub batch_id: i64,
    pub space_id: String,
    #[serde(default)]
    pub seq: i64,
    pub image: ImageRef,
    pub pull: PullCreds,
    #[serde(default)]
    pub inputs: Vec<Input>,
    #[serde(default)]
    pub requirements: Requirements,
    pub deadline: String,
    #[serde(default = "default_hb")]
    pub heartbeat_every_s: u64,
    /// What the batch pays per hour, when the hub says. Absent today: a lease
    /// of unknown value is never stopped to make room for an offer.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub price_per_hour: Option<f64>,
}

fn default_hb() -> u64 {
    60
}

/// What the hub said to a `complete`.
#[derive(Debug, Clone, PartialEq)]
pub enum Completion {
    /// 200: `{"status":"succeeded","paid":0.9}`.
    Accepted { paid: f64 },
    /// 409 (stale/expired/mismatch) or 401 (bad signature).
    Rejected { status: u16 },
}

#[derive(Debug, Clone)]
pub struct Hub {
    pub api_url: String,
    pub api_key: String,
    /// This node's public key (`NodeKey::public_b64`), sent in every call so
    /// the hub can bind it to a node.
    pub node_pubkey: String,
}

fn agent_post(url: &str, key: &str, body: &Value, secs: u64) -> Result<(u16, String), String> {
    let resp = ureq::post(url)
        .config()
        .timeout_global(Some(Duration::from_secs(secs)))
        .http_status_as_error(false)
        .build()
        .header("X-Broker-Api-Key", key)
        .header("Content-Type", "application/json")
        .send(body.to_string().as_str())
        .map_err(|e| e.to_string())?;
    let code = resp.status().as_u16();
    let text = resp.into_body().read_to_string().unwrap_or_default();
    Ok((code, text))
}

impl Hub {
    pub fn new(api_url: &str, api_key: &str, node_pubkey: &str) -> Hub {
        Hub {
            node_pubkey: node_pubkey.to_string(),
            api_url: api_url.trim_end_matches('/').to_string(),
            api_key: api_key.to_string(),
        }
    }

    fn url(&self, path: &str) -> String {
        format!("{}/api/broker/spaces/{path}", self.api_url)
    }

    /// `PUT /api/broker/spaces/settings`.
    pub fn put_settings(
        &self,
        enabled: bool,
        min_price_per_hour: Option<f64>,
    ) -> Result<(), String> {
        let mut body = json!({ "enabled": enabled, "node_pubkey": self.node_pubkey });
        if let Some(p) = min_price_per_hour {
            body["min_price_per_hour"] = json!(p);
        }
        let resp = ureq::put(self.url("settings"))
            .config()
            .timeout_global(Some(Duration::from_secs(10)))
            .http_status_as_error(false)
            .build()
            .header("X-Broker-Api-Key", &self.api_key)
            .header("Content-Type", "application/json")
            .send(body.to_string().as_str())
            .map_err(|e| e.to_string())?;
        let code = resp.status().as_u16();
        if (200..300).contains(&code) {
            Ok(())
        } else {
            Err(format!("settings HTTP {code}"))
        }
    }

    /// `POST /api/broker/spaces/claim`.
    pub fn claim(
        &self,
        node_pubkey: &str,
        capabilities: &Value,
        units: Option<Value>,
        max_leases: u32,
    ) -> Result<Vec<Lease>, String> {
        let mut body = json!({
            "node_pubkey": node_pubkey,
            "capabilities": capabilities,
            "max_leases": max_leases,
        });
        if let Some(u) = units {
            body["units"] = u;
        }
        let (code, text) = agent_post(&self.url("claim"), &self.api_key, &body, 20)?;
        if code != 200 {
            return Err(format!("claim HTTP {code}"));
        }
        parse_claim(&text)
    }

    /// `POST .../leases/{id}/heartbeat` → the new `lease_until`.
    pub fn heartbeat(&self, lease_id: &str) -> Result<Option<String>, String> {
        let (code, text) = agent_post(
            &self.url(&format!("leases/{lease_id}/heartbeat")),
            &self.api_key,
            &json!({ "node_pubkey": self.node_pubkey }),
            10,
        )?;
        if code != 200 {
            return Err(format!("heartbeat HTTP {code}"));
        }
        let v: Value = serde_json::from_str(&text).unwrap_or(Value::Null);
        Ok(v.get("lease_until")
            .and_then(|s| s.as_str())
            .map(String::from))
    }

    /// `POST .../leases/{id}/outputs:presign`. Returns the hub's status and
    /// JSON body so the socket can relay both unchanged.
    pub fn presign(&self, lease_id: &str, names: &[String]) -> Result<(u16, String), String> {
        agent_post(
            &self.url(&format!("leases/{lease_id}/outputs:presign")),
            &self.api_key,
            &json!({ "names": names, "node_pubkey": self.node_pubkey }),
            20,
        )
    }

    /// `POST .../leases/{id}/complete` with the signed receipt.
    pub fn complete(&self, lease_id: &str, r: &SignedReceipt) -> Result<Completion, String> {
        let body = json!({ "receipt_json": r.receipt_json, "signature": r.signature });
        let (code, text) = agent_post(
            &self.url(&format!("leases/{lease_id}/complete")),
            &self.api_key,
            &body,
            30,
        )?;
        match code {
            200 => {
                let v: Value = serde_json::from_str(&text).unwrap_or(Value::Null);
                Ok(Completion::Accepted {
                    paid: v.get("paid").and_then(|p| p.as_f64()).unwrap_or(0.0),
                })
            }
            // 5xx, 429 and 408 are transient (rolling deploy, overload): the
            // caller retries. Everything else (400/401/409/...) is final.
            c if c >= 500 || c == 429 || c == 408 => Err(format!("complete HTTP {c}")),
            c => Ok(Completion::Rejected { status: c }),
        }
    }
}

/// Parse the claim response. One malformed lease is logged and skipped; it
/// never rejects the leases around it.
pub fn parse_claim(text: &str) -> Result<Vec<Lease>, String> {
    let v: Value = serde_json::from_str(text).map_err(|e| format!("bad claim response: {e}"))?;
    let items = match v.get("leases") {
        None | Some(Value::Null) => return Ok(Vec::new()),
        Some(Value::Array(a)) => a,
        Some(_) => return Err("bad claim response: leases is not an array".to_string()),
    };
    let mut out = Vec::new();
    for item in items {
        match serde_json::from_value::<Lease>(item.clone()) {
            Ok(l) => out.push(l),
            Err(e) => eprintln!("  [SPACES] skipping malformed lease in claim response: {e}"),
        }
    }
    Ok(out)
}

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

    pub const LEASE_FIXTURE: &str = r#"{"leases":[{"lease_id":"11111111-1111-4111-8111-111111111111","batch_id":123,"space_id":"22222222-2222-4222-8222-222222222222","seq":7,
 "image":{"mirror_ref":"registry:5000/spaces/22222222-2222-4222-8222-222222222222@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","digest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
 "pull":{"registry":"registry:5000","username":"zk-lease","token":"tok"},
 "inputs":[{"name":"a.fastq","url":"https://example.com/a?sig=1"}],
 "requirements":{"cpus":4,"memory_gb":8,"gpus":0,"min_vram_gb":0,"max_runtime_s":600,"est_runtime_s":120},
 "deadline":"2026-10-04T12:00:00Z","heartbeat_every_s":60}]}"#;

    #[test]
    fn claim_parses_lease_contract() {
        let leases = parse_claim(LEASE_FIXTURE).unwrap();
        assert_eq!(leases.len(), 1);
        let l = &leases[0];
        assert_eq!(l.batch_id, 123);
        assert_eq!(l.seq, 7);
        assert_eq!(l.pull.username, "zk-lease");
        assert_eq!(l.inputs[0].name, "a.fastq");
        assert_eq!(l.requirements.cpus, 4.0);
        assert_eq!(l.requirements.max_runtime_s, 600);
        assert_eq!(l.heartbeat_every_s, 60);
        assert!(l.image.mirror_ref.ends_with(&l.image.digest));
        assert!(parse_claim(r#"{"leases":[]}"#).unwrap().is_empty());
    }

    #[test]
    fn one_malformed_lease_is_skipped_not_fatal() {
        let good: Value =
            serde_json::from_str::<Value>(LEASE_FIXTURE).unwrap()["leases"][0].clone();
        let body = json!({"leases": [{"lease_id": "x"}, good, 7]}).to_string();
        let leases = parse_claim(&body).unwrap();
        assert_eq!(leases.len(), 1);
        assert_eq!(leases[0].batch_id, 123);
        assert!(parse_claim("not json").is_err());
    }
}