zc2 0.0.53

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! The hub client the marketplace verbs and the session share: base URL,
//! the `zk_` key `zc login` saved, timeouts, JSON verbs, and errors that say
//! what to do instead of dumping an HTTP status.

use std::fmt;
use std::time::Duration;

use serde_json::Value;

use crate::credentials;

/// Why a hub call did not return JSON.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HubError {
    /// No `zk_` key on this machine.
    NoKey,
    /// The hub does not know the key (revoked, or never valid).
    BadKey,
    /// The key is valid, but the deployed hub does not accept it on this
    /// route yet (the route still wants a browser session).
    NeedsNewerHub(String),
    NotFound(String),
    /// Any other answer, with the hub's reason as one line.
    Http(u16, String),
    /// The hub did not answer.
    Transport(String),
}

impl fmt::Display for HubError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            HubError::NoKey => write!(f, "no API key; run `zc login` first"),
            HubError::BadKey => write!(f, "the hub does not accept this key; run `zc login`"),
            HubError::NeedsNewerHub(p) => write!(
                f,
                "needs a newer hub: {p} does not accept an API key on this hub yet"
            ),
            HubError::NotFound(m) => write!(f, "not found: {m}"),
            HubError::Http(s, m) => write!(f, "HTTP {s}: {m}"),
            HubError::Transport(m) => write!(f, "the hub did not answer: {m}"),
        }
    }
}

impl std::error::Error for HubError {}

/// A route that takes the key on every hub since the marketplace opened;
/// used to tell "the key is bad" from "this route is key-less".
const KEY_PROBE: &str = "/api/envs/catalog";

#[derive(Clone)]
pub struct Client {
    base: String,
    key: String,
    agent: ureq::Agent,
}

/// Percent-encode one query value or path segment.
pub fn enc(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for b in s.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(b as char)
            }
            _ => out.push_str(&format!("%{b:02X}")),
        }
    }
    out
}

/// `path?k=v&…`, skipping empty values.
pub fn with_query(path: &str, query: &[(&str, &str)]) -> String {
    let q: Vec<String> = query
        .iter()
        .filter(|(_, v)| !v.is_empty())
        .map(|(k, v)| format!("{k}={}", enc(v)))
        .collect();
    match q.is_empty() {
        true => path.to_string(),
        false => format!("{path}?{}", q.join("&")),
    }
}

/// The hub's error body as one line.
pub fn reason(text: &str) -> String {
    crate::atelier_cli::hub_error(text)
}

impl Client {
    pub fn new(base: &str, key: &str) -> Self {
        let agent = ureq::Agent::new_with_config(
            ureq::Agent::config_builder()
                .timeout_connect(Some(Duration::from_secs(10)))
                .timeout_recv_response(Some(Duration::from_secs(30)))
                .http_status_as_error(false)
                .build(),
        );
        Self {
            base: base.trim_end_matches('/').to_string(),
            key: key.trim().to_string(),
            agent,
        }
    }

    /// The client of this machine's login.
    pub fn from_env() -> Result<Self, HubError> {
        credentials::load_into_env();
        let key = std::env::var("ZAKURO_API_KEY")
            .ok()
            .filter(|k| !k.trim().is_empty())
            .ok_or(HubError::NoKey)?;
        let base = std::env::var("ZAKURO_API_URL")
            .ok()
            .filter(|u| !u.trim().is_empty())
            .unwrap_or_else(credentials::default_api_url);
        Ok(Self::new(&base, &key))
    }

    pub fn base(&self) -> &str {
        &self.base
    }

    /// The hub's web address for a browser page (`/billing`, …).
    pub fn web_url(&self, path: &str) -> String {
        web_base(&self.base) + path
    }

    pub fn get(&self, path: &str) -> Result<Value, HubError> {
        self.call("GET", path, None)
    }
    pub fn get_q(&self, path: &str, query: &[(&str, &str)]) -> Result<Value, HubError> {
        self.get(&with_query(path, query))
    }
    pub fn post(&self, path: &str, body: Option<Value>) -> Result<Value, HubError> {
        self.call("POST", path, body)
    }
    pub fn patch(&self, path: &str, body: Value) -> Result<Value, HubError> {
        self.call("PATCH", path, Some(body))
    }
    pub fn delete(&self, path: &str, body: Option<Value>) -> Result<Value, HubError> {
        self.call("DELETE", path, body)
    }

    fn call(&self, method: &str, path: &str, body: Option<Value>) -> Result<Value, HubError> {
        let (status, text) = self.raw(method, path, body)?;
        match status {
            200..=299 => {
                if text.trim().is_empty() {
                    return Ok(Value::Null);
                }
                Ok(serde_json::from_str(&text).unwrap_or(Value::String(text)))
            }
            401 | 403 if self.key_is_valid() => Err(HubError::NeedsNewerHub(
                path.split('?').next().unwrap_or(path).to_string(),
            )),
            401 => Err(HubError::BadKey),
            404 => Err(HubError::NotFound(reason(&text))),
            s => Err(HubError::Http(s, reason(&text))),
        }
    }

    fn raw(
        &self,
        method: &str,
        path: &str,
        body: Option<Value>,
    ) -> Result<(u16, String), HubError> {
        let url = format!("{}{path}", self.base);
        let auth = format!("Bearer {}", self.key);
        let sent = match (method, body) {
            ("GET", _) => self.agent.get(&url).header("Authorization", &auth).call(),
            ("DELETE", None) => self
                .agent
                .delete(&url)
                .header("Authorization", &auth)
                .call(),
            ("DELETE", Some(b)) => self
                .agent
                .delete(&url)
                .header("Authorization", &auth)
                .force_send_body()
                .send_json(b),
            ("PATCH", b) => self
                .agent
                .patch(&url)
                .header("Authorization", &auth)
                .send_json(b.unwrap_or(Value::Null)),
            (_, Some(b)) => self
                .agent
                .post(&url)
                .header("Authorization", &auth)
                .send_json(b),
            (_, None) => self
                .agent
                .post(&url)
                .header("Authorization", &auth)
                .send_empty(),
        }
        .map_err(|e| HubError::Transport(transport_reason(&e)))?;
        let status = sent.status().as_u16();
        let text = sent
            .into_body()
            .read_to_string()
            .map_err(|e| HubError::Transport(e.to_string()))?;
        Ok((status, text))
    }

    /// Whether the hub accepts this key on a route that always took it.
    fn key_is_valid(&self) -> bool {
        matches!(self.raw("GET", KEY_PROBE, None), Ok((200..=299, _)))
    }
}

fn transport_reason(e: &ureq::Error) -> String {
    e.to_string()
}

/// The hub's web console for an API address, which names it with an `api.`
/// label: `https://stg.api.zakuro-ai.com` -> `https://stg.hub.zakuro-ai.com`.
/// `ZAKURO_WEB_URL` overrides it.
pub fn web_base(api: &str) -> String {
    if let Some(u) = std::env::var("ZAKURO_WEB_URL")
        .ok()
        .filter(|u| !u.trim().is_empty())
    {
        return u.trim_end_matches('/').to_string();
    }
    let api = api.trim_end_matches('/');
    match api.split_once("://") {
        Some((scheme, host)) => format!("{scheme}://{}", host.replacen("api.", "hub.", 1)),
        None => api.to_string(),
    }
}

#[cfg(test)]
pub mod tests {
    use super::*;
    use std::sync::{Arc, Mutex};

    pub type Seen = Arc<Mutex<Vec<(String, String, Option<String>)>>>;

    /// A stub hub: `(method, path-with-query) -> (status, body)`; anything
    /// else is 404. Records (method, url, Authorization).
    pub fn stub(routes: Vec<(&'static str, String, u16, String)>) -> (String, Seen) {
        let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
        let base = format!("http://{}", server.server_addr().to_ip().unwrap());
        let seen: Seen = Arc::default();
        let log = seen.clone();
        std::thread::spawn(move || {
            for mut req in server.incoming_requests() {
                let url = req.url().to_string();
                let method = req.method().to_string();
                let auth = req
                    .headers()
                    .iter()
                    .find(|h| h.field.equiv("Authorization"))
                    .map(|h| h.value.to_string());
                let mut sent = String::new();
                let _ = std::io::Read::read_to_string(req.as_reader(), &mut sent);
                let sent = serde_json::from_str::<Value>(&sent)
                    .map(|v| v.to_string())
                    .unwrap_or(sent);
                log.lock().unwrap().push((
                    method.clone(),
                    format!("{url} {sent}").trim().to_string(),
                    auth,
                ));
                let (status, body) = routes
                    .iter()
                    .find(|(m, p, _, _)| *m == method && url == *p)
                    .map(|(_, _, s, b)| (*s, b.clone()))
                    .unwrap_or((404, r#"{"detail":"no such route"}"#.into()));
                let _ =
                    req.respond(tiny_http::Response::from_string(body).with_status_code(status));
            }
        });
        (base, seen)
    }

    #[test]
    fn query_values_are_encoded_and_empty_ones_dropped() {
        assert_eq!(
            with_query("/api/models", &[("q", "a b&c"), ("x", "")]),
            "/api/models?q=a%20b%26c"
        );
        assert_eq!(with_query("/api/models", &[]), "/api/models");
    }

    #[test]
    fn the_web_address_swaps_the_api_label_for_hub() {
        assert_eq!(
            web_base("https://stg.api.zakuro-ai.com/"),
            "https://stg.hub.zakuro-ai.com"
        );
        assert_eq!(
            web_base("https://api.zakuro-ai.com"),
            "https://hub.zakuro-ai.com"
        );
    }

    #[test]
    fn a_call_sends_the_key_and_reads_json() {
        let (base, seen) = stub(vec![(
            "GET",
            "/api/models".into(),
            200,
            r#"[{"id":"m"}]"#.into(),
        )]);
        let v = Client::new(&base, " zk_abc ").get("/api/models").unwrap();
        assert_eq!(v[0]["id"], "m");
        assert_eq!(seen.lock().unwrap()[0].2.as_deref(), Some("Bearer zk_abc"));
    }

    #[test]
    fn a_refused_key_on_a_key_less_route_asks_for_a_newer_hub() {
        let (base, _) = stub(vec![
            (
                "GET",
                "/api/usage/stats".into(),
                401,
                r#"{"detail":"Not authenticated"}"#.into(),
            ),
            ("GET", KEY_PROBE.into(), 200, "[]".into()),
        ]);
        let e = Client::new(&base, "zk_x")
            .get("/api/usage/stats")
            .unwrap_err();
        assert_eq!(e, HubError::NeedsNewerHub("/api/usage/stats".into()));
        assert!(e.to_string().contains("needs a newer hub"));
    }

    #[test]
    fn a_key_the_hub_never_accepts_asks_for_a_login() {
        let (base, _) = stub(vec![
            ("GET", "/api/usage/stats".into(), 401, "{}".into()),
            ("GET", KEY_PROBE.into(), 401, "{}".into()),
        ]);
        let e = Client::new(&base, "zk_x")
            .get("/api/usage/stats")
            .unwrap_err();
        assert_eq!(e, HubError::BadKey);
        assert!(e.to_string().contains("zc login"));
    }

    #[test]
    fn other_statuses_carry_the_hubs_reason() {
        let (base, _) = stub(vec![(
            "GET",
            "/api/x".into(),
            409,
            r#"{"detail":"already paused"}"#.into(),
        )]);
        let c = Client::new(&base, "zk_x");
        assert_eq!(
            c.get("/api/x").unwrap_err(),
            HubError::Http(409, "already paused".into())
        );
        assert!(matches!(
            c.get("/api/none").unwrap_err(),
            HubError::NotFound(_)
        ));
    }

    #[test]
    fn writes_carry_their_body_and_an_empty_answer_is_null() {
        let (base, seen) = stub(vec![
            ("POST", "/api/squads".into(), 201, r#"{"id":"s1"}"#.into()),
            ("DELETE", "/api/envs/e1".into(), 204, String::new()),
            ("PATCH", "/api/spaces/p".into(), 200, "{}".into()),
        ]);
        let c = Client::new(&base, "zk_x");
        assert_eq!(
            c.post("/api/squads", Some(serde_json::json!({"name":"a"})))
                .unwrap()["id"],
            "s1"
        );
        assert_eq!(c.delete("/api/envs/e1", None).unwrap(), Value::Null);
        c.patch("/api/spaces/p", serde_json::json!({"x":1}))
            .unwrap();
        assert!(seen.lock().unwrap()[0].1.contains(r#"{"name":"a"}"#));
    }
}