zc2 0.0.53

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! The marketplace from the terminal (the hub's models, datasets,
//! environments, Spaces, squads, account and ledger), each as a verb with a
//! human table by default and the hub's own JSON with `--json`.
//!
//! The verbs call the hub with the `zk_` key `zc login` saved. A route the
//! deployed hub still keeps for browser sessions answers "needs a newer hub"
//! instead of failing. The session's tabs read the same routes through the
//! same [`client::Client`] and render the same [`fmt::Doc`]s.

pub mod account;
pub mod browse;
pub mod client;
pub mod fmt;
pub mod squads;

use std::collections::{HashMap, HashSet};

use serde_json::Value;

use client::{Client, HubError};
use fmt::Doc;

/// What a verb returns: the hub's JSON, and how to show it.
pub type Out = (Value, Doc);

#[derive(Debug)]
pub enum Fail {
    Usage(String),
    Hub(HubError),
}

impl From<HubError> for Fail {
    fn from(e: HubError) -> Self {
        Fail::Hub(e)
    }
}

/// Positional words, `--name value` options and bare `--flag`s.
#[derive(Debug, Default, PartialEq)]
pub struct Parsed {
    pub pos: Vec<String>,
    opts: HashMap<String, String>,
    flags: HashSet<String>,
}

/// Options that take a value; any other `--word` is a flag.
const VALUED: &[&str] = &[
    "name", "purpose", "budget", "policy", "role", "email", "uses", "hours", "limit", "days",
    "page", "type", "status", "template", "path", "rows", "cursor",
];

impl Parsed {
    pub fn parse(args: &[String]) -> Result<Parsed, String> {
        let mut p = Parsed::default();
        let mut it = args.iter();
        while let Some(a) = it.next() {
            match a.strip_prefix("--") {
                Some(name) if VALUED.contains(&name) => {
                    let v = it.next().ok_or_else(|| format!("--{name} needs a value"))?;
                    p.opts.insert(name.to_string(), v.clone());
                }
                Some(name) if !name.is_empty() => {
                    p.flags.insert(name.to_string());
                }
                _ => p.pos.push(a.clone()),
            }
        }
        Ok(p)
    }

    pub fn opt(&self, name: &str) -> Option<&str> {
        self.opts.get(name).map(String::as_str)
    }

    pub fn flag(&self, name: &str) -> bool {
        self.flags.contains(name)
    }

    /// `--limit N` (or `--all`) as a row count.
    pub fn limit(&self, default: usize) -> Result<usize, Fail> {
        if self.flag("all") {
            return Ok(usize::MAX);
        }
        match self.opt("limit") {
            None => Ok(default),
            Some(n) => n
                .parse()
                .map_err(|_| Fail::Usage(format!("--limit takes a whole number, got {n:?}"))),
        }
    }
}

/// Subcommands the existing `zc dataset` / `zc space` / `zc me` leave to this
/// module; every other word still reaches them unchanged.
const DATASET: &[&str] = &["ls", "list", "show", "preview"];
const SPACE: &[&str] = &["ls", "list", "show", "batches", "cancel", "pause", "resume"];
const ME: &[&str] = &["status", "profile"];

/// Run the marketplace verb in `args` (`zc` first), or `None` when it is not
/// one of ours.
pub fn dispatch(args: &[String], json: bool) -> Option<i32> {
    let verb = args.get(1)?.as_str();
    let rest = &args[2..];
    let first = rest.first().map(String::as_str).unwrap_or("");
    let ours = match verb {
        "model" | "models" | "env" | "envs" | "squad" | "squads" | "usage" | "tx"
        | "transactions" | "receipt" | "payouts" | "quotas" | "billing" | "templates"
        | "template" | "endpoint" | "endpoints" => true,
        "dataset" | "datasets" => DATASET.contains(&first),
        "space" => SPACE.contains(&first),
        "me" | "whoami" | "balance" => ME.contains(&first),
        _ => false,
    };
    if !ours {
        return None;
    }
    Some(run(verb, rest, json))
}

fn run(verb: &str, rest: &[String], json: bool) -> i32 {
    let parsed = match Parsed::parse(rest) {
        Ok(p) => p,
        Err(e) => {
            eprintln!("zc {verb}: {e}");
            return 2;
        }
    };
    match call(verb, parsed) {
        Ok((value, doc)) => {
            // A closed pipe (`| head`) is not a failure worth a panic.
            let text = match json {
                true => serde_json::to_string_pretty(&value).unwrap_or_default() + "\n",
                false => doc.render(),
            };
            let _ = std::io::Write::write_all(&mut std::io::stdout(), text.as_bytes());
            0
        }
        Err(Fail::Usage(m)) => {
            eprintln!("zc {verb}: {m}");
            2
        }
        Err(Fail::Hub(e)) => {
            eprintln!("zc {verb}: {e}");
            1
        }
    }
}

/// The verb's first positional word is its subcommand; the rest are its
/// arguments.
pub fn call(verb: &str, mut p: Parsed) -> Result<Out, Fail> {
    let sub = match p.pos.is_empty() {
        true => String::new(),
        false => p.pos.remove(0),
    };
    // `zc billing` only names a page: it needs no key and no request.
    if verb == "billing" {
        let api = std::env::var("ZAKURO_API_URL")
            .ok()
            .filter(|u| !u.trim().is_empty())
            .unwrap_or_else(crate::credentials::default_api_url);
        return account::billing(&sub, &client::web_base(&api));
    }
    let c = Client::from_env()?;
    call_with(&c, verb, &sub, &p)
}

pub fn call_with(c: &Client, verb: &str, sub: &str, p: &Parsed) -> Result<Out, Fail> {
    let list = |s: &str| {
        if s.is_empty() {
            "ls".to_string()
        } else {
            s.to_string()
        }
    };
    match verb {
        "model" | "models" => browse::model(c, &list(sub), p),
        "dataset" | "datasets" => browse::dataset(c, &list(sub), p),
        "env" | "envs" => browse::env(c, &list(sub), p),
        "space" => browse::space(c, &list(sub), p),
        "me" | "whoami" | "balance" => account::me(c, sub),
        "usage" => account::usage(c, sub, p),
        "tx" | "transactions" => account::transactions(c, sub, p),
        "receipt" => {
            // `zc receipt HASH` and `zc receipt show HASH`.
            let mut q = Parsed {
                pos: p.pos.clone(),
                ..Default::default()
            };
            if sub != "show" && !sub.is_empty() {
                q.pos.insert(0, sub.to_string());
            }
            account::receipt(c, &q)
        }
        "payouts" => account::payouts(c),
        "quotas" => account::quotas(c),
        "squad" | "squads" => squads::squad(c, &list(sub), p),
        "templates" | "template" => squads::templates(c),
        "endpoint" | "endpoints" => squads::endpoint(c, sub, p),
        _ => Err(Fail::Usage(format!("unknown verb {verb}"))),
    }
}

#[cfg(test)]
mod tests;