garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /src/client.rs

raw

//! Asking the hub. Everything that is not the hub — the CLI in an agent's
//! container, the ssh hooks, the MCP server, the node — reaches the workspace's
//! state through here, over plain HTTP on the WireGuard address.
//!
//! Changing anything (taking or giving back a node, draining, adding a node)
//! needs the caller's key, `MIDAS_HUB_KEY` or `~/.config/midas/hub.env`; the
//! hub looks it up in `/srv/midas/callers.json`. Reading does not.

use anyhow::{bail, Context, Result};
use serde_json::Value;

use crate::events::Filter;
use crate::hub;

fn env_file() -> Vec<(String, String)> {
    let home = std::env::var("HOME").unwrap_or_default();
    std::fs::read_to_string(format!("{home}/.config/midas/hub.env"))
        .unwrap_or_default()
        .lines()
        .filter_map(|l| l.trim().split_once('='))
        .map(|(k, v)| (k.trim().to_string(), v.trim().trim_matches('"').to_string()))
        .collect()
}

/// A setting, from the environment or `~/.config/midas/hub.env`.
pub fn setting(k: &str) -> Option<String> {
    std::env::var(k).ok().filter(|v| !v.is_empty())
        .or_else(|| env_file().into_iter().find(|(fk, _)| fk == k).map(|(_, v)| v))
}

/// The hub's address.
pub fn hub_url() -> String {
    setting("MIDAS_HUB")
        .or_else(|| crate::conf::read(std::path::Path::new(crate::conf::HUB_CONF)).ok().flatten().map(|c| c.url()))
        .unwrap_or_else(|| "http://127.0.0.1:4791".into())
}

/// This caller's key, if it has one.
pub fn key() -> Option<String> {
    setting("MIDAS_HUB_KEY")
}

fn parse(code: u16, text: &str) -> Result<Value> {
    let v: Value = serde_json::from_str(text).unwrap_or(Value::String(text.to_string()));
    match code {
        200..=299 => Ok(v),
        401 => bail!("the hub refused this caller's key (MIDAS_HUB_KEY or ~/.config/midas/hub.env)"),
        0 => bail!("no answer from the hub at {}", hub_url()),
        _ => bail!("{}", v["error"].as_str().map(str::to_string).unwrap_or_else(|| format!("hub answered HTTP {code}: {text}"))),
    }
}

pub fn get(path: &str) -> Result<Value> {
    let (code, text) = hub::request(&hub_url(), "GET", path, None).context("asking the hub")?;
    parse(code, &text)
}

/// A read that needs a caller key (the bots' secrets' names).
pub fn get_auth(path: &str) -> Result<Value> {
    let key = key().context("this needs a hub key (MIDAS_HUB_KEY or ~/.config/midas/hub.env)")?;
    let (code, text) = hub::request_auth(&hub_url(), "GET", path, None, Some(&key)).context("asking the hub")?;
    parse(code, &text)
}

/// A change: sent with the caller's key.
pub fn post(path: &str, body: &Value) -> Result<Value> {
    let key = key().context("changing the workspace needs a hub key (MIDAS_HUB_KEY or ~/.config/midas/hub.env)")?;
    let (code, text) = hub::request_auth(&hub_url(), "POST", path, Some(&body.to_string()), Some(&key))
        .context("asking the hub")?;
    parse(code, &text)
}

/// `post`, for a change whose answer takes up to `wait` (a device call, device.rs).
pub fn post_long(path: &str, body: &Value, wait: std::time::Duration) -> Result<Value> {
    let key = key().context("this needs a hub key (MIDAS_HUB_KEY or ~/.config/midas/hub.env)")?;
    let (code, text) = hub::request_auth_for(&hub_url(), "POST", path, Some(&body.to_string()), Some(&key), wait)
        .context("asking the hub")?;
    parse(code, &text)
}

/// Like `post`, but a refusal is an answer, not an error: `(status, body)`.
pub fn post_raw(path: &str, body: &Value) -> Result<(u16, Value)> {
    let key = key().context("changing the workspace needs a hub key (MIDAS_HUB_KEY or ~/.config/midas/hub.env)")?;
    let (code, text) = hub::request_auth(&hub_url(), "POST", path, Some(&body.to_string()), Some(&key))
        .context("asking the hub")?;
    if code == 401 || code == 0 {
        parse(code, &text)?;
    }
    Ok((code, serde_json::from_str(&text).unwrap_or(Value::Null)))
}

/// A file for a hub-run session's page (sessions.rs, `show`): its bytes as they
/// are, its name and caption in headers. Returns the name the hub keeps it as.
pub fn post_media(session: &str, name: &str, caption: Option<&str>, tech: Option<&str>, bytes: &[u8]) -> Result<String> {
    let key = key().context("showing media needs a hub key (MIDAS_HUB_KEY or ~/.config/midas/hub.env)")?;
    let mut headers = vec![("X-Midas-Name", hub::pct_encode(name))];
    if let Some(c) = caption {
        headers.push(("X-Midas-Caption", hub::pct_encode(c)));
    }
    if let Some(t) = tech {
        headers.push(("X-Midas-Tech", hub::pct_encode(t)));
    }
    let (code, text) = hub::request_bytes(&hub_url(), &format!("/v1/hosted/{session}/media"), bytes, &headers, &key)
        .context("sending it to the hub")?;
    let v = parse(code, &text)?;
    v["file"].as_str().map(str::to_string).context("the hub kept no file")
}

/// A session's agent's transcript, to the hub (sessions.rs, `put_transcript`).
pub fn put_transcript(session: &str, bytes: &[u8]) -> Result<()> {
    let key = key().context("carrying a session needs a hub key (MIDAS_HUB_KEY or ~/.config/midas/hub.env)")?;
    let (code, text) = hub::request_bytes(&hub_url(), &format!("/v1/hosted/{session}/transcript"), bytes, &[], &key)
        .context("sending the transcript to the hub")?;
    parse(code, &text).map(|_| ())
}

/// A session's carried transcript, from the hub.
pub fn get_transcript(session: &str) -> Result<Vec<u8>> {
    let key = key().context("carrying a session needs a hub key (MIDAS_HUB_KEY or ~/.config/midas/hub.env)")?;
    let (code, body) = hub::get_bytes(&hub_url(), &format!("/v1/hosted/{session}/transcript"), &key).context("asking the hub for the transcript")?;
    if code != 200 {
        bail!("the hub has no transcript for {session} ({code}: {})", String::from_utf8_lossy(&body).trim());
    }
    Ok(body)
}

/// Best effort: an event that cannot reach the hub is lost, not an error.
pub fn send_event(ev: &Value) {
    // With the caller's key when there is one: the hub acts on some kinds
    // (`events::drives_state`) only when it knows who sent them.
    let _ = hub::request_auth(&hub_url(), "POST", "/v1/events", Some(&ev.to_string()), key().as_deref());
}

pub fn events(f: &Filter) -> Result<Vec<Value>> {
    Ok(get(&format!("/v1/events?{}", f.query()))?.as_array().cloned().unwrap_or_default())
}

/// The whole picture: nodes with readings, leases, the queue.
pub fn state() -> Result<Value> {
    get("/v1/state")
}

/// The node definitions with their live state and latest readings.
pub fn nodes() -> Result<Vec<Value>> {
    if crate::registry::is_hub() {
        return Ok(crate::registry::snapshot()?["nodes"].as_array().cloned().unwrap_or_default());
    }
    Ok(state()?["nodes"].as_array().cloned().unwrap_or_default())
}

/// Who holds `node`, and since when: `(owner, claimed_at)`.
pub fn lease(node: &str) -> Result<Option<(String, i64)>> {
    let v = get(&format!("/v1/lease/{node}"))?;
    Ok((v["leased"] == true).then(|| (v["owner"].as_str().unwrap_or("").to_string(), v["since"].as_i64().unwrap_or(0))))
}