Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions aimdb-client/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
64 changes: 52 additions & 12 deletions aimdb-client/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -110,6 +118,7 @@ pub struct AimxConnection {
handle: ClientHandle,
engine: JoinHandle<()>,
server_info: WelcomeMessage,
request_timeout: Duration,
}

impl AimxConnection {
Expand Down Expand Up @@ -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.
Expand All @@ -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
}
Expand Down Expand Up @@ -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<Option<InstanceInfoReply>> {
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)),
Expand All @@ -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(&params)?)
.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(&params)?).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);
Expand Down Expand Up @@ -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<Payload> {
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<Result<Payload, RpcError>> {
timeout(self.request_timeout, self.handle.call(method, params))
.await
.map_err(|_| ClientError::timeout(method, self.request_timeout))
}
}

Expand Down
17 changes: 17 additions & 0 deletions aimdb-client/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -71,6 +80,14 @@ impl ClientError {
}
}

/// Create a request timeout error
pub fn timeout(method: impl Into<String>, after: std::time::Duration) -> Self {
Self::Timeout {
method: method.into(),
after,
}
}

/// Create a server error
pub fn server_error(
code: impl Into<String>,
Expand Down
78 changes: 78 additions & 0 deletions aimdb-client/tests/request_timeout.rs
Original file line number Diff line number Diff line change
@@ -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());
}
6 changes: 6 additions & 0 deletions tools/aimdb-cli/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

- **`--request-timeout <SECS>` (#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
Expand Down
7 changes: 6 additions & 1 deletion tools/aimdb-cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <SECS>` (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`
Expand Down Expand Up @@ -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
Expand Down
28 changes: 14 additions & 14 deletions tools/aimdb-cli/src/commands/graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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?;

Expand All @@ -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?;

Expand All @@ -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?;

Expand All @@ -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?;
Expand Down
15 changes: 9 additions & 6 deletions tools/aimdb-cli/src/commands/instance.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand Down Expand Up @@ -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,
}
}
}
Expand Down Expand Up @@ -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 {
Expand Down
Loading