zc2 0.0.53

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! The marketplace feeds the session's Models, Jobs, Envs and Spaces tabs
//! and the Account tab's usage panel draw: each is one hub route, fetched on
//! a background thread and turned into a [`Doc`] there, so the UI thread
//! only ever draws what has arrived.

use super::app::{Effect, Event};
use crate::market::client::{Client, HubError};
use crate::market::fmt::Doc;
use crate::market::{account, browse, Parsed};
use std::sync::mpsc::{RecvTimeoutError, Sender};
use std::time::Duration;

pub const MARKET_EVERY: Duration = Duration::from_secs(30);

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum FeedId {
    Models,
    Jobs,
    Envs,
    Spaces,
    Usage,
    Quotas,
    Recent,
}

impl FeedId {
    pub const ALL: [FeedId; 7] = [
        FeedId::Models,
        FeedId::Jobs,
        FeedId::Envs,
        FeedId::Spaces,
        FeedId::Usage,
        FeedId::Quotas,
        FeedId::Recent,
    ];
}

/// What the tab has: nothing yet, the table, or why not.
#[derive(Debug, Clone, PartialEq, Default)]
pub enum FeedState {
    #[default]
    Loading,
    Ready(Doc),
    Failed(String),
}

/// One in-session write to the hub.
#[derive(Debug, Clone, PartialEq)]
pub enum HubWrite {
    StopEnv(String),
    /// `cancel`, `pause` or `resume` of a Space.
    Space(&'static str, String),
}

pub fn fetch(c: &Client, id: FeedId) -> Result<Doc, HubError> {
    Ok(match id {
        FeedId::Models => browse::models_table(&c.get("/api/models")?, "", usize::MAX),
        FeedId::Jobs => browse::jobs_table(&c.get("/api/forge/jobs")?),
        FeedId::Envs => browse::envs_table(&c.get("/api/envs")?),
        FeedId::Spaces => browse::spaces_table(&c.get("/api/spaces")?),
        FeedId::Usage => account::usage_doc(&c.get("/api/usage/stats")?),
        FeedId::Quotas => account::quotas_doc(&c.get("/api/dashboard/quotas")?),
        FeedId::Recent => account::recent_table(&c.get("/api/dashboard/recent-transactions")?),
    })
}

/// Every feed, one after the other, each sent as it lands.
pub fn fetch_all(c: &Result<Client, HubError>, tx: &Sender<Event>) -> bool {
    for id in FeedId::ALL {
        let r = match c {
            Ok(c) => fetch(c, id).map_err(|e| e.to_string()),
            Err(e) => Err(e.to_string()),
        };
        if tx.send(Event::Feed(id, r)).is_err() {
            return false;
        }
    }
    true
}

/// The poller: all feeds now, then every [`MARKET_EVERY`] or when nudged.
pub fn spawn_poller(tx: Sender<Event>, make: fn() -> Result<Client, HubError>) -> Sender<()> {
    let (nudge, rx) = std::sync::mpsc::channel::<()>();
    std::thread::spawn(move || loop {
        if !fetch_all(&make(), &tx) {
            return;
        }
        if let Err(RecvTimeoutError::Disconnected) = rx.recv_timeout(MARKET_EVERY) {
            return;
        }
    });
    nudge
}

/// Carry out a write; the answer is the line to show.
pub fn write(c: &Result<Client, HubError>, w: &HubWrite) -> Result<String, String> {
    let c = c.as_ref().map_err(|e| e.to_string())?;
    let (verb, sub, id) = match w {
        HubWrite::StopEnv(id) => ("env", "stop", id),
        HubWrite::Space(v, id) => ("space", *v, id),
    };
    let p = Parsed::parse(std::slice::from_ref(id)).map_err(|e| e.to_string())?;
    match crate::market::call_with(c, verb, sub, &p) {
        Ok((_, doc)) => Ok(doc.note.unwrap_or_else(|| format!("{verb} {sub}: done"))),
        Err(crate::market::Fail::Hub(e)) => Err(e.to_string()),
        Err(crate::market::Fail::Usage(e)) => Err(e),
    }
}

pub fn execute(effect: &Effect, tx: &Sender<Event>, nudge: &Sender<()>) {
    match effect {
        Effect::RefreshMarket => {
            let _ = nudge.send(());
        }
        Effect::Hub(w) => {
            let (tx, w) = (tx.clone(), w.clone());
            std::thread::spawn(move || {
                let _ = tx.send(Event::HubDone(write(&Client::from_env(), &w)));
            });
        }
        _ => {}
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::market::client::tests::stub;
    use serde_json::json;

    fn routes() -> Vec<(&'static str, String, u16, String)> {
        vec![
            ("GET", "/api/models".into(), 200, json!([{"id": "m1", "name": "vit", "owner_handle": "o"}]).to_string()),
            ("GET", "/api/forge/jobs".into(), 200, json!([{"id": "j1", "status": "queued", "model_ref": "r"}]).to_string()),
            ("GET", "/api/envs".into(), 200, "[]".into()),
            ("GET", "/api/spaces".into(), 200, json!({"items": [{"id": "s1", "name": "n", "status": "done", "counts": {"succeeded": 1}}]}).to_string()),
            ("GET", "/api/usage/stats".into(), 401, r#"{"detail":"Not authenticated"}"#.into()),
            ("GET", "/api/dashboard/quotas".into(), 200, json!({"rate_limit_per_period": 5, "requests_this_period": 1}).to_string()),
            ("GET", "/api/dashboard/recent-transactions".into(), 200, json!([{"id": 1, "job_name": "j", "created_at": "2026-11-18T10:00:00Z", "credits_amount": -1.0}]).to_string()),
            ("GET", "/api/envs/catalog".into(), 200, "[]".into()),
            ("DELETE", "/api/envs/e1".into(), 200, r#"{"status":"stopped"}"#.into()),
            ("POST", "/api/spaces/s1/pause".into(), 200, r#"{"status":"paused"}"#.into()),
            ("POST", "/api/spaces/s2/cancel".into(), 409, r#"{"detail":"already finished"}"#.into()),
        ]
    }

    #[test]
    fn each_feed_becomes_a_table_off_the_ui_thread() {
        let (base, _) = stub(routes());
        let c = Client::new(&base, "zk_k");
        let rows = |id| fetch(&c, id).unwrap().table.unwrap().rows;
        assert_eq!(rows(FeedId::Models)[0][1], "o/vit");
        assert_eq!(rows(FeedId::Jobs)[0][1], "queued");
        assert!(rows(FeedId::Envs).is_empty());
        assert_eq!(rows(FeedId::Spaces)[0][3], "1/1");
        assert_eq!(rows(FeedId::Recent)[0][3], "j");
        assert_eq!(fetch(&c, FeedId::Quotas).unwrap().kv[0].1, "1 of 5");
    }

    #[test]
    fn every_feed_is_sent_and_a_refusal_travels_as_its_message() {
        let (base, _) = stub(routes());
        let (tx, rx) = std::sync::mpsc::channel();
        assert!(fetch_all(&Ok(Client::new(&base, "zk_k")), &tx));
        let got: Vec<(FeedId, Result<Doc, String>)> = (0..FeedId::ALL.len())
            .map(|_| match rx.recv().unwrap() {
                Event::Feed(id, r) => (id, r),
                other => panic!("{other:?}"),
            })
            .collect();
        assert_eq!(
            got.iter().map(|(i, _)| *i).collect::<Vec<_>>(),
            FeedId::ALL.to_vec()
        );
        let usage = got.iter().find(|(i, _)| *i == FeedId::Usage).unwrap();
        // The key works on the probe route, so a refusal here is the hub's age.
        assert!(
            usage.1.as_ref().unwrap_err().contains("needs a newer hub"),
            "{:?}",
            usage.1
        );
        assert!(got.iter().filter(|(_, r)| r.is_ok()).count() >= 6);
    }

    #[test]
    fn no_key_is_a_message_on_every_feed_not_a_crash() {
        let (tx, rx) = std::sync::mpsc::channel();
        assert!(fetch_all(&Err(HubError::NoKey), &tx));
        for _ in 0..FeedId::ALL.len() {
            match rx.recv().unwrap() {
                Event::Feed(_, Err(e)) => assert!(e.contains("zc login")),
                other => panic!("{other:?}"),
            }
        }
    }

    #[test]
    fn a_closed_session_stops_the_fetching() {
        let (tx, rx) = std::sync::mpsc::channel();
        drop(rx);
        assert!(!fetch_all(&Err(HubError::NoKey), &tx));
    }

    #[test]
    fn writes_go_through_the_verbs_and_say_what_the_hub_said() {
        let (base, _) = stub(routes());
        let c = Ok(Client::new(&base, "zk_k"));
        assert!(write(&c, &HubWrite::StopEnv("e1".into()))
            .unwrap()
            .contains("stopped"));
        assert!(write(&c, &HubWrite::Space("pause", "s1".into()))
            .unwrap()
            .contains("paused"));
        let e = write(&c, &HubWrite::Space("cancel", "s2".into())).unwrap_err();
        assert!(e.contains("already finished"), "{e}");
        assert!(write(&Err(HubError::NoKey), &HubWrite::StopEnv("e".into()))
            .unwrap_err()
            .contains("zc login"));
    }

    #[test]
    fn a_refresh_effect_nudges_the_poller() {
        let (tx, _rx) = std::sync::mpsc::channel();
        let (nudge, nrx) = std::sync::mpsc::channel();
        execute(&Effect::RefreshMarket, &tx, &nudge);
        assert!(nrx.try_recv().is_ok());
        execute(&Effect::RefreshMesh, &tx, &nudge);
        assert!(nrx.try_recv().is_err(), "other effects are not ours");
    }
}