automation: ControlClient::is_usable tells a connection the server closed or sent an unasked line; a call checks it before sending and closes such a connection with nothing sent

This commit is contained in:
bflatastic
2026-11-22 08:53:43 +07:00
parent 3b0c8b780d
commit 89f96bcaa6
2 changed files with 55 additions and 3 deletions
+20 -3
View File
@@ -53,6 +53,18 @@ impl ControlClient {
self.broken
}
/// Whether a call can be sent now: false when the connection is broken, the server closed it,
/// or it holds bytes no call asked for (a server that says why it closes), as no reply to the
/// next call could be read from it. Every call checks this before it sends and, when false,
/// closes the connection and fails with nothing sent; a caller reconnects instead.
pub fn is_usable(&self) -> bool {
if self.broken || !self.reader.buffer().is_empty() || self.stream.set_nonblocking(true).is_err() {
return false;
}
let probe = self.stream.peek(&mut [0]);
self.stream.set_nonblocking(false).is_ok() && probe.is_err_and(|e| e.kind() == std::io::ErrorKind::WouldBlock)
}
/// Connect (read timeout [`CALL_TIMEOUT`]), send
/// `{"id": 1, "method": "auth", "params": {"token": token}}` and read one reply line; `Err` with
/// the reply's `error` text as `Refused` when it isn't `ok`, or the I/O error's message as `Transport`.
@@ -90,19 +102,24 @@ impl ControlClient {
}
fn exchange(&mut self, id: u64, method: &str, params: Value, cancelled: Option<&dyn Fn() -> bool>) -> Result<Value, String> {
if self.broken {
if !self.is_usable() {
self.close();
return Err("connection closed".into());
}
let result = self.round_trip(id, method, params, cancelled);
if matches!(result, Err(Failure::Io(_))) {
self.broken = true;
let _ = self.stream.shutdown(std::net::Shutdown::Both);
self.close();
}
result.map_err(|f| match f {
Failure::Io(e) | Failure::Reply(e) => e,
})
}
fn close(&mut self) {
self.broken = true;
let _ = self.stream.shutdown(std::net::Shutdown::Both);
}
fn round_trip(&mut self, id: u64, method: &str, params: Value, cancelled: Option<&dyn Fn() -> bool>) -> Result<Value, Failure> {
let io = |e: std::io::Error| Failure::Io(e.to_string());
writeln!(self.stream, "{}", json!({"id": id, "method": method, "params": params})).map_err(io)?;
+35
View File
@@ -71,3 +71,38 @@ fn a_cancelled_call_stops_waiting_and_closes_the_connection() {
server.join().unwrap();
assert_eq!(client.call("next", json!({})), Err("connection closed".to_string()), "the late reply answers nothing");
}
// A connection the server closed, or one holding a line no call asked for, is unusable: the next
// call sends nothing and fails, so the caller reconnects instead of reading the wrong answer.
#[trial]
fn an_unasked_line_makes_the_connection_unusable_before_sending() {
use std::io::{BufRead, Write};
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let (said, wait) = std::sync::mpsc::channel::<()>();
let server = std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
let mut reader = std::io::BufReader::new(stream.try_clone().unwrap());
let mut out = stream;
let mut line = String::new();
reader.read_line(&mut line).unwrap();
writeln!(out, "{}", json!({"id": 1, "ok": true})).unwrap();
wait.recv().unwrap();
writeln!(out, "{}", json!({"id": null, "ok": false, "error": "idle connection closed"})).unwrap();
out.flush().unwrap();
// The client's close shows as an end of input or, with the unread line, a reset.
line.clear();
reader.read_line(&mut line).ok().filter(|&read| read > 0).map(|_| line)
});
let mut client = ControlClient::connect(addr, TOKEN).unwrap();
assert!(client.is_usable(), "an idle connection with nothing pending is usable");
said.send(()).unwrap();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
while client.is_usable() && std::time::Instant::now() < deadline {
std::thread::sleep(std::time::Duration::from_millis(5));
}
assert!(!client.is_usable(), "the unasked line makes the connection unusable");
assert_eq!(client.call("next", json!({})), Err("connection closed".to_string()));
assert!(client.is_broken(), "the unusable connection is closed");
assert_eq!(server.join().unwrap(), None, "the call sent nothing");
}