cellos-ctl 0.5.3

cellctl — kubectl-style CLI for CellOS execution cells and formations. Thin HTTP client over cellos-server with apply/get/describe/logs/events/webui.
Documentation
//! HTTP client wrapping reqwest for cellos-server.
//!
//! Per Feynman (CHATROOM Session 16): "cellctl is a thin client over cellos-server.
//! Every command = exactly one API call." This module is that contract.
//!
//! All state queries hit the projector via HTTP. There is no client-side cache.

use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE};
use reqwest::StatusCode;
use serde::de::DeserializeOwned;
use serde::Serialize;

use crate::config::Config;
use crate::exit::{CtlError, CtlResult};

/// User-Agent string sent to the server — helps the projector identify CLI traffic.
const USER_AGENT: &str = concat!("cellctl/", env!("CARGO_PKG_VERSION"));

/// Build the right `/v1/formations/...` path for a user-supplied
/// identifier. CTL-002 (E2E report): the server's `/v1/formations/{id}`
/// route uses `Path<Uuid>` and rejects names with HTTP 400. We detect
/// the shape locally and route to the parallel `/v1/formations/by-name/{name}`
/// route when the input is not a UUID.
///
/// Detection is `Uuid::parse_str(input).is_ok()` — UUID-shaped strings
/// always go to the UUID route (preserves existing operator workflows),
/// everything else routes to by-name. We URL-encode the name so an
/// operator-supplied identifier containing `/` or other reserved
/// characters does not silently truncate or break path parsing.
pub fn formation_path(ident: &str) -> String {
    if uuid::Uuid::parse_str(ident).is_ok() {
        format!("/v1/formations/{ident}")
    } else {
        format!(
            "/v1/formations/by-name/{}",
            url::form_urlencoded::byte_serialize(ident.as_bytes()).collect::<String>()
        )
    }
}

#[cfg(test)]
mod path_tests {
    use super::formation_path;

    #[test]
    fn uuid_input_uses_uuid_route() {
        // Canonical hyphenated v4.
        let id = "550e8400-e29b-41d4-a716-446655440000";
        assert_eq!(formation_path(id), format!("/v1/formations/{id}"));
    }

    #[test]
    fn simple_name_uses_by_name_route() {
        assert_eq!(formation_path("demo"), "/v1/formations/by-name/demo");
    }

    #[test]
    fn name_with_reserved_chars_is_url_encoded() {
        // `/` in a name MUST NOT escape the path segment.
        let got = formation_path("ns/team");
        assert!(
            got.starts_with("/v1/formations/by-name/") && !got.contains("ns/team"),
            "expected encoded segment, got {got}"
        );
        // Round-trip via percent decoder to confirm semantic preservation.
        let tail = got.trim_start_matches("/v1/formations/by-name/");
        let decoded: String = url::form_urlencoded::parse(format!("k={tail}").as_bytes())
            .next()
            .map(|(_, v)| v.into_owned())
            .unwrap_or_default();
        assert_eq!(decoded, "ns/team");
    }

    #[test]
    fn empty_string_routes_to_by_name() {
        // Empty is not a UUID; the server will surface a 404 (or a
        // route-level miss). Either way, cellctl does not silently
        // mis-route to the UUID path.
        assert_eq!(formation_path(""), "/v1/formations/by-name/");
    }

    #[test]
    fn uppercase_uuid_input_uses_uuid_route() {
        // RFC 4122 §3 explicitly allows uppercase hex; `Uuid::parse_str`
        // accepts it. The server's `Path<Uuid>` extractor does too.
        let id = "550E8400-E29B-41D4-A716-446655440000";
        assert_eq!(formation_path(id), format!("/v1/formations/{id}"));
    }

    #[test]
    fn near_uuid_shaped_name_does_not_collide() {
        // A 32-char hex string without hyphens parses as a UUID per
        // RFC 4122 §3 "simple" form — that is intentional and the
        // server's Uuid extractor accepts it. This pin documents the
        // boundary: if an operator ever names a formation as 32 hex
        // chars, cellctl WILL route it to the UUID path. That is the
        // known ambiguity Option B accepts (Option C would have made
        // it worse). The test exists so the choice is auditable.
        let s = "550e8400e29b41d4a716446655440000";
        assert_eq!(formation_path(s), format!("/v1/formations/{s}"));
    }
}

#[derive(Clone)]
pub struct CellosClient {
    base: String,
    http: reqwest::Client,
    /// Raw bearer token if configured. Held separately so paths that
    /// don't go through reqwest (the WebSocket upgrade in
    /// `cmd::events`) can still authenticate without parsing it back
    /// out of `default_headers`. EVT-002 (E2E report): cellctl's WS
    /// upgrade needs to set `Authorization: Bearer <token>` on the
    /// `http::Request`; before this field it had no clean way to
    /// reach the configured token.
    bearer: Option<String>,
}

impl CellosClient {
    pub fn new(cfg: &Config) -> CtlResult<Self> {
        let base = cfg.effective_server();
        // Normalize: strip trailing slash so we can confidently concatenate paths.
        let base = base.trim_end_matches('/').to_string();

        let bearer = cfg.effective_token();
        let mut headers = HeaderMap::new();
        headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
        if let Some(tok) = bearer.as_deref() {
            let v = HeaderValue::from_str(&format!("Bearer {tok}"))
                .map_err(|e| CtlError::usage(format!("bad token: {e}")))?;
            headers.insert(AUTHORIZATION, v);
        }

        let http = reqwest::Client::builder()
            .user_agent(USER_AGENT)
            .default_headers(headers)
            .build()
            .map_err(|e| CtlError::api(format!("init http client: {e}")))?;

        Ok(Self { base, http, bearer })
    }

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

    /// Raw bearer token, if one is configured. Used by the WebSocket
    /// upgrade path (`cmd::events::follow_ws`) where the auth header
    /// has to be installed on a `tokio_tungstenite` `http::Request`
    /// rather than a reqwest call.
    pub fn bearer_token(&self) -> Option<&str> {
        self.bearer.as_deref()
    }

    fn url(&self, path: &str) -> String {
        if path.starts_with('/') {
            format!("{}{}", self.base, path)
        } else {
            format!("{}/{}", self.base, path)
        }
    }

    /// GET <path> → T
    pub async fn get_json<T: DeserializeOwned>(&self, path: &str) -> CtlResult<T> {
        let resp = self.http.get(self.url(path)).send().await?;
        decode_json(resp).await
    }

    /// POST <path> with JSON body → T
    pub async fn post_json<B: Serialize, T: DeserializeOwned>(
        &self,
        path: &str,
        body: &B,
    ) -> CtlResult<T> {
        let resp = self.http.post(self.url(path)).json(body).send().await?;
        decode_json(resp).await
    }

    /// DELETE <path> — body ignored, only status checked.
    pub async fn delete(&self, path: &str) -> CtlResult<()> {
        let resp = self.http.delete(self.url(path)).send().await?;
        check_status(resp).await.map(|_| ())
    }

    /// Stream Server-Sent-Events-ish JSON lines (newline-delimited) from a GET endpoint.
    /// Used by `logs --follow` over HTTP chunked transfer.
    pub async fn get_stream(&self, path: &str) -> CtlResult<reqwest::Response> {
        let resp = self.http.get(self.url(path)).send().await?;
        check_status(resp).await
    }

    /// Build a WebSocket URL aligned to the same base. http→ws, https→wss.
    pub fn ws_url(&self, path: &str) -> CtlResult<String> {
        let mut u = url::Url::parse(&self.url(path))
            .map_err(|e| CtlError::usage(format!("bad url: {e}")))?;
        match u.scheme() {
            "http" => u
                .set_scheme("ws")
                .map_err(|_| CtlError::usage("set ws scheme"))?,
            "https" => u
                .set_scheme("wss")
                .map_err(|_| CtlError::usage("set wss scheme"))?,
            "ws" | "wss" => {}
            other => return Err(CtlError::usage(format!("unsupported scheme: {other}"))),
        }
        Ok(u.to_string())
    }
}

async fn check_status(resp: reqwest::Response) -> CtlResult<reqwest::Response> {
    let status = resp.status();
    if status.is_success() {
        return Ok(resp);
    }
    // Best-effort: include server-provided body in the error message.
    let body = resp.text().await.unwrap_or_default();
    let body_trim = body.trim();
    let detail = if body_trim.is_empty() {
        format!("server returned {status}")
    } else {
        format!("server returned {status}: {body_trim}")
    };
    let code = status.as_u16();
    Err(match status {
        StatusCode::BAD_REQUEST | StatusCode::UNPROCESSABLE_ENTITY => {
            CtlError::validation(detail).with_status(code)
        }
        _ => CtlError::api(detail).with_status(code),
    })
}

async fn decode_json<T: DeserializeOwned>(resp: reqwest::Response) -> CtlResult<T> {
    let resp = check_status(resp).await?;
    let bytes = resp.bytes().await?;
    serde_json::from_slice(&bytes).map_err(|e| CtlError::api(format!("decode json: {e}")))
}