From 782c5a8701ea25fa59e3615103a0117865fc5ee5 Mon Sep 17 00:00:00 2001 From: Simon Klee Date: Wed, 4 Nov 2026 18:30:47 +0100 Subject: [PATCH] feat(cli-rs): connect to --server or a discovered service Port ServerConnection.resolve, the /api/info probe and its decide() classification, and the connect error texts. Discovery tries the OPENCODE_CHANNEL registration, then service.json, then every other service*.json newest first (O-21), so the client finds a channel build's service without flags. A mismatched version warns and is never replaced; standalone and ensure wait for F.9. --- packages/cli-rs/Cargo.lock | 8 + packages/cli-rs/crates/service/Cargo.toml | 11 + .../cli-rs/crates/service/examples/connect.rs | 38 ++ packages/cli-rs/crates/service/src/connect.rs | 392 ++++++++++++++++++ .../cli-rs/crates/service/src/discover.rs | 256 ++++++++++++ packages/cli-rs/crates/service/src/lib.rs | 3 + packages/cli-rs/crates/service/src/probe.rs | 389 +++++++++++++++++ packages/cli-rs/crates/service/src/testing.rs | 70 ++++ 8 files changed, 1167 insertions(+) create mode 100644 packages/cli-rs/crates/service/examples/connect.rs create mode 100644 packages/cli-rs/crates/service/src/testing.rs diff --git a/packages/cli-rs/Cargo.lock b/packages/cli-rs/Cargo.lock index 2c2f10a9440..0de53d98848 100644 --- a/packages/cli-rs/Cargo.lock +++ b/packages/cli-rs/Cargo.lock @@ -1036,8 +1036,16 @@ dependencies = [ name = "opencode-service" version = "0.1.0" dependencies = [ + "anyhow", + "bytes", + "futures-util", "opencode-api", "opencode-local", + "serde_json", + "tempfile", + "thiserror", + "tokio", + "url", ] [[package]] diff --git a/packages/cli-rs/crates/service/Cargo.toml b/packages/cli-rs/crates/service/Cargo.toml index 68dbed37b56..791163197fe 100644 --- a/packages/cli-rs/crates/service/Cargo.toml +++ b/packages/cli-rs/crates/service/Cargo.toml @@ -12,3 +12,14 @@ workspace = true [dependencies] opencode-api.workspace = true opencode-local.workspace = true +futures-util.workspace = true +serde_json.workspace = true +thiserror.workspace = true +tokio = { workspace = true, features = ["time"] } +url.workspace = true + +[dev-dependencies] +anyhow.workspace = true +bytes.workspace = true +tempfile.workspace = true +tokio = { workspace = true, features = ["macros", "rt-multi-thread"] } diff --git a/packages/cli-rs/crates/service/examples/connect.rs b/packages/cli-rs/crates/service/examples/connect.rs new file mode 100644 index 00000000000..042bc1f8cb3 --- /dev/null +++ b/packages/cli-rs/crates/service/examples/connect.rs @@ -0,0 +1,38 @@ +//! Connects the way the CLI does and prints the server version from `/api/info`. +//! +//! `cargo run -p opencode-service --example connect [-- --print-logs] [--server URL]` + +use std::sync::Arc; + +use opencode_api::client::RequestOptions; +use opencode_api::transport::Reqwest; +use opencode_local::paths::Paths; +use opencode_service::connect::{self, Env, Options}; + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + let args: Vec = std::env::args().skip(1).collect(); + let mut env = Env::from_env(); + env.print_logs |= args.iter().any(|arg| arg == "--print-logs"); + let options = Options { + server: args + .iter() + .position(|arg| arg == "--server") + .and_then(|index| args.get(index + 1).cloned()), + standalone: args.iter().any(|arg| arg == "--standalone"), + client_version: "local".to_owned(), + }; + let transport = Arc::new(Reqwest::default()); + let connection = + connect::resolve(transport.clone(), &Paths::from_env()?, &env, &options).await?; + // A second, typed request through the generated client, with the endpoint's credentials. + let info = connection + .endpoint + .client(transport)? + .server_info(&RequestOptions::default()) + .await?; + println!("source: {:?}", connection.source); + println!("url: {}", connection.endpoint.url); + println!("version: {}", info.version); + Ok(()) +} diff --git a/packages/cli-rs/crates/service/src/connect.rs b/packages/cli-rs/crates/service/src/connect.rs index e39ab2acc34..3e143dae11c 100644 --- a/packages/cli-rs/crates/service/src/connect.rs +++ b/packages/cli-rs/crates/service/src/connect.rs @@ -1 +1,393 @@ //! `--server`, standalone, registered service, or ensure (F.6). +//! +//! Ports `ServerConnection.resolve` (`packages/cli/src/services/server-connection.ts:25-64`) with +//! two changes (plan 6.6, decision O-21): a service is found through [`discover`], which tries more +//! than one registration, and a service of another version is used with a warning, never +//! replaced. Starting a service or a standalone server is F.9; until then those paths are errors. + +use std::fmt::Write as _; +use std::path::PathBuf; +use std::sync::Arc; +use std::time::Duration; + +use opencode_api::client::RequestOptions; +use opencode_api::error::Error as ApiError; +use opencode_api::transport::Transport; +use opencode_local::channel::Channels; +use opencode_local::paths::Paths; +use opencode_local::service_config::ServiceConfig; + +use crate::discover::{self, Missing}; +use crate::probe::Endpoint; + +/// How long `--server` waits for `/api/info` (`server-connection.ts:40`). +pub const SERVER_TIMEOUT: Duration = Duration::from_secs(5); + +/// What the command line asked for. +#[derive(Clone, Debug, Default)] +pub struct Options { + pub server: Option, + pub standalone: bool, + /// This client's version, for the mismatch warning. + pub client_version: String, +} + +/// The environment `resolve` reads. +#[derive(Clone, Default, PartialEq, Eq)] +pub struct Env { + /// `OPENCODE_PASSWORD`, else `OPENCODE_SERVER_PASSWORD` (`packages/cli/src/env.ts:10-13`). + pub password: Option, + /// `OPENCODE_CHANNEL`. + pub channel: Option, + /// `OPENCODE_PRINT_LOGS=1`, which `--print-logs` sets. + pub print_logs: bool, +} + +impl std::fmt::Debug for Env { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Env") + .field("password", &self.password.as_ref().map(|_| "")) + .field("channel", &self.channel) + .field("print_logs", &self.print_logs) + .finish() + } +} + +impl Env { + pub fn from_env() -> Self { + Self::from_vars(|name| std::env::var(name).ok()) + } + + pub fn from_vars(var: impl Fn(&str) -> Option) -> Self { + // Effect's `Config.Redacted` takes an empty value as set, so an empty password is sent. + Self { + password: var("OPENCODE_PASSWORD").or_else(|| var("OPENCODE_SERVER_PASSWORD")), + channel: var("OPENCODE_CHANNEL").filter(|channel| !channel.is_empty()), + print_logs: var("OPENCODE_PRINT_LOGS").as_deref() == Some("1"), + } + } +} + +/// A server the client can use. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Connection { + pub endpoint: Endpoint, + /// The version the server reported. + pub version: String, + pub source: Source, + /// The mismatch warning, already written to stderr, if any. + pub warning: Option, +} + +/// Where the server came from. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Source { + /// `--server`. + Server, + /// A registered background service. + Service { channel: String, file: PathBuf }, +} + +/// A connection failure, with the TypeScript client's text. +#[derive(Debug, thiserror::Error)] +#[error("{message}")] +pub struct Error { + pub message: String, +} + +impl Error { + fn new(message: impl Into) -> Self { + Self { + message: message.into(), + } + } +} + +/// Finds the server to use: `--server`, else standalone, else a registered service. +pub async fn resolve( + transport: Arc, + paths: &Paths, + env: &Env, + options: &Options, +) -> Result { + if options.server.is_some() && options.standalone { + return Err(Error::new("--server and --standalone cannot be combined")); + } + if let Some(url) = &options.server { + let endpoint = Endpoint::new(url, env.password.clone()); + let version = server_version(transport, &endpoint).await?; + return Ok(connected(endpoint, version, Source::Server, options)); + } + let channels = Channels::from_vars(|name| match name { + "OPENCODE_CHANNEL" => env.channel.clone().map(Into::into), + _ => None, + }); + let disabled = ServiceConfig::new(paths, &channels.channel) + .read() + .map_err(|error| Error::new(format!("Failed to read the service config: {error}")))? + .disabled + == Some(true); + if options.standalone || disabled { + return Err(Error::new( + "A standalone server is not supported yet (plan step F.9); pass --server", + )); + } + let found = discover::discover(transport.as_ref(), paths, env.channel.as_deref()) + .await + .map_err(|missing| not_found(paths, missing))?; + if env.print_logs { + eprintln!( + "INFO service.connect channel={} file={} url={}", + found.channel, + found.file.display(), + found.service.endpoint.url + ); + } + let version = found.service.version.clone().unwrap_or_default(); + let source = Source::Service { + channel: found.channel, + file: found.file, + }; + Ok(connected(found.service.endpoint, version, source, options)) +} + +fn connected(endpoint: Endpoint, version: String, source: Source, options: &Options) -> Connection { + let warning = (version != options.client_version).then(|| { + format!( + "Warning: Server at {} has version {version}; this client is {}. Continuing anyway.", + endpoint.url, options.client_version + ) + }); + if let Some(warning) = &warning { + eprintln!("{warning}"); + } + Connection { + endpoint, + version, + source, + warning, + } +} + +async fn server_version( + transport: Arc, + endpoint: &Endpoint, +) -> Result { + let client = endpoint + .client(transport) + .map_err(|error| connect_error(endpoint, &error))?; + match tokio::time::timeout( + SERVER_TIMEOUT, + client.server_info(&RequestOptions::default()), + ) + .await + { + Ok(Ok(info)) => Ok(info.version), + Ok(Err(error)) => Err(connect_error(endpoint, &error)), + // The abort signal of the TypeScript client fails the fetch as a transport error. + Err(_) => Err(Error::new(format!( + "Could not reach server at {}: The operation timed out.", + endpoint.url + ))), + } +} + +// `connectError` (`server-connection.ts:99-114`). +fn connect_error(endpoint: &Endpoint, error: &ApiError) -> Error { + let url = &endpoint.url; + if error.reason() == "UnauthorizedError" { + return Error::new(match endpoint.auth { + None => format!("Server at {url} requires a password; set OPENCODE_PASSWORD"), + Some(_) => format!("Server at {url} rejected the password"), + }); + } + if let ApiError::Transport(cause) = error { + return Error::new(format!("Could not reach server at {url}: {cause}")); + } + Error::new(format!( + "Server at {url} did not provide a compatible V2 health response: {error}" + )) +} + +fn not_found(paths: &Paths, missing: Missing) -> Error { + let mut message = format!( + "No running OpenCode service found in {}. Start one with `opencode service start`, or pass --server.", + paths.state.display() + ); + if let Some(reason) = missing.reason { + let _ = write!(message, " {reason}"); + } + Error::new(message) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testing::{Reply, Server}; + use std::ffi::OsString; + use std::path::Path; + + fn paths(root: &Path) -> Paths { + let state = root.join("state").into_os_string(); + let config = root.join("config").into_os_string(); + let paths = Paths::from_vars(|name| match name { + "HOME" => Some(OsString::from(root)), + "XDG_STATE_HOME" => Some(state.clone()), + "XDG_CONFIG_HOME" => Some(config.clone()), + _ => None, + }) + .unwrap(); + std::fs::create_dir_all(&paths.state).unwrap(); + std::fs::create_dir_all(&paths.config).unwrap(); + paths + } + + fn options(server: Option<&str>) -> Options { + Options { + server: server.map(str::to_owned), + standalone: false, + client_version: "1.0.0".to_owned(), + } + } + + const URL: &str = "http://127.0.0.1:4096"; + const INFO: &str = "http://127.0.0.1:4096/api/info"; + const HEALTH: &str = r#"{"version":"2.0.0","pid":9,"urls":[],"paths":{"tmp":"/tmp"}}"#; + + async fn run( + server: Server, + env: Env, + options: Options, + ) -> (Result, Arc) { + let dir = tempfile::tempdir().unwrap(); + let paths = paths(dir.path()); + let server = Arc::new(server); + let result = resolve(server.clone(), &paths, &env, &options).await; + (result, server) + } + + fn message(result: Result) -> String { + result.unwrap_err().message + } + + #[tokio::test] + async fn server_flag_connects_with_the_password_and_warns_on_a_mismatch() { + let env = + Env::from_vars(|name| (name == "OPENCODE_SERVER_PASSWORD").then(|| "pw".to_owned())); + let (result, server) = run( + Server::default().reply(INFO, Reply::json(200, HEALTH)), + env, + options(Some(URL)), + ) + .await; + let connection = result.unwrap(); + assert_eq!(connection.version, "2.0.0"); + assert_eq!(connection.source, Source::Server); + assert_eq!( + connection.warning.as_deref(), + Some( + "Warning: Server at http://127.0.0.1:4096 has version 2.0.0; this client is 1.0.0. Continuing anyway." + ) + ); + assert_eq!( + server.requests()[0].1.as_deref(), + Some( + format!( + "Basic {}", + opencode_api::client::Auth::password("pw").token() + ) + .as_str() + ) + ); + assert!(!format!("{connection:?}").contains("pw")); + } + + #[tokio::test] + async fn server_flag_errors_use_the_typescript_texts() { + let unauthorized = || { + Server::default().reply( + INFO, + Reply::json(401, r#"{"_tag":"UnauthorizedError","message":"no"}"#), + ) + }; + let (result, _) = run(unauthorized(), Env::default(), options(Some(URL))).await; + assert_eq!( + message(result), + "Server at http://127.0.0.1:4096 requires a password; set OPENCODE_PASSWORD" + ); + let env = Env::from_vars(|name| (name == "OPENCODE_PASSWORD").then(|| "pw".to_owned())); + let (result, _) = run(unauthorized(), env, options(Some(URL))).await; + assert_eq!( + message(result), + "Server at http://127.0.0.1:4096 rejected the password" + ); + let (result, _) = run(Server::default(), Env::default(), options(Some(URL))).await; + assert_eq!( + message(result), + "Could not reach server at http://127.0.0.1:4096: connection refused" + ); + let (result, _) = run( + Server::default().reply(INFO, Reply::json(200, "{}")), + Env::default(), + options(Some(URL)), + ) + .await; + assert!(message(result).starts_with( + "Server at http://127.0.0.1:4096 did not provide a compatible V2 health response: " + )); + let both = Options { + standalone: true, + ..options(Some(URL)) + }; + let (result, _) = run(Server::default(), Env::default(), both).await; + assert_eq!( + message(result), + "--server and --standalone cannot be combined" + ); + } + + #[tokio::test] + async fn a_registered_service_is_used_without_flags() { + let dir = tempfile::tempdir().unwrap(); + let paths = paths(dir.path()); + std::fs::write( + paths.state.join("service-oc-x.json"), + r#"{"url":"http://127.0.0.1:4096","pid":9,"version":"2.0.0","password":"p"}"#, + ) + .unwrap(); + let server: Arc = + Arc::new(Server::default().reply(INFO, Reply::json(200, HEALTH))); + let connection = resolve(server.clone(), &paths, &Env::default(), &options(None)) + .await + .unwrap(); + assert_eq!(connection.version, "2.0.0"); + assert_eq!( + connection.source, + Source::Service { + channel: "oc-x".to_owned(), + file: paths.state.join("service-oc-x.json") + } + ); + assert!(connection.warning.is_some()); + // The same version gives no warning. + let same = Options { + client_version: "2.0.0".to_owned(), + ..options(None) + }; + let connection = resolve(server, &paths, &Env::default(), &same) + .await + .unwrap(); + assert_eq!(connection.warning, None); + } + + #[tokio::test] + async fn no_service_says_how_to_start_one() { + let (result, _) = run(Server::default(), Env::default(), options(None)).await; + let text = message(result); + assert!( + text.starts_with("No running OpenCode service found in "), + "{text}" + ); + assert!(text.contains("`opencode service start`"), "{text}"); + } +} diff --git a/packages/cli-rs/crates/service/src/discover.rs b/packages/cli-rs/crates/service/src/discover.rs index 8f16e4cde04..126764677dc 100644 --- a/packages/cli-rs/crates/service/src/discover.rs +++ b/packages/cli-rs/crates/service/src/discover.rs @@ -1 +1,257 @@ //! Registration discovery (F.6). +//! +//! The TypeScript client reads the registration of its build channel and probes it +//! (`discover`, `packages/client/src/effect/service.ts:25-31`). The Rust client has no build +//! channel, and the installed `opencode` may be a preview channel with its own file, so it tries +//! several registrations in order (decision O-21): +//! +//! 1. the registration of `OPENCODE_CHANNEL`, when set; +//! 2. the registration of the client's own channel ([`channel::DEFAULT`]); +//! 3. every other `service*.json` in the state directory, newest first. +//! +//! The first ready, compatible service wins. Discovery only reads: it never migrates, replaces, or +//! stops a service. + +use std::path::{Path, PathBuf}; + +use futures_util::future::join_all; +use opencode_api::transport::Transport; +use opencode_local::channel; +use opencode_local::paths::Paths; +use opencode_local::registration; + +use crate::probe::{self, Decision, LocalService, REQUEST_TIMEOUT}; + +/// A service discovery found, and where it was registered. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Found { + pub service: LocalService, + pub file: PathBuf, + /// The channel the file name stands for: `latest` for `service.json`, else the part after + /// `service-` (a legacy file shows its hash). + pub channel: String, +} + +/// Why no candidate was usable: the first registration that answered but could not be used, if +/// any (such as "Background service failed to start"). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Missing { + pub reason: Option, +} + +/// Discovers a ready, compatible service. `env_channel` is `OPENCODE_CHANNEL`. +pub async fn discover( + transport: &dyn Transport, + paths: &Paths, + env_channel: Option<&str>, +) -> Result { + let preferred = preferred(paths, env_channel); + let mut reason = None; + for file in &preferred { + match usable(transport, file).await { + Ok(found) => return Ok(found), + Err(why) => reason = reason.or(why), + } + } + let scanned = scan(&paths.state, &preferred); + // Probes run together so that unresponsive registrations cost one timeout, not one each. + for result in join_all(scanned.iter().map(|file| usable(transport, file))).await { + match result { + Ok(found) => return Ok(found), + Err(why) => reason = reason.or(why), + } + } + Err(Missing { reason }) +} + +/// The registration files of `OPENCODE_CHANNEL` and of the default channel, without duplicates. +pub fn preferred(paths: &Paths, env_channel: Option<&str>) -> Vec { + let mut files: Vec = env_channel + .filter(|channel| !channel.is_empty()) + .into_iter() + .chain([channel::DEFAULT]) + .map(|channel| registration::Files::new(paths, channel).file) + .collect(); + files.dedup(); + files +} + +/// Every `service*.json` in `state` not in `skip`, newest first. +pub fn scan(state: &Path, skip: &[PathBuf]) -> Vec { + let Ok(entries) = std::fs::read_dir(state) else { + return Vec::new(); + }; + let mut files: Vec<(std::time::SystemTime, PathBuf)> = entries + .filter_map(Result::ok) + .filter(|entry| { + let name = entry.file_name(); + let name = name.to_string_lossy(); + name.starts_with("service") && name.ends_with(".json") + }) + .filter(|entry| !skip.contains(&entry.path())) + .filter_map(|entry| { + let metadata = entry.metadata().ok().filter(std::fs::Metadata::is_file)?; + Some((metadata.modified().ok()?, entry.path())) + }) + .collect(); + files.sort_by(|left, right| right.cmp(left)); + files.into_iter().map(|(_, file)| file).collect() +} + +/// The channel a registration file name stands for. +pub fn channel_of(file: &Path) -> String { + let name = file + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default(); + match name + .strip_prefix("service-") + .and_then(|rest| rest.strip_suffix(".json")) + { + Some(channel) => channel.to_owned(), + None => channel::DEFAULT.to_owned(), + } +} + +// The service registered in `file` when it is ready and compatible. Otherwise the reason it cannot +// be used, when it answered. +async fn usable(transport: &dyn Transport, file: &Path) -> Result> { + let registration = registration::read(file).ok_or(None)?; + let service = probe::probe(transport, ®istration, REQUEST_TIMEOUT) + .await + .service + .ok_or(None)?; + match probe::decide(&service, None) { + Decision::Reuse => Ok(Found { + service, + file: file.to_owned(), + channel: channel_of(file), + }), + Decision::Wait => Err(Some(format!( + "Background service at {} is still starting", + service.endpoint.url + ))), + Decision::Fail(reason) => Err(Some(reason)), + Decision::Replace { .. } => unreachable!("no version requirement"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testing::{Reply, Server}; + use std::ffi::OsString; + use std::time::{Duration, SystemTime}; + + fn paths(root: &Path) -> Paths { + let state = root.join("state").into_os_string(); + let paths = Paths::from_vars(|name| match name { + "HOME" => Some(OsString::from(root)), + "XDG_STATE_HOME" => Some(state.clone()), + _ => None, + }) + .unwrap(); + std::fs::create_dir_all(&paths.state).unwrap(); + paths + } + + // Writes a registration for `port` with pid `port`, `age` seconds old. + fn register(paths: &Paths, name: &str, port: u16, age: u64) { + let file = paths.state.join(name); + std::fs::write( + &file, + format!(r#"{{"url":"http://127.0.0.1:{port}","pid":{port},"password":"p"}}"#), + ) + .unwrap(); + let time = SystemTime::now() - Duration::from_secs(age); + std::fs::File::options() + .write(true) + .open(&file) + .unwrap() + .set_modified(time) + .unwrap(); + } + + fn ready(port: u16) -> (String, Reply) { + let body = format!(r#"{{"version":"1.0.0","pid":{port}}}"#).leak(); + ( + format!("http://127.0.0.1:{port}/api/info"), + Reply::json(200, body), + ) + } + + fn server(replies: impl IntoIterator) -> Server { + replies + .into_iter() + .fold(Server::default(), |server, (url, reply)| { + server.reply(&url, reply) + }) + } + + async fn found(server: &Server, paths: &Paths, env: Option<&str>) -> Result { + discover(server, paths, env) + .await + .map(|found| found.channel) + } + + #[tokio::test] + async fn prefers_the_env_channel_then_the_default_channel() { + let dir = tempfile::tempdir().unwrap(); + let paths = paths(dir.path()); + register(&paths, "service.json", 1001, 50); + register(&paths, "service-oc-x.json", 1002, 100); + register(&paths, "service-oc-new.json", 1003, 0); + let all = server([ready(1001), ready(1002), ready(1003)]); + assert_eq!(found(&all, &paths, Some("oc-x")).await.unwrap(), "oc-x"); + assert_eq!(found(&all, &paths, None).await.unwrap(), "latest"); + // `dev` shares `service.json`. + assert_eq!(found(&all, &paths, Some("dev")).await.unwrap(), "latest"); + } + + #[tokio::test] + async fn falls_back_to_the_newest_answering_registration() { + let dir = tempfile::tempdir().unwrap(); + let paths = paths(dir.path()); + register(&paths, "service.json", 1001, 0); + register(&paths, "service-oc-old.json", 1002, 200); + register(&paths, "service-oc-dead.json", 1003, 10); + register(&paths, "service-oc-mid.json", 1004, 100); + std::fs::write(paths.state.join("service.json.identity"), "{}").unwrap(); + std::fs::write(paths.state.join("service-oc-bad.json"), "{").unwrap(); + let live = server([ready(1002), ready(1004)]); + assert_eq!( + found(&live, &paths, Some("oc-gone")).await.unwrap(), + "oc-mid" + ); + // The scan probes the dead and newer registration too, but takes the newest that answered. + let probed: Vec = live.requests().into_iter().map(|(url, _)| url).collect(); + assert!(probed.contains(&"http://127.0.0.1:1003/api/info".to_owned())); + } + + #[tokio::test] + async fn reports_why_an_answering_service_was_not_used() { + let dir = tempfile::tempdir().unwrap(); + let paths = paths(dir.path()); + assert_eq!( + found(&Server::default(), &paths, None).await, + Err(Missing { reason: None }) + ); + register(&paths, "service.json", 1001, 0); + let failed = server([( + "http://127.0.0.1:1001/api/info".to_owned(), + Reply::json(500, r#"{"version":"1.0.0","pid":1001}"#), + )]); + assert_eq!( + found(&failed, &paths, None).await, + Err(Missing { + reason: Some("Background service failed to start".to_owned()) + }) + ); + } + + #[test] + fn channel_names() { + assert_eq!(channel_of(Path::new("/s/service.json")), "latest"); + assert_eq!(channel_of(Path::new("/s/service-oc-x.json")), "oc-x"); + } +} diff --git a/packages/cli-rs/crates/service/src/lib.rs b/packages/cli-rs/crates/service/src/lib.rs index f94701180ff..838452d60b0 100644 --- a/packages/cli-rs/crates/service/src/lib.rs +++ b/packages/cli-rs/crates/service/src/lib.rs @@ -11,3 +11,6 @@ pub mod spawn; pub mod standalone; pub mod stop; pub mod ts_command; + +#[cfg(test)] +mod testing; diff --git a/packages/cli-rs/crates/service/src/probe.rs b/packages/cli-rs/crates/service/src/probe.rs index 20a4ae64337..de86c771077 100644 --- a/packages/cli-rs/crates/service/src/probe.rs +++ b/packages/cli-rs/crates/service/src/probe.rs @@ -1 +1,390 @@ //! `/api/info` probe and classification (F.6). +//! +//! Ports `packages/client/src/service-probe.ts`: ask a registered service for its health, classify +//! the answer, and decide what a client does with it. + +use std::sync::Arc; +use std::time::Duration; + +use opencode_api::client::{Auth, Client}; +use opencode_api::error::Error; +use opencode_api::transport::{Request, Transport}; +use opencode_local::registration::Registration; + +/// How long one probe waits (`defaultEnsureTiming.requestTimeout`, +/// `packages/client/src/service-timing.ts:18`). +pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(2); + +/// A server URL and its credentials. `Debug` hides the password. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Endpoint { + pub url: String, + pub auth: Option, +} + +impl Endpoint { + /// An endpoint with Basic credentials for user `opencode`, or none. + pub fn new(url: impl Into, password: Option) -> Self { + Self { + url: url.into(), + auth: password.map(Auth::password), + } + } + + /// An API client for this endpoint on `transport`. + pub fn client(&self, transport: Arc) -> Result { + let client = Client::with_transport(&self.url, transport)?; + Ok(match &self.auth { + Some(auth) => client.auth(auth.clone()), + None => client, + }) + } +} + +/// The probe's view of a service's startup. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum State { + Ready, + Waiting, + Failed, +} + +/// A registered service that answered its probe (`LocalService`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LocalService { + pub registration: Registration, + pub endpoint: Endpoint, + pub version: Option, + pub state: State, + /// False when the server has no `/api/info` (an incompatible health protocol). + pub compatible: bool, +} + +/// The result of one probe. `timed_out` tells an unresponsive service from one that is gone. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Probe { + pub service: Option, + pub timed_out: bool, +} + +/// What a client does with a service that answered (`decide`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Decision { + Reuse, + Wait, + /// The version does not meet the requirement. `handoff` keeps persistent terminals, which only + /// a ready service can hand over. The Rust client never replaces a service (plan 6.6); F.9 maps + /// this to a warning. + Replace { + handoff: bool, + }, + Fail(String), +} + +/// A version requirement: none, or a predicate on the service version (`DiscoverOptions.version`). +pub type Requirement<'a> = Option<&'a dyn Fn(&str) -> bool>; + +/// Whether `version` meets `required` (`packages/client/src/service-version.ts`). +pub fn matches_version(version: Option<&str>, required: Requirement<'_>) -> bool { + match (required, version) { + (None, _) => true, + (Some(_), None) => false, + (Some(required), Some(version)) => required(version), + } +} + +const INCOMPATIBLE: &str = "Background service uses an incompatible health protocol. Update this client or explicitly restart the service."; + +/// Decides what to do with a service that answered (`packages/client/src/service-probe.ts:22-32`). +pub fn decide(service: &LocalService, required: Requirement<'_>) -> Decision { + if !matches_version(service.version.as_deref(), required) { + return Decision::Replace { + handoff: service.state == State::Ready, + }; + } + if !service.compatible { + return Decision::Fail(INCOMPATIBLE.to_owned()); + } + match service.state { + State::Ready => Decision::Reuse, + State::Failed => Decision::Fail("Background service failed to start".to_owned()), + State::Waiting => Decision::Wait, + } +} + +/// Asks a registered service for its health and classifies the answer +/// (`probeResult`, `packages/client/src/service-probe.ts:49-90`). Any failure to get a usable +/// answer is "no service"; so is an answer from another process (pid) or version than registered. +pub async fn probe( + transport: &dyn Transport, + registration: &Registration, + timeout: Duration, +) -> Probe { + let endpoint = Endpoint::new(®istration.url, registration.password.clone()); + match tokio::time::timeout(timeout, answer(transport, &endpoint)).await { + Err(_) => Probe { + service: None, + timed_out: true, + }, + Ok(answer) => Probe { + service: answer.and_then(|answer| classify(registration, endpoint, answer)), + timed_out: false, + }, + } +} + +struct Answer { + status: u16, + info: Option<(String, u32)>, +} + +async fn answer(transport: &dyn Transport, endpoint: &Endpoint) -> Option { + // `new URL("/api/info", url)`: the absolute path replaces any path on the registered URL. + let url = url::Url::parse(&endpoint.url) + .ok()? + .join("/api/info") + .ok()?; + let headers = endpoint + .auth + .iter() + .map(|auth| { + ( + "authorization".to_owned(), + format!("Basic {}", auth.token()), + ) + }) + .collect(); + let response = transport + .send(Request { + method: "GET", + url, + headers, + body: None, + }) + .await + .ok()?; + let status = response.status; + if status == 404 { + return Some(Answer { status, info: None }); + } + // A body that is not JSON rejects the TypeScript fetch, which counts as no answer. + let body: serde_json::Value = serde_json::from_slice(&response.bytes().await.ok()?).ok()?; + Some(Answer { + status, + info: Some(decode_info(&body)?), + }) +} + +fn classify( + registration: &Registration, + endpoint: Endpoint, + answer: Answer, +) -> Option { + // A missing health endpoint identifies protocol incompatibility, not an older version. + let Some((version, pid)) = answer.info else { + return Some(LocalService { + registration: registration.clone(), + endpoint, + version: registration.version.clone(), + state: State::Ready, + compatible: false, + }); + }; + if pid != registration.pid { + return None; + } + if registration + .version + .as_ref() + .is_some_and(|registered| *registered != version) + { + return None; + } + let state = match answer.status { + 200..=299 => State::Ready, + 500 => State::Failed, + _ => State::Waiting, + }; + Some(LocalService { + registration: registration.clone(), + endpoint, + version: Some(version), + state, + compatible: true, + }) +} + +// `version` a string and `pid` a non-negative JavaScript integer (`decodeInfo`). +fn decode_info(body: &serde_json::Value) -> Option<(String, u32)> { + let version = body.get("version")?.as_str()?.to_owned(); + let pid = body + .get("pid")? + .as_f64() + .filter(|pid| pid.fract() == 0.0 && *pid >= 0.0 && *pid <= f64::from(u32::MAX))?; + Some((version, pid as u32)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testing::{Reply, Server}; + + // The cases of `packages/client/test/service-decision.test.ts`. + fn service(version: Option<&str>, state: State, compatible: bool) -> LocalService { + LocalService { + registration: Registration { + id: None, + version: version.map(str::to_owned), + url: "http://127.0.0.1:4096".to_owned(), + pid: 4242, + password: None, + }, + endpoint: Endpoint::new("http://127.0.0.1:4096", None), + version: version.map(str::to_owned), + state, + compatible, + } + } + + fn exact(expected: &'static str) -> impl Fn(&str) -> bool { + move |version| version == expected + } + + #[test] + fn a_missing_health_endpoint_fails_unless_the_caller_requires_a_different_version() { + let missing = service(Some("2.0.0"), State::Ready, false); + let protocol = Decision::Fail(INCOMPATIBLE.to_owned()); + assert_eq!(decide(&missing, None), protocol); + assert_eq!(decide(&missing, Some(&exact("2.0.0"))), protocol); + assert_eq!( + decide(&missing, Some(&|version: &str| version.starts_with("2."))), + protocol + ); + assert_eq!( + decide(&missing, Some(&exact("3.0.0"))), + Decision::Replace { handoff: true } + ); + assert_eq!( + decide(&service(None, State::Ready, false), Some(&exact("3.0.0"))), + Decision::Replace { handoff: true } + ); + } + + #[test] + fn a_compatible_service_is_reused_when_ready_awaited_while_starting_and_fails_when_it_failed() { + assert_eq!( + decide(&service(Some("2.0.0"), State::Ready, true), None), + Decision::Reuse + ); + assert_eq!( + decide( + &service(Some("2.0.0"), State::Waiting, true), + Some(&exact("2.0.0")) + ), + Decision::Wait + ); + assert_eq!( + decide(&service(Some("2.0.0"), State::Failed, true), None), + Decision::Fail("Background service failed to start".to_owned()) + ); + } + + #[test] + fn a_version_mismatch_replaces_the_service_handing_off_terminals_only_when_it_is_ready() { + let two = exact("2.0.0"); + for (state, handoff) in [ + (State::Ready, true), + (State::Waiting, false), + (State::Failed, false), + ] { + assert_eq!( + decide(&service(Some("1.0.0"), state, true), Some(&two)), + Decision::Replace { handoff } + ); + } + } + + fn registration(version: Option<&str>) -> Registration { + Registration { + id: None, + version: version.map(str::to_owned), + url: "http://127.0.0.1:4096/prefix".to_owned(), + pid: 7, + password: Some("secret".to_owned()), + } + } + + async fn probed(reply: Reply, version: Option<&str>) -> Probe { + let server = Server::default().reply("http://127.0.0.1:4096/api/info", reply); + probe(&server, ®istration(version), REQUEST_TIMEOUT).await + } + + #[tokio::test] + async fn probe_classifies_answers() { + let state = |probe: Probe| { + probe + .service + .map(|service| (service.state, service.compatible)) + }; + let info = r#"{"version":"1.0.0","pid":7}"#; + assert_eq!( + state(probed(Reply::json(200, info), Some("1.0.0")).await), + Some((State::Ready, true)) + ); + assert_eq!( + state(probed(Reply::json(503, info), None).await), + Some((State::Waiting, true)) + ); + assert_eq!( + state(probed(Reply::json(500, info), None).await), + Some((State::Failed, true)) + ); + assert_eq!( + state(probed(Reply::json(404, "not json"), None).await), + Some((State::Ready, false)) + ); + // Another process, another version, a body without the fields, and no listener. + for (reply, version) in [ + (Reply::json(200, r#"{"version":"1.0.0","pid":8}"#), None), + (Reply::json(200, info), Some("2.0.0")), + (Reply::json(200, r#"{"version":"1.0.0","pid":-1}"#), None), + (Reply::json(401, r#"{"_tag":"UnauthorizedError"}"#), None), + (Reply::json(200, ""), None), + (Reply::Refused, None), + ] { + let probe = probed(reply, version).await; + assert_eq!( + probe, + Probe { + service: None, + timed_out: false + } + ); + } + } + + #[tokio::test] + async fn probe_sends_basic_auth_and_times_out() { + let server = Server::default().reply( + "http://127.0.0.1:4096/api/info", + Reply::json(200, r#"{"version":"1.0.0","pid":7}"#), + ); + probe(&server, ®istration(None), REQUEST_TIMEOUT).await; + assert_eq!( + server.requests(), + vec![( + "http://127.0.0.1:4096/api/info".to_owned(), + Some(format!("Basic {}", Auth::password("secret").token())) + )] + ); + let slow = Server::default().reply("http://127.0.0.1:4096/api/info", Reply::Hang); + let probe = probe(&slow, ®istration(None), Duration::from_millis(10)).await; + assert_eq!( + probe, + Probe { + service: None, + timed_out: true + } + ); + } +} diff --git a/packages/cli-rs/crates/service/src/testing.rs b/packages/cli-rs/crates/service/src/testing.rs new file mode 100644 index 00000000000..77cd811e8a3 --- /dev/null +++ b/packages/cli-rs/crates/service/src/testing.rs @@ -0,0 +1,70 @@ +//! A fake transport for the crate's tests: fixed replies per URL, and a record of the requests. + +use std::collections::HashMap; +use std::sync::Mutex; + +use bytes::Bytes; +use opencode_api::transport::{BoxFuture, Request, Response, Transport}; + +#[derive(Clone)] +pub enum Reply { + Status(u16, &'static str), + Refused, + Hang, +} + +impl Reply { + pub fn json(status: u16, body: &'static str) -> Self { + Self::Status(status, body) + } +} + +#[derive(Default)] +pub struct Server { + replies: HashMap, + requests: Mutex)>>, +} + +impl Server { + pub fn reply(mut self, url: &str, reply: Reply) -> Self { + self.replies.insert(url.to_owned(), reply); + self + } + + /// URL and `authorization` header of each request, in order. + pub fn requests(&self) -> Vec<(String, Option)> { + self.requests.lock().unwrap().clone() + } +} + +impl Transport for Server { + fn send(&self, request: Request) -> BoxFuture<'_, Result> { + let authorization = request + .headers + .iter() + .find(|(name, _)| name == "authorization") + .map(|(_, value)| value.clone()); + self.requests + .lock() + .unwrap() + .push((request.url.to_string(), authorization)); + let reply = self + .replies + .get(request.url.as_str()) + .cloned() + .unwrap_or(Reply::Refused); + Box::pin(async move { + match reply { + Reply::Refused => Err("connection refused".to_owned()), + Reply::Hang => std::future::pending().await, + Reply::Status(status, body) => Ok(Response { + status, + headers: vec![("content-type".to_owned(), "application/json".to_owned())], + body: Box::pin(futures_util::stream::iter([Ok(Bytes::from_static( + body.as_bytes(), + ))])), + }), + } + }) + } +}