diff --git a/aimdb-client/CHANGELOG.md b/aimdb-client/CHANGELOG.md index 2efadbbe..8fff2c3b 100644 --- a/aimdb-client/CHANGELOG.md +++ b/aimdb-client/CHANGELOG.md @@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- **Requests time out (#474).** Every typed call that awaits a reply + (`get_record`, `set_record`, `list_records`, `drain_record`, `query`, + `graph_*`, `instance_info`, each `post_link` chunk, the resets) is bounded by + the connection's request timeout, `DEFAULT_REQUEST_TIMEOUT` (5 s), and fails + with the new `ClientError::Timeout { method, after }` instead of waiting + forever on an instance that stopped answering after the handshake. Set it + with `AimxConnection::with_request_timeout`. The connection stays open and a + late reply is discarded. Subscriptions, `write_record` and raw + `handle().call(…)` are not bounded. + ### Changed - **A rejected `set_record` value is `invalid_value` (#454).** A value the diff --git a/aimdb-client/src/engine.rs b/aimdb-client/src/engine.rs index 8889b28e..d4a34318 100644 --- a/aimdb-client/src/engine.rs +++ b/aimdb-client/src/engine.rs @@ -39,6 +39,14 @@ use aimdb_core::{Stamp, Stamped}; /// no handshake timeout of its own, so the wait would otherwise be unbounded. pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(5); +/// Default deadline for each request after the handshake (`record.get`, +/// `record.set`, `record.list`, …). Bounds the case where an instance stops +/// answering mid-session — a hung task, a board held by a watchdog, a link that +/// dropped without closing — which the engine cannot tell from a slow reply. +/// Subscriptions are not bounded by it. See +/// [`AimxConnection::with_request_timeout`]. +pub const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(5); + /// Response from a `record.drain` call: the values accumulated since the /// previous drain for this connection's per-record cursor. #[derive(Debug, Clone, PartialEq)] @@ -110,6 +118,7 @@ pub struct AimxConnection { handle: ClientHandle, engine: JoinHandle<()>, server_info: WelcomeMessage, + request_timeout: Duration, } impl AimxConnection { @@ -211,6 +220,7 @@ impl AimxConnection { handle, engine, server_info, + request_timeout: DEFAULT_REQUEST_TIMEOUT, }), Err(e) => { // Don't leave the engine task blocked on a stalled dial/connection. @@ -220,8 +230,29 @@ impl AimxConnection { } } + /// Set the deadline for each request on this connection, replacing + /// [`DEFAULT_REQUEST_TIMEOUT`]. + /// + /// A request that gets no reply in time fails with + /// [`ClientError::Timeout`]; the connection stays open, and a reply that + /// arrives later is discarded. It covers every typed call that awaits a + /// reply — not [`subscribe`](Self::subscribe), not + /// [`write_record`](Self::write_record), and not raw calls made through + /// [`handle`](Self::handle). [`post_link`](Self::post_link) applies it to + /// each chunk. + pub fn with_request_timeout(mut self, request_timeout: Duration) -> Self { + self.request_timeout = request_timeout; + self + } + + /// The deadline each request on this connection gets. + pub fn request_timeout(&self) -> Duration { + self.request_timeout + } + /// The raw engine handle — `call` / `subscribe` / `write` for methods the - /// typed wrappers below don't cover. + /// typed wrappers below don't cover. Calls made through it have no + /// deadline. pub fn handle(&self) -> &ClientHandle { &self.handle } @@ -358,7 +389,7 @@ impl AimxConnection { /// Which build and which instance this is (`instance.info`, since protocol /// 3.1). `None` from a server that does not know the method. pub async fn instance_info(&self) -> ClientResult> { - match self.handle.call("instance.info", null_payload()).await { + match self.rpc("instance.info", null_payload()).await? { Ok(reply) => Ok(Some(from_payload(&reply)?)), Err(RpcError::NotFound) => Ok(None), Err(e) => Err(rpc_err(e)), @@ -381,15 +412,12 @@ impl AimxConnection { loop { let offset = data.len(); let params = json!({ "offset": offset, "len": POST_LINK_CHUNK_MAX }); - let chunk: PostLinkChunk = match self - .handle - .call("instance.post_link", to_payload(¶ms)?) - .await - { - Ok(reply) => from_payload(&reply)?, - Err(RpcError::NotFound) => return Ok(None), - Err(e) => return Err(rpc_err(e)), - }; + let chunk: PostLinkChunk = + match self.rpc("instance.post_link", to_payload(¶ms)?).await? { + Ok(reply) => from_payload(&reply)?, + Err(RpcError::NotFound) => return Ok(None), + Err(e) => return Err(rpc_err(e)), + }; let total = *total.get_or_insert(chunk.total); let bytes = check_chunk(&chunk, offset, total)?; data.extend_from_slice(&bytes); @@ -433,7 +461,19 @@ impl AimxConnection { /// Issue a raw RPC and map a transport/engine failure to [`ClientError`]. async fn call(&self, method: &str, params: Payload) -> ClientResult { - self.handle.call(method, params).await.map_err(rpc_err) + self.rpc(method, params).await?.map_err(rpc_err) + } + + /// Issue a raw RPC bounded by the request timeout. The outer error is the + /// timeout; the inner result is the engine's, for callers that treat some + /// replies (`not_found`) as an answer rather than a failure. + /// + /// Dropping the timed-out call is safe: the engine reclaims the abandoned + /// pending entry and discards a reply that turns up later. + async fn rpc(&self, method: &str, params: Payload) -> ClientResult> { + timeout(self.request_timeout, self.handle.call(method, params)) + .await + .map_err(|_| ClientError::timeout(method, self.request_timeout)) } } diff --git a/aimdb-client/src/error.rs b/aimdb-client/src/error.rs index 70a3aa28..3cd1b847 100644 --- a/aimdb-client/src/error.rs +++ b/aimdb-client/src/error.rs @@ -34,6 +34,15 @@ pub enum ClientError { #[error("Protocol error: {reason}")] Protocol { reason: String }, + /// A request got no reply within the connection's request timeout. The + /// instance may be hung, busy, or unreachable over a link that did not + /// close; the connection itself stays open. + #[error("Request {method} timed out after {after:?}: the instance did not answer")] + Timeout { + method: String, + after: std::time::Duration, + }, + /// I/O error #[error("I/O error: {0}")] Io(#[from] std::io::Error), @@ -71,6 +80,14 @@ impl ClientError { } } + /// Create a request timeout error + pub fn timeout(method: impl Into, after: std::time::Duration) -> Self { + Self::Timeout { + method: method.into(), + after, + } + } + /// Create a server error pub fn server_error( code: impl Into, diff --git a/aimdb-client/tests/request_timeout.rs b/aimdb-client/tests/request_timeout.rs new file mode 100644 index 00000000..8cae91e4 --- /dev/null +++ b/aimdb-client/tests/request_timeout.rs @@ -0,0 +1,78 @@ +//! Requests after the handshake are bounded by the connection's request +//! timeout (#474): a silent instance fails a call with +//! [`ClientError::Timeout`] instead of hanging it. + +#![cfg(feature = "transport-uds")] + +use std::time::Duration; + +use aimdb_client::{AimxConnection, ClientError}; +use serde_json::{json, Value}; +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; +use tokio::net::UnixListener; + +/// A server on the raw AimX wire that completes the `hello` handshake, answers +/// `record.list` with an empty list, and never answers anything else — an +/// instance that stopped responding after the handshake. +async fn serve_silent(dir: &tempfile::TempDir) -> String { + let path = dir.path().join("silent.sock"); + let listener = UnixListener::bind(&path).unwrap(); + tokio::spawn(async move { + loop { + let (stream, _) = listener.accept().await.unwrap(); + tokio::spawn(async move { + let (read, mut write) = stream.into_split(); + let mut lines = BufReader::new(read).lines(); + while let Ok(Some(line)) = lines.next_line().await { + let frame: Value = serde_json::from_str(&line).unwrap(); + let ok = |body: Value| json!({ "t": "reply", "id": frame["id"], "ok": body }); + let reply = match (frame["t"].as_str(), frame["method"].as_str()) { + (Some("ping"), _) => json!({ "t": "pong" }), + (Some("req"), Some("hello")) => ok(json!({ + "version": "4.0", "server": "aimdb", + "permissions": ["read", "write"], "writable_records": [], + })), + (Some("req"), Some("record.list")) => ok(json!([])), + // Swallow the request: no reply, ever. + _ => continue, + }; + let mut bytes = serde_json::to_vec(&reply).unwrap(); + bytes.push(b'\n'); + write.write_all(&bytes).await.unwrap(); + } + }); + } + }); + path.to_str().unwrap().to_owned() +} + +#[tokio::test] +async fn a_silent_instance_times_out_instead_of_hanging() { + let dir = tempfile::tempdir().unwrap(); + let sock = serve_silent(&dir).await; + let after = Duration::from_millis(200); + let conn = AimxConnection::connect(&sock) + .await + .expect("connect") + .with_request_timeout(after); + + let err = conn + .set_record("spike.fault", json!({ "kind": 2 })) + .await + .expect_err("no reply must not hang"); + assert!( + matches!(&err, ClientError::Timeout { method, after: a } if method == "record.set" && *a == after), + "{err}" + ); + + // Calls that treat `not_found` as an answer take a separate path. + assert!(matches!( + conn.instance_info().await, + Err(ClientError::Timeout { .. }) + )); + + // A timeout leaves the connection open: a request the instance does + // answer still succeeds. + assert!(!conn.is_closed()); + assert!(conn.list_records().await.expect("still served").is_empty()); +} diff --git a/tools/aimdb-cli/CHANGELOG.md b/tools/aimdb-cli/CHANGELOG.md index bcba3d34..4f5184d1 100644 --- a/tools/aimdb-cli/CHANGELOG.md +++ b/tools/aimdb-cli/CHANGELOG.md @@ -9,6 +9,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **`--request-timeout ` (#474),** a global option, default 5. A + command whose instance stops answering after the handshake (`record get` / + `set`, `graph …`, `instance info`) now fails with exit code 3 instead of + hanging. `watch --timeout` is unchanged and still governs how long `watch` + waits for updates. + - **`aimdb record list` shows a `Key` column (#455)** as its first column: the record key that `aimdb record get` / `set` and `aimdb watch` take. The `Name` column (the Rust type name) stays beside it. JSON output is diff --git a/tools/aimdb-cli/README.md b/tools/aimdb-cli/README.md index 51055708..20b90e52 100644 --- a/tools/aimdb-cli/README.md +++ b/tools/aimdb-cli/README.md @@ -108,6 +108,11 @@ instance (see [Connecting to an Instance](#connecting-to-an-instance)). When omitted, the CLI reads the `AIMDB_CONNECT` env var, then falls back to UDS auto-discovery. `instance list` is discovery-only and ignores `--connect`. +`--request-timeout ` (global, default 5) bounds each reply after the +handshake, so a hung instance or a link that dropped without closing fails +with exit code 3 instead of hanging the command. It does not limit how long +`watch` waits for updates; that is `watch --timeout`. + ### Instance Commands #### `instance list` @@ -442,7 +447,7 @@ unreachable instance without retrying a rejected request: | 0 | Success | | | 1 | Rejected: the instance or a remote service refused the request | record not found, record not writable, server error | | 2 | Usage: bad arguments or malformed input | unknown subcommand or flag, unsupported `--connect` endpoint, invalid JSON for `record set` | -| 3 | Environment: worth retrying | connection failed, no instance found, protocol mismatch, I/O error, a reply that does not parse | +| 3 | Environment: worth retrying | connection failed, no instance found, protocol mismatch, I/O error, a reply that does not parse, no reply within `--request-timeout` | | 4 | Timeout | `watch --timeout` passed before `--count` updates arrived | ```bash diff --git a/tools/aimdb-cli/src/commands/graph.rs b/tools/aimdb-cli/src/commands/graph.rs index cc0beb77..ebe54cad 100644 --- a/tools/aimdb-cli/src/commands/graph.rs +++ b/tools/aimdb-cli/src/commands/graph.rs @@ -2,7 +2,7 @@ //! //! Commands for exploring the dependency graph of records in an AimDB instance. -use crate::commands::connect_endpoint; +use crate::commands::Target; use crate::error::CliResult; use crate::output::{json, table, OutputFormat}; use clap::Args; @@ -44,18 +44,18 @@ pub enum GraphSubcommand { } impl GraphCommand { - pub async fn execute(self, endpoint: Option<&str>) -> CliResult<()> { + pub async fn execute(self, target: Target<'_>) -> CliResult<()> { match self.subcommand { - GraphSubcommand::Nodes { format } => list_nodes(endpoint, format).await, - GraphSubcommand::Edges { format } => list_edges(endpoint, format).await, - GraphSubcommand::Order { format } => show_topo_order(endpoint, format).await, - GraphSubcommand::Dot { name } => export_dot(endpoint, &name).await, + GraphSubcommand::Nodes { format } => list_nodes(target, format).await, + GraphSubcommand::Edges { format } => list_edges(target, format).await, + GraphSubcommand::Order { format } => show_topo_order(target, format).await, + GraphSubcommand::Dot { name } => export_dot(target, &name).await, } } } -async fn list_nodes(endpoint: Option<&str>, format: OutputFormat) -> CliResult<()> { - let client = connect_endpoint(endpoint).await?; +async fn list_nodes(target: Target<'_>, format: OutputFormat) -> CliResult<()> { + let client = target.connect().await?; let nodes = client.graph_nodes().await?; @@ -72,8 +72,8 @@ async fn list_nodes(endpoint: Option<&str>, format: OutputFormat) -> CliResult<( Ok(()) } -async fn list_edges(endpoint: Option<&str>, format: OutputFormat) -> CliResult<()> { - let client = connect_endpoint(endpoint).await?; +async fn list_edges(target: Target<'_>, format: OutputFormat) -> CliResult<()> { + let client = target.connect().await?; let edges = client.graph_edges().await?; @@ -90,8 +90,8 @@ async fn list_edges(endpoint: Option<&str>, format: OutputFormat) -> CliResult<( Ok(()) } -async fn show_topo_order(endpoint: Option<&str>, format: OutputFormat) -> CliResult<()> { - let client = connect_endpoint(endpoint).await?; +async fn show_topo_order(target: Target<'_>, format: OutputFormat) -> CliResult<()> { + let client = target.connect().await?; let order = client.graph_topo_order().await?; @@ -108,8 +108,8 @@ async fn show_topo_order(endpoint: Option<&str>, format: OutputFormat) -> CliRes Ok(()) } -async fn export_dot(endpoint: Option<&str>, name: &str) -> CliResult<()> { - let client = connect_endpoint(endpoint).await?; +async fn export_dot(target: Target<'_>, name: &str) -> CliResult<()> { + let client = target.connect().await?; let nodes = client.graph_nodes().await?; let edges = client.graph_edges().await?; diff --git a/tools/aimdb-cli/src/commands/instance.rs b/tools/aimdb-cli/src/commands/instance.rs index 09a0bfb6..7cb181e8 100644 --- a/tools/aimdb-cli/src/commands/instance.rs +++ b/tools/aimdb-cli/src/commands/instance.rs @@ -1,5 +1,6 @@ //! Instance Management Commands +use crate::commands::Target; use crate::error::CliResult; use crate::output::{json, table, OutputFormat}; use aimdb_client::discovery::{discover_instances, find_instance, InstanceInfo}; @@ -37,14 +38,14 @@ pub enum InstanceSubcommand { } impl InstanceCommand { - pub async fn execute(self, endpoint: Option<&str>) -> CliResult<()> { + pub async fn execute(self, target: Target<'_>) -> CliResult<()> { match self.subcommand { // `list` is discovery-only (a Unix-socket scan); it ignores --connect. InstanceSubcommand::List { format } => list_instances(format).await, InstanceSubcommand::Info { format, post_link } => { - show_instance_info(endpoint, format, post_link).await + show_instance_info(target, format, post_link).await } - InstanceSubcommand::Ping {} => ping_instance(endpoint).await, + InstanceSubcommand::Ping {} => ping_instance(target.endpoint).await, } } } @@ -81,16 +82,18 @@ async fn list_instances(format: OutputFormat) -> CliResult<()> { } async fn show_instance_info( - endpoint: Option<&str>, + target: Target<'_>, format: OutputFormat, with_post_link: bool, ) -> CliResult<()> { // `instance.info` needs a connection, so discovery only picks the endpoint. - let endpoint = match endpoint { + let endpoint = match target.endpoint { Some(ep) => ep.to_string(), None => find_instance(None).await?.endpoint.display().to_string(), }; - let conn = AimxConnection::connect(&endpoint).await?; + let conn = AimxConnection::connect(&endpoint) + .await? + .with_request_timeout(target.request_timeout); let instance = InstanceInfo::from((PathBuf::from(&endpoint), conn.server_info().clone())); let reply = conn.instance_info().await?; let post_link = match with_post_link { diff --git a/tools/aimdb-cli/src/commands/mod.rs b/tools/aimdb-cli/src/commands/mod.rs index 6a040967..4b52408f 100644 --- a/tools/aimdb-cli/src/commands/mod.rs +++ b/tools/aimdb-cli/src/commands/mod.rs @@ -7,21 +7,36 @@ pub mod instance; pub mod record; pub mod watch; +use std::time::Duration; + use aimdb_client::AimxConnection; use crate::error::CliResult; -/// Resolve an `endpoint` to a live connection. -/// -/// An explicit endpoint (`--connect`, or the `AIMDB_CONNECT` env) dials directly — -/// any `scheme://` URL, or a bare path as the `unix://` shorthand. `None` falls -/// back to UDS auto-discovery (the first running instance found). -pub(crate) async fn connect_endpoint(endpoint: Option<&str>) -> CliResult { - match endpoint { - Some(ep) => Ok(AimxConnection::connect(ep).await?), - None => { - let instance = aimdb_client::discovery::find_instance(None).await?; - Ok(AimxConnection::connect(&instance.endpoint.to_string_lossy()).await?) - } +/// The instance a command talks to, and how long each request may take. +#[derive(Debug, Clone, Copy)] +pub(crate) struct Target<'a> { + /// An explicit endpoint (`--connect`, or the `AIMDB_CONNECT` env), or + /// `None` for UDS auto-discovery. + pub endpoint: Option<&'a str>, + /// Deadline for each request after the handshake (`--request-timeout`). + pub request_timeout: Duration, +} + +impl Target<'_> { + /// Resolve the target to a live connection. + /// + /// An explicit endpoint dials directly — any `scheme://` URL, or a bare + /// path as the `unix://` shorthand. `None` falls back to UDS + /// auto-discovery (the first running instance found). + pub async fn connect(self) -> CliResult { + let conn = match self.endpoint { + Some(ep) => AimxConnection::connect(ep).await?, + None => { + let instance = aimdb_client::discovery::find_instance(None).await?; + AimxConnection::connect(&instance.endpoint.to_string_lossy()).await? + } + }; + Ok(conn.with_request_timeout(self.request_timeout)) } } diff --git a/tools/aimdb-cli/src/commands/record.rs b/tools/aimdb-cli/src/commands/record.rs index 1f340d77..b1545d88 100644 --- a/tools/aimdb-cli/src/commands/record.rs +++ b/tools/aimdb-cli/src/commands/record.rs @@ -1,6 +1,6 @@ //! Record Management Commands -use crate::commands::connect_endpoint; +use crate::commands::Target; use crate::error::CliResult; use crate::output::{json, table, OutputFormat}; use clap::Args; @@ -48,27 +48,27 @@ pub enum RecordSubcommand { } impl RecordCommand { - pub async fn execute(self, endpoint: Option<&str>) -> CliResult<()> { + pub async fn execute(self, target: Target<'_>) -> CliResult<()> { match self.subcommand { RecordSubcommand::List { format, writable } => { - list_records(endpoint, format, writable).await + list_records(target, format, writable).await } - RecordSubcommand::Get { record, format } => get_record(&record, endpoint, format).await, + RecordSubcommand::Get { record, format } => get_record(&record, target, format).await, RecordSubcommand::Set { name, value, dry_run, - } => set_record(&name, &value, endpoint, dry_run).await, + } => set_record(&name, &value, target, dry_run).await, } } } async fn list_records( - endpoint: Option<&str>, + target: Target<'_>, format: OutputFormat, writable_only: bool, ) -> CliResult<()> { - let client = connect_endpoint(endpoint).await?; + let client = target.connect().await?; let mut records = client.list_records().await?; @@ -90,8 +90,8 @@ async fn list_records( Ok(()) } -async fn get_record(name: &str, endpoint: Option<&str>, format: OutputFormat) -> CliResult<()> { - let client = connect_endpoint(endpoint).await?; +async fn get_record(name: &str, target: Target<'_>, format: OutputFormat) -> CliResult<()> { + let client = target.connect().await?; let sample = client.get_record(name).await?; @@ -116,7 +116,7 @@ async fn get_record(name: &str, endpoint: Option<&str>, format: OutputFormat) -> async fn set_record( name: &str, value_str: &str, - endpoint: Option<&str>, + target: Target<'_>, dry_run: bool, ) -> CliResult<()> { // Parse JSON value @@ -130,7 +130,7 @@ async fn set_record( return Ok(()); } - let client = connect_endpoint(endpoint).await?; + let client = target.connect().await?; let result = client.set_record(name, value).await?; diff --git a/tools/aimdb-cli/src/commands/watch.rs b/tools/aimdb-cli/src/commands/watch.rs index a1fa8b38..32abf1e4 100644 --- a/tools/aimdb-cli/src/commands/watch.rs +++ b/tools/aimdb-cli/src/commands/watch.rs @@ -3,7 +3,7 @@ use std::io::Write; use std::time::Duration; -use crate::commands::connect_endpoint; +use crate::commands::Target; use crate::error::{CliError, CliResult, EXIT_ENVIRONMENT, EXIT_REJECTED}; use crate::output::live; use aimdb_client::watch::{self, WatchOutcome, WatchStatus}; @@ -55,7 +55,7 @@ pub struct WatchCommand { } impl WatchCommand { - pub async fn execute(self, endpoint: Option<&str>) -> CliResult<()> { + pub async fn execute(self, target: Target<'_>) -> CliResult<()> { let mut watcher = Watcher::new(self.format, self.full, std::io::stdout(), std::io::stderr()); let options = WatchOptions { @@ -63,7 +63,7 @@ impl WatchCommand { new: self.new, timeout: self.timeout.map(Duration::from_secs), }; - let result = watch_record(&self.record, endpoint, options, &mut watcher).await; + let result = watch_record(&self.record, target, options, &mut watcher).await; if let Err(e) = &result { watcher.failed(e)?; } @@ -79,11 +79,11 @@ struct WatchOptions { async fn watch_record( record_name: &str, - endpoint: Option<&str>, + target: Target<'_>, options: WatchOptions, watcher: &mut Watcher, ) -> CliResult<()> { - let conn = connect_endpoint(endpoint).await?; + let conn = target.connect().await?; // The stream is loss-aware, so the watcher reports gaps instead of // skipping over them silently. With `--new`, the record's current stamp @@ -126,7 +126,7 @@ async fn watch_record( wanted: outcome.wanted, }), WatchStatus::Disconnected => Err(CliError::connection_failed( - endpoint.unwrap_or("auto-discovered instance"), + target.endpoint.unwrap_or("auto-discovered instance"), format!( "the subscription ended after {} of {} updates", outcome.received, outcome.wanted diff --git a/tools/aimdb-cli/src/error.rs b/tools/aimdb-cli/src/error.rs index 2b7e45a2..965bb839 100644 --- a/tools/aimdb-cli/src/error.rs +++ b/tools/aimdb-cli/src/error.rs @@ -76,6 +76,13 @@ pub enum CliError { wanted: usize, }, + /// The instance did not answer a request in time + #[error("Request timed out: {method} got no reply within {after:?}\n Hint: the instance may be hung or the link down; raise --request-timeout if it is just slow")] + RequestTimeout { + method: String, + after: std::time::Duration, + }, + /// I/O error occurred #[error("I/O error: {0}")] Io(#[from] std::io::Error), @@ -109,6 +116,9 @@ impl From for CliError { details, }, aimdb_client::ClientError::Protocol { reason } => CliError::Protocol { reason }, + aimdb_client::ClientError::Timeout { method, after } => { + CliError::RequestTimeout { method, after } + } aimdb_client::ClientError::Io(e) => CliError::Io(e), aimdb_client::ClientError::Json(e) => CliError::Json(e), aimdb_client::ClientError::Other(e) => CliError::Other(e), @@ -126,6 +136,8 @@ impl CliError { | Self::NoInstancesFound | Self::ProtocolMismatch { .. } | Self::Protocol { .. } + // A silent instance: worth retrying, unlike `watch --timeout`. + | Self::RequestTimeout { .. } | Self::Io(_) // A reply or file that does not parse. | Self::Json(_) => EXIT_ENVIRONMENT, @@ -211,6 +223,9 @@ mod tests { CliError::NoInstancesFound, CliError::protocol_mismatch("m", "2", "1"), CliError::Io(std::io::Error::other("io")), + // A silent instance (#474), as the client reports it. + aimdb_client::ClientError::timeout("record.get", std::time::Duration::from_secs(5)) + .into(), CliError::Json(serde_json::from_str::("{").unwrap_err()), ]; let usage = [ diff --git a/tools/aimdb-cli/src/main.rs b/tools/aimdb-cli/src/main.rs index 5fcd0c9f..49b51f2f 100644 --- a/tools/aimdb-cli/src/main.rs +++ b/tools/aimdb-cli/src/main.rs @@ -3,9 +3,12 @@ //! This tool provides commands to discover, inspect, and interact with running //! AimDB instances via the AimX remote access protocol (v2 NDJSON wire). +use std::time::Duration; + use clap::{Parser, Subcommand}; use commands::{ graph::GraphCommand, instance::InstanceCommand, record::RecordCommand, watch::WatchCommand, + Target, }; mod commands; @@ -27,6 +30,19 @@ struct Cli { #[arg(long, global = true)] connect: Option, + /// Seconds to wait for each reply from the instance before failing with + /// exit code 3. Covers requests after the handshake (`record get/set`, + /// `graph …`, `instance info`), not the updates `watch` waits for: that + /// has its own `--timeout`. + #[arg( + long, + global = true, + value_name = "SECS", + default_value_t = aimdb_client::engine::DEFAULT_REQUEST_TIMEOUT.as_secs(), + value_parser = clap::value_parser!(u64).range(1..), + )] + request_timeout: u64, + /// Enable verbose output #[arg(short, long, global = true)] verbose: bool, @@ -60,13 +76,16 @@ async fn main() { .connect .or_else(|| std::env::var("AIMDB_CONNECT").ok()) .filter(|s| !s.is_empty()); - let endpoint = endpoint.as_deref(); + let target = Target { + endpoint: endpoint.as_deref(), + request_timeout: Duration::from_secs(cli.request_timeout), + }; let result = match cli.command { - Command::Instance(cmd) => cmd.execute(endpoint).await, - Command::Record(cmd) => cmd.execute(endpoint).await, - Command::Graph(cmd) => cmd.execute(endpoint).await, - Command::Watch(cmd) => cmd.execute(endpoint).await, + Command::Instance(cmd) => cmd.execute(target).await, + Command::Record(cmd) => cmd.execute(target).await, + Command::Graph(cmd) => cmd.execute(target).await, + Command::Watch(cmd) => cmd.execute(target).await, }; if let Err(e) = result { diff --git a/tools/aimdb-mcp/CHANGELOG.md b/tools/aimdb-mcp/CHANGELOG.md index 9c566228..1a2f171a 100644 --- a/tools/aimdb-mcp/CHANGELOG.md +++ b/tools/aimdb-mcp/CHANGELOG.md @@ -9,6 +9,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **A silent instance no longer hangs a tool (#474).** Each request on the + persistent client times out after 5 s, releasing the client for the next + call. The timeout reaches the agent as a tool error (`isError: true`, text + naming the method) rather than a JSON-RPC error, so it can retry or report + the instance as unresponsive. The session is kept: a timeout does not + reconnect. + - **Every tool shares one session per endpoint (#451).** Tools opened a new connection per call, which over serial failed (the tty was already open) or sent a new `hello` that reset the board's session and discarded its drain diff --git a/tools/aimdb-mcp/src/server.rs b/tools/aimdb-mcp/src/server.rs index 5ac2ba7f..2e385afd 100644 --- a/tools/aimdb-mcp/src/server.rs +++ b/tools/aimdb-mcp/src/server.rs @@ -473,19 +473,19 @@ impl McpServer { }; let result = match params.name.as_str() { - "discover_instances" => tools::discover_instances(params.arguments).await?, - "list_records" => tools::list_records(params.arguments).await?, - "get_record" => tools::get_record(params.arguments).await?, - "set_record" => tools::set_record(params.arguments).await?, - "get_instance_info" => tools::get_instance_info(params.arguments).await?, - "drain_record" => tools::drain_record(params.arguments).await?, - "graph_nodes" => tools::graph_nodes(params.arguments).await?, - "graph_edges" => tools::graph_edges(params.arguments).await?, - "graph_topo_order" => tools::graph_topo_order(params.arguments).await?, - "get_buffer_metrics" => tools::get_buffer_metrics(params.arguments).await?, - "reset_buffer_metrics" => tools::reset_buffer_metrics(params.arguments).await?, - "get_stage_profiling" => tools::get_stage_profiling(params.arguments).await?, - "reset_stage_profiling" => tools::reset_stage_profiling(params.arguments).await?, + "discover_instances" => tools::discover_instances(params.arguments).await, + "list_records" => tools::list_records(params.arguments).await, + "get_record" => tools::get_record(params.arguments).await, + "set_record" => tools::set_record(params.arguments).await, + "get_instance_info" => tools::get_instance_info(params.arguments).await, + "drain_record" => tools::drain_record(params.arguments).await, + "graph_nodes" => tools::graph_nodes(params.arguments).await, + "graph_edges" => tools::graph_edges(params.arguments).await, + "graph_topo_order" => tools::graph_topo_order(params.arguments).await, + "get_buffer_metrics" => tools::get_buffer_metrics(params.arguments).await, + "reset_buffer_metrics" => tools::reset_buffer_metrics(params.arguments).await, + "get_stage_profiling" => tools::get_stage_profiling(params.arguments).await, + "reset_stage_profiling" => tools::reset_stage_profiling(params.arguments).await, _ => { return Err(McpError::MethodNotFound(format!( "Unknown tool: {}", @@ -494,15 +494,7 @@ impl McpServer { } }; - // Wrap result in ToolCallResult - let content = vec![ToolContent::Text { - text: serde_json::to_string_pretty(&result)?, - }]; - - Ok(ToolCallResult { - content, - is_error: Some(false), - }) + tool_call_result(result) } /// Handle resources/list request @@ -588,6 +580,26 @@ impl Default for McpServer { } } +/// Wrap a tool's outcome in a [`ToolCallResult`]. +/// +/// A request the instance did not answer in time is a tool error +/// (`isError: true`) the agent sees and can act on — retry, or report the +/// instance as unresponsive — not a JSON-RPC protocol error. Every other error +/// stays a protocol error, as before. +fn tool_call_result(result: McpResult) -> McpResult { + let (text, is_error) = match result { + Ok(value) => (serde_json::to_string_pretty(&value)?, false), + Err(McpError::Client(e @ aimdb_client::ClientError::Timeout { .. })) => { + (e.to_string(), true) + } + Err(e) => return Err(e), + }; + Ok(ToolCallResult { + content: vec![ToolContent::Text { text }], + is_error: Some(is_error), + }) +} + #[cfg(test)] mod tests { use super::*; @@ -721,6 +733,29 @@ mod tests { ); } + /// A request timeout reaches the agent as a tool error (#474); other + /// failures stay protocol errors. + #[test] + fn a_request_timeout_is_a_tool_error() { + let timeout = + aimdb_client::ClientError::timeout("record.get", std::time::Duration::from_secs(5)); + let result = tool_call_result(Err(McpError::Client(timeout))).unwrap(); + assert_eq!(result.is_error, Some(true)); + let ToolContent::Text { text } = &result.content[0] else { + panic!("expected text content"); + }; + assert!(text.contains("record.get"), "{text}"); + assert!(text.contains("did not answer"), "{text}"); + + let ok = tool_call_result(Ok(json!({ "n": 1 }))).unwrap(); + assert_eq!(ok.is_error, Some(false)); + + let other = tool_call_result(Err(McpError::Client( + aimdb_client::ClientError::NoInstancesFound, + ))); + assert!(matches!(other, Err(McpError::Client(_)))); + } + #[tokio::test] async fn public_mode_wins_over_allow_writes() { let server = McpServer::new()