From 32f3c071e3b4379c8e54e9c0023da412e3f5a421 Mon Sep 17 00:00:00 2001 From: Turker Mertkan Aytac Date: Tue, 24 Nov 2026 13:47:14 +0300 Subject: [PATCH] fix(ipc): serve IPC connections off the main loop with total deadlines (R-28, S-42) The main loop read and answered each IPC connection synchronously. The 5 s timeout applied per read call, and writes had none, so a client that sent a byte every few seconds, or never read its reply, held the current_thread loop: REST, /live, SOX, the watchdog kick and the sd_notify watchdog stopped, and with WatchdogSec=10 systemd restarted the service. A throwaway test on the old path: a 200 ms per-read timeout was held for 1055 ms by one byte per 150 ms. - ipc.rs: an accept task (100 ms backoff on error) and one task per connection; at most 4 at once, a fifth gets Error("busy"). Reading the frame and writing the reply have a 5 s total deadline each; queueing the command and getting the engine reply share one 10 s deadline. On a failure the client gets EngineResponse::Error. A partial length prefix is an error. Logs name the command (no field values) and are limited to one line per kind per 10 s with a suppressed count. - main.rs: only the command reaches the loop, through a bounded channel (4) and a oneshot; a command whose client already gave up is skipped and logged; Shutdown waits at most 1 s for its reply to be written. - dispatch.rs: handle_connection becomes run (command in, reply out). - sandstar-ipc: MAX_FRAME_SIZE is pub (same value). - sandstar-cli: 20 s read/write timeout, above the server deadlines. Behaviour: wire protocol unchanged. A command that cannot reach the engine within 10 s is now not run and the client is told so (before, it got no reply and the command ran later). Four slow local clients can keep the CLI busy for 5 s at a time; the service and REST are unaffected. Tests: gates.sh fmt, clippy, test (28 suites, 2921 passed, 0 failed), hal OK; 16 IPC unit tests (total vs per-read deadline, unread reply, full queue, abandoned command, written ack, oversized/garbage/partial frames, connection limit and permit release). E2E on Windows TCP IPC: 6 slow clients, REST /health 24/24 within 6 ms, slow ones closed at 5.0 s, CLI "busy" while full then OK, poll and shutdown answered. The unix path is not compiled on this machine; Linux CI covers it. docs: HARDCODED_LIMITS.md IPC rows updated. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QKRNiek8qYRoRt7dcrDDVC --- crates/sandstar-cli/src/client.rs | 15 +- crates/sandstar-ipc/src/protocol.rs | 2 +- crates/sandstar-server/src/dispatch.rs | 31 +- crates/sandstar-server/src/ipc.rs | 664 +++++++++++++++++++++---- crates/sandstar-server/src/main.rs | 87 ++-- docs/Progress/HARDCODED_LIMITS.md | 7 +- 6 files changed, 661 insertions(+), 145 deletions(-) diff --git a/crates/sandstar-cli/src/client.rs b/crates/sandstar-cli/src/client.rs index 25b21d7..ab8f488 100644 --- a/crates/sandstar-cli/src/client.rs +++ b/crates/sandstar-cli/src/client.rs @@ -4,6 +4,12 @@ use sandstar_ipc::protocol::{read_frame, write_frame}; use sandstar_ipc::types::{EngineCommand, EngineResponse}; use std::io; use std::net::TcpStream; +use std::time::Duration; + +/// Longest wait for the server, per read or write. Above the server's own +/// deadlines (5 s read, 10 s engine, 5 s write), so the server's error reply +/// arrives first; below it the CLI would give up on a busy but healthy engine. +const IO_TIMEOUT: Duration = Duration::from_secs(20); /// Send a command to the engine server and return the response. pub fn send_command(address: &str, cmd: &EngineCommand) -> io::Result { @@ -28,15 +34,22 @@ pub fn send_command(address: &str, cmd: &EngineCommand) -> io::Result io::Result { if !address.contains(':') { let stream = std::os::unix::net::UnixStream::connect(address)?; + stream.set_read_timeout(Some(IO_TIMEOUT))?; + stream.set_write_timeout(Some(IO_TIMEOUT))?; return Ok(ConnStream::Unix(stream)); } let stream = TcpStream::connect(address)?; + stream.set_read_timeout(Some(IO_TIMEOUT))?; + stream.set_write_timeout(Some(IO_TIMEOUT))?; Ok(ConnStream::Tcp(stream)) } #[cfg(not(unix))] fn connect(address: &str) -> io::Result { - TcpStream::connect(address) + let stream = TcpStream::connect(address)?; + stream.set_read_timeout(Some(IO_TIMEOUT))?; + stream.set_write_timeout(Some(IO_TIMEOUT))?; + Ok(stream) } // --- Platform-specific stream type --- diff --git a/crates/sandstar-ipc/src/protocol.rs b/crates/sandstar-ipc/src/protocol.rs index 2af7a2e..f66c98a 100644 --- a/crates/sandstar-ipc/src/protocol.rs +++ b/crates/sandstar-ipc/src/protocol.rs @@ -8,7 +8,7 @@ use serde::{de::DeserializeOwned, Serialize}; use std::io; /// Maximum frame size (1 MB). Prevents OOM from malformed length prefixes. -const MAX_FRAME_SIZE: u32 = 1_048_576; +pub const MAX_FRAME_SIZE: u32 = 1_048_576; /// Write a serializable value as a length-prefixed bincode frame. /// diff --git a/crates/sandstar-server/src/dispatch.rs b/crates/sandstar-server/src/dispatch.rs index 6ba6174..acf13d0 100644 --- a/crates/sandstar-server/src/dispatch.rs +++ b/crates/sandstar-server/src/dispatch.rs @@ -1,20 +1,19 @@ -//! Command dispatch: deserialize IPC commands, execute on engine, send response. +//! Command dispatch: run an IPC command on the engine (main loop side). +//! +//! The connection itself (framing, deadlines) lives in `crate::ipc` (R-28). -use std::io; use std::time::Instant; use sandstar_engine::{Engine, EngineValue}; use sandstar_hal::{HalDiagnostics, HalRead, HalWrite}; -use sandstar_ipc::protocol::{read_frame, write_frame}; use sandstar_ipc::types::*; use tracing::{debug, info, warn}; use crate::config::ServerConfig; use crate::history::HistoryStore; -use crate::ipc::Stream; use crate::reload; -/// Result of handling an IPC connection. +/// What the main loop must do after an IPC command. pub enum ConnectionResult { /// Normal command processed, continue accepting connections. Continue, @@ -24,19 +23,15 @@ pub enum ConnectionResult { PollNow, } -/// Handle a single IPC connection: read one command, dispatch, write response. -pub fn handle_connection( - mut stream: Stream, +/// Run one IPC command on the engine: what the main loop must do next, and +/// the reply for the client. +pub fn run( + cmd: EngineCommand, engine: &mut Engine, config: &ServerConfig, start_time: Instant, history_store: &HistoryStore, -) -> io::Result { - let cmd: EngineCommand = match read_frame(&mut stream)? { - Some(cmd) => cmd, - None => return Ok(ConnectionResult::Continue), // clean disconnect - }; - +) -> (ConnectionResult, EngineResponse) { debug!(?cmd, "received command"); crate::metrics::metrics() .ipc_requests @@ -47,10 +42,10 @@ pub fn handle_connection( EngineCommand::PollNow => ConnectionResult::PollNow, _ => ConnectionResult::Continue, }; - let response = execute(cmd, engine, config, start_time, history_store); - write_frame(&mut stream, &response)?; - - Ok(result) + ( + result, + execute(cmd, engine, config, start_time, history_store), + ) } /// Execute a command against the engine and produce a response. diff --git a/crates/sandstar-server/src/ipc.rs b/crates/sandstar-server/src/ipc.rs index 79f5911..4e0a7b6 100644 --- a/crates/sandstar-server/src/ipc.rs +++ b/crates/sandstar-server/src/ipc.rs @@ -2,10 +2,27 @@ //! //! On Unix: Unix domain sockets. //! On Windows: TCP on localhost (named pipes require winapi; TCP is simpler for dev). +//! +//! Connections are accepted and served on their own tasks, off the main loop +//! (R-28). A connection task reads one command frame, hands it to the main +//! loop over a channel, and writes the reply. Reading, getting the command to +//! and back from the engine, and writing each have a total deadline, so a slow +//! or stuck client never holds the engine, REST, SOX or the watchdog. On a +//! failure the client gets an `EngineResponse::Error` when it can still be +//! written. Wire format is unchanged: `[u32 LE length][bincode]`. use std::io; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; use std::time::Duration; +use sandstar_ipc::protocol::MAX_FRAME_SIZE; +use sandstar_ipc::types::{EngineCommand, EngineResponse}; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; +use tokio::sync::{mpsc, oneshot, Semaphore}; +use tokio::time::{timeout, timeout_at, Instant}; +use tracing::{error, warn}; + // --- Platform abstraction --- /// Opaque listener type. @@ -17,10 +34,89 @@ pub type Listener = tokio::net::TcpListener; /// Opaque stream type. #[cfg(unix)] -pub type Stream = std::os::unix::net::UnixStream; +pub type Stream = tokio::net::UnixStream; #[cfg(not(unix))] -pub type Stream = std::net::TcpStream; +pub type Stream = tokio::net::TcpStream; + +/// Total time to read one command frame, and again to write the reply. +pub const IO_TIMEOUT: Duration = Duration::from_secs(5); + +/// Time for the command to reach the engine and its reply to come back +/// (queue wait included); as `EngineHandle`'s 10 s. +pub const REPLY_TIMEOUT: Duration = Duration::from_secs(10); + +/// Connections served at the same time; more get a "busy" reply. +pub const MAX_CONNECTIONS: usize = 4; + +/// How long `Shutdown` waits for its reply to be written before stopping. +pub const SHUTDOWN_REPLY_WAIT: Duration = Duration::from_secs(1); + +/// Pause after a failed `accept` (e.g. out of file descriptors). +const ACCEPT_BACKOFF: Duration = Duration::from_millis(100); + +/// Time for a short error reply on a failure path. +const ERROR_REPLY_TIMEOUT: Duration = Duration::from_secs(1); + +/// At most one log line per kind of IPC failure in this period. +const LOG_EVERY: Duration = Duration::from_secs(10); + +/// One command for the main loop. +pub struct IpcRequest { + pub cmd: EngineCommand, + /// The reply goes back to the connection task. + pub reply: oneshot::Sender, + /// Fires once the reply is written, so `Shutdown` can wait for it. + pub written: oneshot::Receiver<()>, +} + +impl IpcRequest { + /// The client's task has given up (deadline passed): do not run it. + pub fn abandoned(&self) -> bool { + self.reply.is_closed() + } +} + +/// Variant name of a command, for logs (no field values). +pub fn command_name(cmd: &EngineCommand) -> String { + let debug = format!("{cmd:?}"); + debug + .split(|c: char| !c.is_alphanumeric()) + .next() + .unwrap_or_default() + .to_string() +} + +/// Lets one log line through per `LOG_EVERY`, counting the rest. +struct LogLimit { + last: Mutex>, + suppressed: AtomicU64, +} + +impl LogLimit { + const fn new() -> Self { + Self { + last: Mutex::new(None), + suppressed: AtomicU64::new(0), + } + } + + /// `Some(n)`: log now; `n` lines were suppressed since the last one. + fn check(&self) -> Option { + let now = std::time::Instant::now(); + let mut last = self.last.lock().unwrap_or_else(|p| p.into_inner()); + if last.is_some_and(|t| now.duration_since(t) < LOG_EVERY) { + self.suppressed.fetch_add(1, Ordering::Relaxed); + return None; + } + *last = Some(now); + Some(self.suppressed.swap(0, Ordering::Relaxed)) + } +} + +static BUSY_LOG: LogLimit = LogLimit::new(); +static CONN_ERROR_LOG: LogLimit = LogLimit::new(); +static ACCEPT_ERROR_LOG: LogLimit = LogLimit::new(); /// Create the IPC listener. pub async fn create_listener(path: &str) -> io::Result { @@ -44,30 +140,193 @@ pub async fn create_listener(path: &str) -> io::Result { } } -/// Accept one connection, returning a synchronous stream for frame I/O. +/// Accept one connection. +pub async fn accept(listener: &Listener) -> io::Result { + let (stream, _addr) = listener.accept().await?; + Ok(stream) +} + +/// Accept connections until the main loop is gone, each served on its own task. +pub fn spawn_accept_loop( + listener: Listener, + tx: mpsc::Sender, + slots: Arc, +) -> tokio::task::JoinHandle<()> { + tokio::spawn(async move { + while !tx.is_closed() { + match accept(&listener).await { + Ok(stream) => spawn_connection(stream, tx.clone(), slots.clone()), + Err(e) => { + if let Some(n) = ACCEPT_ERROR_LOG.check() { + error!(err = %e, suppressed = n, "failed to accept IPC connection"); + } + tokio::time::sleep(ACCEPT_BACKOFF).await; + } + } + } + }) +} + +/// Serve `stream` on its own task if a connection slot is free; otherwise +/// tell the client the server is busy. +pub fn spawn_connection(stream: Stream, tx: mpsc::Sender, slots: Arc) { + let Ok(permit) = slots.try_acquire_owned() else { + if let Some(n) = BUSY_LOG.check() { + warn!( + max = MAX_CONNECTIONS, + suppressed = n, + "IPC: too many connections, refusing" + ); + } + tokio::spawn(async move { + let mut stream = stream; + reply_error(&mut stream, "busy: too many IPC connections, try again").await; + }); + return; + }; + tokio::spawn(async move { + let _permit = permit; + if let Err(e) = serve(stream, &tx, IO_TIMEOUT, REPLY_TIMEOUT).await { + if let Some(n) = CONN_ERROR_LOG.check() { + warn!(err = %e, suppressed = n, "IPC connection failed"); + } + } + }); +} + +/// Read one command, pass it to the main loop, write the reply. /// -/// We accept via tokio (async) then convert to std (sync) for the -/// blocking bincode read/write in the single-threaded runtime. -pub async fn accept(listener: &Listener) -> io::Result<(Stream, Vec, Vec)> { - #[cfg(unix)] - { - let (stream, _addr) = listener.accept().await?; - let std_stream = stream.into_std()?; - std_stream.set_nonblocking(false)?; - // Prevent a hung client from blocking the event loop + watchdog. - std_stream.set_read_timeout(Some(Duration::from_secs(5)))?; - Ok((std_stream, Vec::new(), Vec::new())) +/// A clean disconnect before any byte is `Ok`. Every step that waits on the +/// client or the main loop has a deadline; errors name the command and say +/// whether it ran. +pub async fn serve( + mut stream: S, + tx: &mpsc::Sender, + io_timeout: Duration, + reply_timeout: Duration, +) -> io::Result<()> +where + S: AsyncRead + AsyncWrite + Unpin, +{ + let cmd: EngineCommand = match timeout(io_timeout, read_frame(&mut stream)).await { + Err(_) => return Err(timed_out("client too slow sending the command")), + Ok(Err(e)) => { + if e.kind() == io::ErrorKind::InvalidData { + reply_error(&mut stream, &format!("bad command frame: {e}")).await; + } + return Err(e); + } + Ok(Ok(None)) => return Ok(()), + Ok(Ok(Some(cmd))) => cmd, + }; + let name = command_name(&cmd); + + // One deadline for queueing the command and getting its reply. + let deadline = Instant::now() + reply_timeout; + let (reply_tx, reply_rx) = oneshot::channel(); + let (written_tx, written_rx) = oneshot::channel(); + let request = IpcRequest { + cmd, + reply: reply_tx, + written: written_rx, + }; + match timeout_at(deadline, tx.send(request)).await { + Err(_) => { + reply_error(&mut stream, "engine busy: command not queued, not run").await; + return Err(timed_out(&format!("{name}: engine queue full, not run"))); + } + Ok(Err(_)) => { + reply_error(&mut stream, "server is stopping: command not run").await; + return Err(broken(&format!("{name}: engine loop has stopped, not run"))); + } + Ok(Ok(())) => {} } - #[cfg(not(unix))] - { - let (stream, _addr) = listener.accept().await?; - let std_stream = stream.into_std()?; - std_stream.set_nonblocking(false)?; - // Prevent a hung client from blocking the event loop + watchdog. - std_stream.set_read_timeout(Some(Duration::from_secs(5)))?; - Ok((std_stream, Vec::new(), Vec::new())) + // On timeout `reply_rx` is dropped here, so the main loop skips the + // command if it has not started it yet. + let response = match timeout_at(deadline, reply_rx).await { + Err(_) => { + reply_error( + &mut stream, + "timed out waiting for the engine: command not run", + ) + .await; + return Err(timed_out(&format!("{name}: engine did not answer in time"))); + } + Ok(Err(_)) => { + reply_error(&mut stream, "engine did not run the command").await; + return Err(broken(&format!("{name}: engine loop dropped the command"))); + } + Ok(Ok(r)) => r, + }; + + match timeout(io_timeout, write_frame(&mut stream, &response)).await { + Err(_) => { + return Err(timed_out(&format!( + "{name} ran, client too slow reading the reply" + ))) + } + Ok(Err(e)) => { + return Err(io::Error::new( + e.kind(), + format!("{name} ran, reply not delivered: {e}"), + )) + } + Ok(Ok(())) => {} } + // Nobody waits unless the command was Shutdown. + let _ = written_tx.send(()); + Ok(()) +} + +/// Best effort: the connection is failing anyway. +async fn reply_error(stream: &mut S, msg: &str) { + let response = EngineResponse::Error(msg.to_string()); + let _ = timeout(ERROR_REPLY_TIMEOUT, write_frame(stream, &response)).await; +} + +fn timed_out(what: &str) -> io::Error { + io::Error::new(io::ErrorKind::TimedOut, what.to_string()) +} + +fn broken(what: &str) -> io::Error { + io::Error::new(io::ErrorKind::BrokenPipe, what.to_string()) +} + +/// Async version of `sandstar_ipc::protocol::read_frame`. `None` only when +/// the client closed before sending anything; a partial frame is an error. +async fn read_frame(reader: &mut R) -> io::Result> { + let mut len_buf = [0u8; 4]; + if reader.read(&mut len_buf[..1]).await? == 0 { + return Ok(None); + } + reader.read_exact(&mut len_buf[1..]).await?; + let len = u32::from_le_bytes(len_buf); + if len > MAX_FRAME_SIZE { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("frame too large: {len} bytes (max {MAX_FRAME_SIZE})"), + )); + } + let mut payload = vec![0u8; len as usize]; + reader.read_exact(&mut payload).await?; + bincode::deserialize(&payload) + .map(Some) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) +} + +/// Async version of `sandstar_ipc::protocol::write_frame`. +async fn write_frame( + writer: &mut W, + value: &EngineResponse, +) -> io::Result<()> { + let payload = + bincode::serialize(value).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; + let len = u32::try_from(payload.len()) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "reply too large"))?; + writer.write_all(&len.to_le_bytes()).await?; + writer.write_all(&payload).await?; + writer.flush().await } /// Clean up the socket file on shutdown (Unix only). @@ -86,6 +345,7 @@ pub fn cleanup(path: &str) { #[cfg(test)] mod tests { use super::*; + use tokio::io::duplex; // Tests run against the platform transport: a Unix socket file on Unix // (the production path on the device), TCP on localhost elsewhere. @@ -111,8 +371,8 @@ mod tests { (listener, addr) } - fn connect(target: &Target) -> Stream { - Stream::connect(target).unwrap() + async fn connect(target: &Target) -> Stream { + Stream::connect(target).await.unwrap() } fn cleanup_test(target: &Target) { @@ -122,6 +382,39 @@ mod tests { let _ = target; } + fn frame(cmd: &EngineCommand) -> Vec { + let mut buf = Vec::new(); + sandstar_ipc::protocol::write_frame(&mut buf, cmd).unwrap(); + buf + } + + async fn read_reply(r: &mut R) -> EngineResponse { + let mut len = [0u8; 4]; + r.read_exact(&mut len).await.unwrap(); + let mut body = vec![0u8; u32::from_le_bytes(len) as usize]; + r.read_exact(&mut body).await.unwrap(); + bincode::deserialize(&body).unwrap() + } + + fn error_text(r: &EngineResponse) -> &str { + match r { + EngineResponse::Error(s) => s, + _ => panic!("expected an error reply"), + } + } + + /// Stand-in for the main loop: answers every live command with `Ok`. + fn answer_all(mut rx: mpsc::Receiver) -> tokio::task::JoinHandle { + tokio::spawn(async move { + let mut n = 0; + while let Some(req) = rx.recv().await { + n += 1; + let _ = req.reply.send(EngineResponse::Ok); + } + n + }) + } + #[tokio::test] async fn test_create_listener() { let (_listener, target) = bind_test("create").await; @@ -136,26 +429,11 @@ mod tests { cleanup_test(&target); } - #[tokio::test] - async fn test_accept_sets_read_timeout() { - let (listener, target) = bind_test("timeout").await; - - // Connect a client - let _client = connect(&target); - - // Accept it on the server side - let (stream, _, _) = accept(&listener).await.unwrap(); - let timeout = stream.read_timeout().unwrap(); - assert_eq!(timeout, Some(Duration::from_secs(5))); - cleanup_test(&target); - } - #[test] fn test_cleanup_idempotent() { // Calling cleanup on a non-existent path should not panic cleanup("127.0.0.1:0"); cleanup("/tmp/nonexistent-sandstar-test-socket"); - // If we get here without panicking, the test passes } #[cfg(unix)] @@ -167,66 +445,280 @@ mod tests { assert!(!target.exists()); } - #[tokio::test] - async fn test_round_trip_frame() { - use sandstar_ipc::protocol::{read_frame, write_frame}; - use sandstar_ipc::types::{EngineCommand, EngineResponse}; + #[test] + fn test_command_name_has_no_field_values() { + let cmd = EngineCommand::ReadChannel { channel: 1113 }; + assert_eq!(command_name(&cmd), "ReadChannel"); + assert_eq!(command_name(&EngineCommand::Status), "Status"); + } + #[tokio::test] + async fn test_round_trip_over_platform_socket() { let (listener, target) = bind_test("roundtrip").await; - let client_target = target.clone(); + let (tx, rx) = mpsc::channel(MAX_CONNECTIONS); + let main_loop = answer_all(rx); + let slots = Arc::new(Semaphore::new(MAX_CONNECTIONS)); + let accept_loop = spawn_accept_loop(listener, tx, slots); + + let mut c = connect(&target).await; + c.write_all(&frame(&EngineCommand::Status)).await.unwrap(); + assert!(matches!(read_reply(&mut c).await, EngineResponse::Ok)); + accept_loop.abort(); + let _ = accept_loop.await; + assert_eq!(main_loop.await.unwrap(), 1); + cleanup_test(&target); + } - // Client sends a command - let handle = std::thread::spawn(move || { - let mut client = connect(&client_target); - let cmd = EngineCommand::Status; - write_frame(&mut client, &cmd).unwrap(); + #[tokio::test(start_paused = true)] + async fn test_read_deadline_is_total_not_per_read() { + // One byte every 1 s: every single read is quick, the whole frame + // would finish at ~7 s. A per-read 5 s limit would let it through. + let (mut client, server) = duplex(64); + let (tx, mut rx) = mpsc::channel(1); + let start = Instant::now(); + let task = tokio::spawn(async move { serve(server, &tx, IO_TIMEOUT, REPLY_TIMEOUT).await }); + for b in frame(&EngineCommand::Status) { + if client.write_all(&[b]).await.is_err() { + break; + } + tokio::time::sleep(Duration::from_secs(1)).await; + } + let err = task.await.unwrap().unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::TimedOut); + let took = Instant::now() - start; + assert!( + took >= IO_TIMEOUT && took < IO_TIMEOUT + Duration::from_secs(2), + "{took:?}" + ); + assert!( + rx.try_recv().is_err(), + "an unfinished frame must not reach the engine" + ); + } - // Read back the response - let resp: EngineResponse = read_frame(&mut client).unwrap().unwrap(); - resp - }); + #[tokio::test(start_paused = true)] + async fn test_client_that_never_reads_the_reply_times_out() { + // A tiny pipe the client never drains: the reply cannot be written. + let (mut client, server) = duplex(8); + let (tx, mut rx) = mpsc::channel(1); + let task = tokio::spawn(async move { serve(server, &tx, IO_TIMEOUT, REPLY_TIMEOUT).await }); + client + .write_all(&frame(&EngineCommand::ListChannels)) + .await + .unwrap(); + let req = rx.recv().await.unwrap(); + let mut written = req.written; + let channels = (0..200) + .map(|i| sandstar_ipc::types::ChannelInfo { + id: i, + label: format!("channel {i}"), + channel_type: "Analog".into(), + direction: "In".into(), + enabled: true, + status: "Ok".into(), + raw: 0.0, + cur: 0.0, + }) + .collect(); + let _ = req.reply.send(EngineResponse::Channels(channels)); + let err = task.await.unwrap().unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::TimedOut); + assert!(err.to_string().contains("ListChannels ran"), "{err}"); + assert!(written.try_recv().is_err(), "no ack for an unwritten reply"); + let _ = client; // kept open, never read + } - // Server accepts and echoes back a response - let (mut stream, _, _) = accept(&listener).await.unwrap(); - let cmd: EngineCommand = sandstar_ipc::protocol::read_frame(&mut stream) - .unwrap() + #[tokio::test] + async fn test_written_ack_follows_the_reply() { + let (mut client, server) = duplex(1024); + let (tx, mut rx) = mpsc::channel(1); + let task = tokio::spawn(async move { serve(server, &tx, IO_TIMEOUT, REPLY_TIMEOUT).await }); + client + .write_all(&frame(&EngineCommand::Shutdown)) + .await .unwrap(); - assert!(matches!(cmd, EngineCommand::Status)); + let req = rx.recv().await.unwrap(); + let _ = req.reply.send(EngineResponse::Ok); + req.written.await.expect("ack after the reply is written"); + assert!(matches!(read_reply(&mut client).await, EngineResponse::Ok)); + task.await.unwrap().unwrap(); + } - let resp = EngineResponse::Ok; - sandstar_ipc::protocol::write_frame(&mut stream, &resp).unwrap(); + #[tokio::test(start_paused = true)] + async fn test_stuck_engine_times_out_and_the_command_is_abandoned() { + let (mut client, server) = duplex(1024); + let (tx, mut rx) = mpsc::channel(1); + let task = tokio::spawn(async move { serve(server, &tx, IO_TIMEOUT, REPLY_TIMEOUT).await }); + client + .write_all(&frame(&EngineCommand::Status)) + .await + .unwrap(); + let held = rx.recv().await.unwrap(); // never answered + assert!(!held.abandoned()); + let err = task.await.unwrap().unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::TimedOut); + assert!( + held.abandoned(), + "the main loop must see the client gave up" + ); + assert!(error_text(&read_reply(&mut client).await).contains("not run")); + } - let client_resp = handle.join().unwrap(); - assert!(matches!(client_resp, EngineResponse::Ok)); - cleanup_test(&target); + #[tokio::test(start_paused = true)] + async fn test_full_queue_times_out_without_queueing() { + // The queue is full and nothing drains it (engine in a poll). + let (tx, mut rx) = mpsc::channel(1); + let (blocker, _) = oneshot::channel(); + let (_, blocker_written) = oneshot::channel(); + tx.send(IpcRequest { + cmd: EngineCommand::Status, + reply: blocker, + written: blocker_written, + }) + .await + .unwrap(); + let (mut client, server) = duplex(1024); + client + .write_all(&frame(&EngineCommand::Status)) + .await + .unwrap(); + let err = serve(server, &tx, IO_TIMEOUT, REPLY_TIMEOUT) + .await + .unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::TimedOut); + assert!(err.to_string().contains("not run"), "{err}"); + assert!(error_text(&read_reply(&mut client).await).contains("not queued")); + rx.recv().await.unwrap(); + assert!(rx.try_recv().is_err(), "only the blocker was queued"); } #[tokio::test] - async fn test_concurrent_connections() { - let (listener, target) = bind_test("concurrent").await; - - // Three sequential clients connect and exchange a frame - for i in 0..3 { - let client_target = target.clone(); - let handle = std::thread::spawn(move || { - let mut client = connect(&client_target); - let cmd = sandstar_ipc::types::EngineCommand::ListChannels; - sandstar_ipc::protocol::write_frame(&mut client, &cmd).unwrap(); - }); - - let (mut stream, _, _) = accept(&listener).await.unwrap(); - let cmd: sandstar_ipc::types::EngineCommand = - sandstar_ipc::protocol::read_frame(&mut stream) - .unwrap() - .unwrap(); - assert!( - matches!(cmd, sandstar_ipc::types::EngineCommand::ListChannels), - "client {} should send ListChannels", - i - ); + async fn test_oversized_length_is_refused() { + let (mut client, server) = duplex(256); + let (tx, mut rx) = mpsc::channel(1); + client + .write_all(&(MAX_FRAME_SIZE + 1).to_le_bytes()) + .await + .unwrap(); + let err = serve(server, &tx, IO_TIMEOUT, REPLY_TIMEOUT) + .await + .unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidData); + assert!(rx.try_recv().is_err()); + assert!(error_text(&read_reply(&mut client).await).contains("bad command frame")); + } + + #[tokio::test] + async fn test_garbage_payload_is_refused() { + let (mut client, server) = duplex(64); + let (tx, mut rx) = mpsc::channel(1); + client + .write_all(&[3, 0, 0, 0, 0xff, 0xff, 0xff]) + .await + .unwrap(); + let err = serve(server, &tx, IO_TIMEOUT, REPLY_TIMEOUT) + .await + .unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidData); + assert!(rx.try_recv().is_err()); + } + + #[tokio::test] + async fn test_empty_connection_is_quiet() { + let (client, server) = duplex(64); + drop(client); + let (tx, mut rx) = mpsc::channel(1); + serve(server, &tx, IO_TIMEOUT, REPLY_TIMEOUT).await.unwrap(); + assert!(rx.try_recv().is_err()); + } + + #[tokio::test] + async fn test_partial_length_prefix_is_an_error() { + let (mut client, server) = duplex(64); + client.write_all(&[10, 0]).await.unwrap(); + drop(client); + let (tx, _rx) = mpsc::channel(1); + let err = serve(server, &tx, IO_TIMEOUT, REPLY_TIMEOUT) + .await + .unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof); + } + + #[tokio::test] + async fn test_short_payload_is_an_error() { + // Length says 10, two bytes arrive, then the client hangs up. + let (mut client, server) = duplex(64); + client.write_all(&[10, 0, 0, 0, 1, 2]).await.unwrap(); + drop(client); + let (tx, _rx) = mpsc::channel(1); + let err = serve(server, &tx, IO_TIMEOUT, REPLY_TIMEOUT) + .await + .unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof); + } - handle.join().unwrap(); + #[tokio::test] + async fn test_connections_over_the_limit_get_busy_and_slots_come_back() { + let (listener, target) = bind_test("limit").await; + let (tx, mut rx) = mpsc::channel(MAX_CONNECTIONS); + let slots = Arc::new(Semaphore::new(MAX_CONNECTIONS)); + let mut idle = Vec::new(); + for _ in 0..MAX_CONNECTIONS { + idle.push(connect(&target).await); + let stream = accept(&listener).await.unwrap(); + spawn_connection(stream, tx.clone(), slots.clone()); } + tokio::task::yield_now().await; + assert_eq!(slots.available_permits(), 0); + + let mut extra = connect(&target).await; + let stream = accept(&listener).await.unwrap(); + spawn_connection(stream, tx.clone(), slots.clone()); + let reply = tokio::time::timeout(Duration::from_secs(2), read_reply(&mut extra)) + .await + .expect("refused at once"); + assert!(error_text(&reply).contains("busy")); + + // Idle clients hang up: every slot is released. + drop(idle); + tokio::time::timeout(Duration::from_secs(2), async { + while slots.available_permits() < MAX_CONNECTIONS { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("permits released"); + assert!(rx.try_recv().is_err()); cleanup_test(&target); } + + #[tokio::test] + async fn test_a_slow_client_does_not_hold_another() { + let (tx, rx) = mpsc::channel(MAX_CONNECTIONS); + let main_loop = answer_all(rx); + // A client that sent half a length prefix and went quiet. + let (mut slow, slow_server) = duplex(64); + slow.write_all(&[1, 0]).await.unwrap(); + let slow_task = tokio::spawn({ + let tx = tx.clone(); + async move { serve(slow_server, &tx, IO_TIMEOUT, REPLY_TIMEOUT).await } + }); + // A normal client is answered while the slow one waits. + let (mut fast, fast_server) = duplex(1024); + fast.write_all(&frame(&EngineCommand::Status)) + .await + .unwrap(); + tokio::time::timeout( + Duration::from_secs(1), + serve(fast_server, &tx, IO_TIMEOUT, REPLY_TIMEOUT), + ) + .await + .expect("served without waiting for the slow client") + .unwrap(); + assert!(matches!(read_reply(&mut fast).await, EngineResponse::Ok)); + slow_task.abort(); + drop(tx); + drop(slow); + let _ = main_loop.await; + } } diff --git a/crates/sandstar-server/src/main.rs b/crates/sandstar-server/src/main.rs index 0be9514..9f548c6 100644 --- a/crates/sandstar-server/src/main.rs +++ b/crates/sandstar-server/src/main.rs @@ -680,6 +680,11 @@ async fn main() -> Result<(), Box> { let mut shutdown = pin!(tokio::signal::ctrl_c()); let mut hup = signal::HupSignal::new()?; let mut ipc_shutdown = false; + // IPC connections are served on their own tasks; only the command reaches + // this loop (R-28). + let (ipc_tx, mut ipc_rx) = mpsc::channel::(ipc::MAX_CONNECTIONS); + let ipc_slots = Arc::new(tokio::sync::Semaphore::new(ipc::MAX_CONNECTIONS)); + let _ipc_accept = ipc::spawn_accept_loop(listener, ipc_tx, ipc_slots); // 12. Main event loop info!("engine running — press Ctrl+C to stop"); @@ -918,47 +923,53 @@ async fn main() -> Result<(), Box> { } } - // --- Incoming IPC connection (only when engine is available) --- - result = ipc::accept(&listener), if engine.is_some() => { - match result { - Ok((stream, _read_buf, _write_buf)) => { - let conn_result = dispatch::handle_connection( - stream, - engine.as_mut().expect("select! guard ensures engine.is_some()"), - &config, - start_time, - &history_store, - ); - match conn_result { - Ok(dispatch::ConnectionResult::Shutdown) => { - info!("shutdown requested via IPC"); - ipc_shutdown = true; - break; - } - Ok(dispatch::ConnectionResult::PollNow) => { - if !poll_in_progress { - let mut eng = engine.take().expect("select! guard ensures engine.is_some()"); - let mut ctrl = control_runner.take().unwrap_or_default(); - poll_in_progress = true; - let tx = poll_result_tx.clone(); - tokio::task::spawn_blocking(move || { - let poll_start = Instant::now(); - let notifications = eng.poll_update(); - ctrl.execute(&mut eng, Instant::now()); - let elapsed = poll_start.elapsed(); - let _ = tx.blocking_send((eng, ctrl, notifications, elapsed)); - }); - } - } - Ok(dispatch::ConnectionResult::Continue) => {} - Err(e) => { - error!(err = %e, "IPC connection error"); - } + // --- IPC command (only when engine is available) --- + Some(req) = ipc_rx.recv(), if engine.is_some() => { + let name = ipc::command_name(&req.cmd); + if req.abandoned() { + // The client was told "not run" (deadline passed in the queue). + warn!(cmd = %name, "IPC: client gave up while the command was queued; not run"); + continue; + } + let (conn_result, response) = dispatch::run( + req.cmd, + engine.as_mut().expect("select! guard ensures engine.is_some()"), + &config, + start_time, + &history_store, + ); + if req.reply.send(response).is_err() { + warn!(cmd = %name, "IPC: command ran, but the client gave up before the reply"); + } + match conn_result { + dispatch::ConnectionResult::Shutdown => { + info!("shutdown requested via IPC"); + // Let the reply reach the client before the runtime goes. + if !matches!( + tokio::time::timeout(ipc::SHUTDOWN_REPLY_WAIT, req.written).await, + Ok(Ok(())) + ) { + warn!("IPC: shutdown reply not confirmed as written"); } + ipc_shutdown = true; + break; } - Err(e) => { - error!(err = %e, "failed to accept IPC connection"); + dispatch::ConnectionResult::PollNow => { + if !poll_in_progress { + let mut eng = engine.take().expect("select! guard ensures engine.is_some()"); + let mut ctrl = control_runner.take().unwrap_or_default(); + poll_in_progress = true; + let tx = poll_result_tx.clone(); + tokio::task::spawn_blocking(move || { + let poll_start = Instant::now(); + let notifications = eng.poll_update(); + ctrl.execute(&mut eng, Instant::now()); + let elapsed = poll_start.elapsed(); + let _ = tx.blocking_send((eng, ctrl, notifications, elapsed)); + }); + } } + dispatch::ConnectionResult::Continue => {} } } diff --git a/docs/Progress/HARDCODED_LIMITS.md b/docs/Progress/HARDCODED_LIMITS.md index ded0e03..8cc56a3 100644 --- a/docs/Progress/HARDCODED_LIMITS.md +++ b/docs/Progress/HARDCODED_LIMITS.md @@ -132,7 +132,12 @@ Audited: 2026-03-10 | Constant | Value | File | Line | Recommendation | |----------|-------|------|------|----------------| | `MAX_FRAME_SIZE` | 1,048,576 (1MB) | `sandstar-ipc/src/protocol.rs` | 11 | **Document** — max IPC message size. Prevents unbounded allocation. | -| IPC read timeout | 5s | `sandstar-server/src/ipc.rs` | 58,68 | **Document** — prevents blocking IPC reads indefinitely. | +| IPC `IO_TIMEOUT` | 5s | `sandstar-server/src/ipc.rs` | 43 | **Document** — total time to read one command frame, and again to write the reply. Connections are served on their own tasks, never in the main loop (R-28, S-42). | +| IPC `REPLY_TIMEOUT` | 10s | `sandstar-server/src/ipc.rs` | 47 | **Document** — one deadline for queueing the command and getting the engine's reply. On expiry the client gets `Error(...not run)`; the main loop skips a command whose client gave up (S-42). | +| IPC `MAX_CONNECTIONS` | 4 | `sandstar-server/src/ipc.rs` | 50 | **Document** — IPC connections served at once, also the IPC command channel capacity. A fifth gets `Error("busy...")` (S-42). | +| IPC `SHUTDOWN_REPLY_WAIT` | 1s | `sandstar-server/src/ipc.rs` | 53 | **Keep** — `Shutdown` waits this long for its reply to be written; kept short for systemd `WatchdogSec=10` (S-42). | +| IPC `ACCEPT_BACKOFF` / `ERROR_REPLY_TIMEOUT` / `LOG_EVERY` | 100ms / 1s / 10s | `sandstar-server/src/ipc.rs` | 56-62 | **Keep** — pause after a failed `accept`; time for a failure reply; one IPC failure log line per kind per period, with a suppressed count (S-42). | +| CLI `IO_TIMEOUT` | 20s | `sandstar-cli/src/client.rs` | 12 | **Keep** — `sandstar-cli` read/write timeout; above the server's own deadlines so its error reply arrives first (S-42). | | `ENGINE_REPLY_TIMEOUT` | 10s | `sandstar-server/src/rest/mod.rs` | 146 | **Document** — max wait for an `EngineHandle` command (send + reply). On timeout the caller gets `engine timeout` (REST: 503); a state-changing command may still run later (R-28, S-20). | | Engine timeout warn interval | 60s | `sandstar-server/src/rest/mod.rs` | 160 | **Keep** — first timeout per 60 s logged at `warn`, the rest at `debug`. | | `HEALTH_ENGINE_TIMEOUT` | 2s | `sandstar-server/src/rest/handlers.rs` | 369 | **Document** — `/health` waits at most this long for the engine; otherwise 503 with `healthy:false` (R-28, S-21). |