From 01a1073943f89902e0bc003cfd37b5ed49fefee0 Mon Sep 17 00:00:00 2001 From: Miguel Palhas Date: Sat, 22 Aug 2026 12:11:37 +0100 Subject: [PATCH] feat(maestro): own the /api surface in maestro-protocol MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The crate held the wire types but not the wire surface, so every consumer re-derived routes, URL construction and the error envelope. Adds `routes` (path constants, axum patterns, and a single fallible `ws_base`), the `ApiError` envelope, `DaemonInfo`, and a `DaemonClient` behind an optional `client` feature. `SpawnPreset` moves here because it rides `GET /api/info`; `maestro-config` re-exports it so the on-disk schema and the payload stay one type. `ws_base` now rejects a base with no recognised scheme. The five previous copies disagreed — the CLI errored, the web proxy trusted it, the TUI passed it through. Co-Authored-By: Claude Opus 5 (1M context) --- Cargo.lock | 8 +- crates/maestro-config/Cargo.toml | 1 + crates/maestro-config/src/lib.rs | 10 +- crates/maestro-protocol/Cargo.toml | 10 ++ crates/maestro-protocol/src/client.rs | 202 ++++++++++++++++++++++++++ crates/maestro-protocol/src/lib.rs | 67 +++++++++ crates/maestro-protocol/src/routes.rs | 180 +++++++++++++++++++++++ 7 files changed, 469 insertions(+), 9 deletions(-) create mode 100644 crates/maestro-protocol/src/client.rs create mode 100644 crates/maestro-protocol/src/routes.rs diff --git a/Cargo.lock b/Cargo.lock index 12d1764..24dd4b2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1067,8 +1067,6 @@ dependencies = [ "maestro-config", "maestro-protocol", "nix", - "reqwest", - "serde", "serde_json", "tempfile", "thiserror 1.0.69", @@ -1085,6 +1083,7 @@ name = "maestro-config" version = "0.1.0" dependencies = [ "dirs", + "maestro-protocol", "serde", "tempfile", "thiserror 1.0.69", @@ -1151,8 +1150,11 @@ name = "maestro-protocol" version = "0.1.0" dependencies = [ "chrono", + "reqwest", "serde", "serde_json", + "thiserror 1.0.69", + "tokio", "uuid", ] @@ -1168,7 +1170,6 @@ dependencies = [ "maestro-config", "maestro-protocol", "ratatui", - "reqwest", "serde_json", "thiserror 1.0.69", "tokio", @@ -1189,6 +1190,7 @@ dependencies = [ "futures-util", "include_dir", "maestro-config", + "maestro-protocol", "mime_guess", "reqwest", "serde_json", diff --git a/crates/maestro-config/Cargo.toml b/crates/maestro-config/Cargo.toml index f1e4c60..96fe960 100644 --- a/crates/maestro-config/Cargo.toml +++ b/crates/maestro-config/Cargo.toml @@ -8,6 +8,7 @@ publish.workspace = true [dependencies] dirs.workspace = true +maestro-protocol.workspace = true serde.workspace = true thiserror.workspace = true toml.workspace = true diff --git a/crates/maestro-config/src/lib.rs b/crates/maestro-config/src/lib.rs index 2e3c888..5b34a3e 100644 --- a/crates/maestro-config/src/lib.rs +++ b/crates/maestro-config/src/lib.rs @@ -226,12 +226,10 @@ impl SpawnSection { /// tile, and the `command` to run. The implicit `custom` tile (see /// [`custom_preset`]) reuses this shape with an empty `command` the client /// fills from free-text input. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct SpawnPreset { - pub id: String, - pub label: String, - pub command: String, -} +/// +/// Defined in `maestro-protocol` because it also rides `GET /api/info`; the +/// on-disk `[spawn].presets` schema and the wire payload are one type. +pub use maestro_protocol::SpawnPreset; /// Reserved id for the implicit free-text tile. A user-defined preset may not /// claim it (see [`SpawnConfigError::ReservedCustomId`]) since it's always diff --git a/crates/maestro-protocol/Cargo.toml b/crates/maestro-protocol/Cargo.toml index 8a2a0cd..4027830 100644 --- a/crates/maestro-protocol/Cargo.toml +++ b/crates/maestro-protocol/Cargo.toml @@ -7,11 +7,21 @@ repository.workspace = true publish.workspace = true description = "Shared wire types for Maestro daemon/client communication" +[features] +default = [] +# Opt-in `reqwest`-backed client. Off by default so `maestro-web`, which only +# needs the wire types and route paths, does not pull an HTTP stack it has its +# own copy of. +client = ["dep:reqwest", "dep:tokio"] + [dependencies] chrono.workspace = true serde.workspace = true serde_json.workspace = true +thiserror.workspace = true uuid.workspace = true +reqwest = { workspace = true, optional = true } +tokio = { workspace = true, optional = true } [dev-dependencies] serde_json.workspace = true diff --git a/crates/maestro-protocol/src/client.rs b/crates/maestro-protocol/src/client.rs new file mode 100644 index 0000000..71ae127 --- /dev/null +++ b/crates/maestro-protocol/src/client.rs @@ -0,0 +1,202 @@ +//! Typed client for the daemon's `/api/*` surface. +//! +//! Behind the `client` feature so consumers that only need the wire types and +//! route paths — `maestro-web`, `maestro-config` — don't pull an HTTP stack. +//! +//! This is the one place that knows how to call the daemon: the CLI, the TUI and +//! the end-to-end harness all go through it. + +use std::time::Duration; + +use reqwest::{Method, Response, StatusCode}; +use serde::de::DeserializeOwned; +use serde::Serialize; +use uuid::Uuid; + +use crate::routes::{self, UrlError}; +use crate::{ + ApiError, CreateSessionRequest, DaemonInfo, DirListing, ErrorInfo, GitRoot, RecentDirs, Session, +}; + +/// Time budget for establishing a TCP connection to the daemon. +pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(5); +/// Total budget for a single request. Bounds the case where the daemon is +/// TCP-alive but never makes forward progress. +pub const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30); + +#[derive(Debug, thiserror::Error)] +pub enum ClientError { + #[error("http: {0}")] + Http(#[from] reqwest::Error), + /// The daemon answered with a structured [`ApiError`] envelope. + #[error("daemon returned {status} ({}): {}", .info.code, .info.message)] + Api { status: StatusCode, info: ErrorInfo }, + /// A non-success response whose body was not an [`ApiError`]. + #[error("daemon returned {status}: {body}")] + Status { status: StatusCode, body: String }, + #[error("decode: {0}")] + Json(#[from] serde_json::Error), + #[error(transparent)] + Url(#[from] UrlError), +} + +impl ClientError { + /// True when the daemon could not be reached at all, rather than reaching it + /// and being refused. Drives "is the daemon running?" messaging. + pub fn is_unreachable(&self) -> bool { + matches!(self, ClientError::Http(e) if e.is_connect()) + } + + /// The daemon's own message when it sent one, so callers can render the + /// reason rather than a bare status code. + pub fn daemon_message(&self) -> Option<&str> { + match self { + ClientError::Api { info, .. } => Some(&info.message), + _ => None, + } + } +} + +/// HTTP client bound to one daemon's base URL. +/// +/// The daemon's surface needs no auth — reaching its bind address is the +/// authorization, same trust model as tmux itself. +#[derive(Debug, Clone)] +pub struct DaemonClient { + base: String, + http: reqwest::Client, +} + +impl DaemonClient { + /// Client with the standard timeouts. + pub fn new(base: impl Into) -> Self { + Self::with_timeouts(base, DEFAULT_CONNECT_TIMEOUT, DEFAULT_REQUEST_TIMEOUT) + } + + /// Client with explicit timeouts, for callers with a tighter budget than the + /// default — the TUI's startup health probe wants to fail fast rather than + /// hold the terminal for 30 seconds. + pub fn with_timeouts(base: impl Into, connect: Duration, request: Duration) -> Self { + let http = reqwest::Client::builder() + .user_agent(concat!("maestro/", env!("CARGO_PKG_VERSION"))) + .connect_timeout(connect) + .timeout(request) + .build() + .expect("build reqwest client"); + Self { + base: routes::normalize_base(&base.into()).to_string(), + http, + } + } + + pub fn base(&self) -> &str { + &self.base + } + + /// `WS /api/events` URL for this daemon. + pub fn events_url(&self) -> Result { + Ok(routes::events_url(&self.base)?) + } + + /// `WS /api/attach/:id` URL for this daemon. + pub fn attach_url(&self, id: Uuid) -> Result { + Ok(routes::attach_url(&self.base, id)?) + } + + // -- typed calls -------------------------------------------------------- + + pub async fn list_sessions(&self) -> Result, ClientError> { + self.get(routes::SESSIONS, &[]).await + } + + pub async fn create_session(&self, req: &CreateSessionRequest) -> Result { + self.post(routes::SESSIONS, req).await + } + + pub async fn kill_session(&self, id: Uuid) -> Result<(), ClientError> { + let resp = self + .send(Method::DELETE, &routes::session(id), &[], None::<&()>) + .await?; + check(resp).await?; + Ok(()) + } + + pub async fn daemon_info(&self) -> Result { + self.get(routes::INFO, &[]).await + } + + pub async fn list_dir(&self, path: &str) -> Result { + self.get(routes::DIRS, &[(routes::PATH_QUERY, path)]).await + } + + pub async fn recent_dirs(&self) -> Result { + self.get(routes::RECENT_DIRS, &[]).await + } + + pub async fn git_root(&self, path: &str) -> Result { + self.get(routes::GITROOT, &[(routes::PATH_QUERY, path)]) + .await + } + + // -- plumbing ----------------------------------------------------------- + + async fn get( + &self, + path: &str, + query: &[(&str, &str)], + ) -> Result { + let resp = self.send(Method::GET, path, query, None::<&()>).await?; + json(check(resp).await?).await + } + + async fn post( + &self, + path: &str, + body: &B, + ) -> Result { + let resp = self.send(Method::POST, path, &[], Some(body)).await?; + json(check(resp).await?).await + } + + async fn send( + &self, + method: Method, + path: &str, + query: &[(&str, &str)], + body: Option<&B>, + ) -> Result { + let mut req = self + .http + .request(method, routes::http_url(&self.base, path)); + if !query.is_empty() { + req = req.query(query); + } + if let Some(b) = body { + req = req.json(b); + } + Ok(req.send().await?) + } +} + +/// Turn a non-success response into the richest error its body supports: the +/// daemon's [`ApiError`] envelope when present, the raw body otherwise. +async fn check(resp: Response) -> Result { + let status = resp.status(); + if status.is_success() { + return Ok(resp); + } + let body = resp.text().await.unwrap_or_default(); + match serde_json::from_str::(&body) { + Ok(api) => Err(ClientError::Api { + status, + info: api.error, + }), + Err(_) => Err(ClientError::Status { status, body }), + } +} + +async fn json(resp: Response) -> Result { + // `204 No Content` is a valid success for the calls that return `()`; the + // typed getters never hit it. + Ok(resp.json::().await?) +} diff --git a/crates/maestro-protocol/src/lib.rs b/crates/maestro-protocol/src/lib.rs index 048fa97..dcdf4e1 100644 --- a/crates/maestro-protocol/src/lib.rs +++ b/crates/maestro-protocol/src/lib.rs @@ -7,6 +7,13 @@ #![deny(missing_debug_implementations)] +#[cfg(feature = "client")] +pub mod client; +pub mod routes; + +#[cfg(feature = "client")] +pub use client::{ClientError, DaemonClient}; + use std::collections::HashMap; use std::path::PathBuf; @@ -158,6 +165,66 @@ pub struct ErrorInfo { pub message: String, } +/// The envelope every `/api/*` failure is wrapped in: `{"error": {…}}`. +/// +/// The daemon builds it, the CLI and TUI decode it to surface the daemon's own +/// message, and `maestro-web` uses it both to report proxy failures and to +/// recover the rejection reason from an upstream WebSocket handshake. Before it +/// lived here that shape was hand-rolled in four places, one of them by +/// escaping quotes into a format string. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ApiError { + pub error: ErrorInfo, +} + +impl ApiError { + pub fn new(code: impl Into, message: impl Into) -> Self { + Self { + error: ErrorInfo { + code: code.into(), + message: message.into(), + }, + } + } + + /// The daemon's human-readable reason, for clients that only render text. + pub fn message(&self) -> &str { + &self.error.message + } +} + +/// One command tile offered by the spawn form. +/// +/// Lives here rather than in `maestro-config` because it is on the wire inside +/// [`DaemonInfo`]; `maestro-config` re-exports it so the on-disk `[spawn]` +/// schema and the payload stay one type. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SpawnPreset { + pub id: String, + pub label: String, + pub command: String, +} + +/// Payload of `GET /api/info` — daemon identity, protocol version, and the +/// spawn presets clients render as one-click tiles. +/// +/// Previously declared three times (daemon, CLI, TypeScript), and the CLI's +/// copy silently dropped `version` and `presets`. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct DaemonInfo { + #[serde(default)] + pub hostname: String, + /// The `PROTOCOL_VERSION` the daemon implements. + #[serde(default)] + pub version: String, + /// Home directory of the OS user the daemon runs as, so clients can prefill + /// a spawn form's working directory. Empty if unresolved. + #[serde(default)] + pub home_dir: String, + #[serde(default)] + pub presets: Vec, +} + // --------------------------------------------------------------------------- // Catalog events (`WS /api/events`) // --------------------------------------------------------------------------- diff --git a/crates/maestro-protocol/src/routes.rs b/crates/maestro-protocol/src/routes.rs new file mode 100644 index 0000000..10c8131 --- /dev/null +++ b/crates/maestro-protocol/src/routes.rs @@ -0,0 +1,180 @@ +//! The daemon's `/api/*` surface: paths, and the scheme swap every client +//! needs to reach the WebSocket endpoints. +//! +//! Everything that knows what the daemon's URLs look like lives here. + +use uuid::Uuid; + +/// Prefix every daemon route shares. `maestro-web` uses it to decide whether a +/// request is proxied to the daemon or served from the SPA bundle. +pub const API_PREFIX: &str = "/api"; + +/// `GET` list / `POST` spawn. +pub const SESSIONS: &str = "/api/sessions"; +/// `GET` daemon identity, version, and spawn presets. +pub const INFO: &str = "/api/info"; +/// `GET` one directory's immediate subdirectories. Takes a `path` query param. +pub const DIRS: &str = "/api/dirs"; +/// `GET` spawn history. +pub const RECENT_DIRS: &str = "/api/recent-dirs"; +/// `GET` the enclosing repository of a path. Takes a `path` query param. +pub const GITROOT: &str = "/api/gitroot"; +/// `WS` catalog snapshot + session deltas. +pub const EVENTS: &str = "/api/events"; + +/// Name of the query parameter [`DIRS`] and [`GITROOT`] both take. +pub const PATH_QUERY: &str = "path"; + +/// `DELETE /api/sessions/:id`. +pub fn session(id: Uuid) -> String { + format!("{SESSIONS}/{id}") +} + +/// `WS /api/attach/:id` — raw PTY bytes. +pub fn attach(id: Uuid) -> String { + format!("{API_PREFIX}/attach/{id}") +} + +/// Axum-style patterns for the two parameterised routes, so the server +/// registers the same paths [`session`] and [`attach`] build. +pub mod patterns { + pub const SESSION: &str = "/api/sessions/:id"; + pub const ATTACH: &str = "/api/attach/:id"; +} + +/// A daemon base URL that could not be turned into a WebSocket base. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum UrlError { + #[error("daemon url has no supported scheme (want http/https/ws/wss): {0}")] + UnsupportedScheme(String), +} + +/// Strip a trailing slash so `{base}{path}` never doubles up. +pub fn normalize_base(base: &str) -> &str { + base.trim_end_matches('/') +} + +/// Join a daemon base URL and one of this module's paths. +pub fn http_url(base: &str, path: &str) -> String { + format!("{}{}", normalize_base(base), path) +} + +/// Swap an HTTP base URL for its WebSocket equivalent. +/// +/// `http://` becomes `ws://`, `https://` becomes `wss://`, and a base that is +/// already `ws://`/`wss://` passes through. Anything else is an error — a +/// scheme-less base would otherwise produce a URL that fails much later, at +/// connect time, with nothing pointing back at the configuration that caused +/// it. +pub fn ws_base(http_base: &str) -> Result { + let base = normalize_base(http_base); + if let Some(rest) = base.strip_prefix("https://") { + Ok(format!("wss://{rest}")) + } else if let Some(rest) = base.strip_prefix("http://") { + Ok(format!("ws://{rest}")) + } else if base.starts_with("wss://") || base.starts_with("ws://") { + Ok(base.to_string()) + } else { + Err(UrlError::UnsupportedScheme(http_base.to_string())) + } +} + +/// Full `WS /api/events` URL for a daemon reachable at `http_base`. +pub fn events_url(http_base: &str) -> Result { + Ok(format!("{}{}", ws_base(http_base)?, EVENTS)) +} + +/// Full `WS /api/attach/:id` URL for a daemon reachable at `http_base`. +pub fn attach_url(http_base: &str, id: Uuid) -> Result { + Ok(format!("{}{}", ws_base(http_base)?, attach(id))) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn id() -> Uuid { + Uuid::parse_str("6f1a7c0e-0f5e-4a2b-9a3d-6b1c2d3e4f50").unwrap() + } + + #[test] + fn ws_base_swaps_http_and_https() { + assert_eq!( + ws_base("http://127.0.0.1:7070").unwrap(), + "ws://127.0.0.1:7070" + ); + assert_eq!( + ws_base("https://laptop.lan:7070").unwrap(), + "wss://laptop.lan:7070" + ); + } + + #[test] + fn ws_base_passes_through_websocket_schemes() { + assert_eq!(ws_base("ws://10.0.0.1:7070").unwrap(), "ws://10.0.0.1:7070"); + assert_eq!( + ws_base("wss://10.0.0.1:7070").unwrap(), + "wss://10.0.0.1:7070" + ); + } + + #[test] + fn ws_base_rejects_an_unknown_scheme() { + assert_eq!( + ws_base("127.0.0.1:7070"), + Err(UrlError::UnsupportedScheme("127.0.0.1:7070".into())) + ); + assert!(ws_base("ftp://host:7070").is_err()); + } + + #[test] + fn trailing_slashes_never_double_up() { + assert_eq!(ws_base("http://host:7070/").unwrap(), "ws://host:7070"); + assert_eq!( + http_url("http://host:7070/", SESSIONS), + "http://host:7070/api/sessions" + ); + assert_eq!( + events_url("http://host:7070/").unwrap(), + "ws://host:7070/api/events" + ); + } + + #[test] + fn builds_per_session_paths() { + assert_eq!( + session(id()), + "/api/sessions/6f1a7c0e-0f5e-4a2b-9a3d-6b1c2d3e4f50" + ); + assert_eq!( + attach(id()), + "/api/attach/6f1a7c0e-0f5e-4a2b-9a3d-6b1c2d3e4f50" + ); + assert_eq!( + attach_url("https://laptop.lan:7070", id()).unwrap(), + "wss://laptop.lan:7070/api/attach/6f1a7c0e-0f5e-4a2b-9a3d-6b1c2d3e4f50" + ); + } + + /// The server registers `patterns::*` while clients call `session`/`attach`; + /// nothing but this test keeps the two spellings in step. + #[test] + fn patterns_and_builders_agree() { + assert_eq!( + patterns::SESSION.trim_end_matches(":id"), + session(id()).trim_end_matches(&id().to_string()) + ); + assert_eq!( + patterns::ATTACH.trim_end_matches(":id"), + attach(id()).trim_end_matches(&id().to_string()) + ); + } + + #[test] + fn every_route_sits_under_the_api_prefix() { + for path in [SESSIONS, INFO, DIRS, RECENT_DIRS, GITROOT, EVENTS] { + assert!(path.starts_with(API_PREFIX), "{path} escapes {API_PREFIX}"); + } + assert!(attach(id()).starts_with(API_PREFIX)); + } +}