diff --git a/crates/rmcp/src/transport.rs b/crates/rmcp/src/transport.rs index 9ce7b1bb6..0e68f5215 100644 --- a/crates/rmcp/src/transport.rs +++ b/crates/rmcp/src/transport.rs @@ -73,6 +73,26 @@ use crate::service::{RxJsonRpcMessage, ServiceRole, TxJsonRpcMessage}; pub mod sink_stream; +/// How long a transport's `close` waits for the rest of a message that a dropped `send` left +/// buffered (best effort: a peer that is not reading within this time still gets a partial +/// message). It also delays closing the output, e.g. a child process's stdin, by up to this long +/// when bytes are left. +pub(crate) const CLOSE_FLUSH_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(500); + +/// Flushes `sink` before the transport closes, bounded by [`CLOSE_FLUSH_TIMEOUT`]. A send whose +/// future was dropped during its flush (the service loop abandons the progress write of a request +/// the peer cancelled) may leave the message buffered in the sink; this finishes it, so that the +/// peer does not get a truncated or missing message. A write error or the timeout is ignored. The +/// bound covers the flush only: the caller holds the sink, so a send future that is still alive and +/// holds the sink's lock delays `close` until it ends or is dropped. +pub(crate) async fn flush_before_close(sink: &mut S) +where + S: futures::Sink + Unpin, +{ + use futures::SinkExt; + let _ = tokio::time::timeout(CLOSE_FLUSH_TIMEOUT, SinkExt::::flush(sink)).await; +} + #[cfg(feature = "transport-async-rw")] pub mod async_rw; diff --git a/crates/rmcp/src/transport/async_rw.rs b/crates/rmcp/src/transport/async_rw.rs index da2900008..a106082ef 100644 --- a/crates/rmcp/src/transport/async_rw.rs +++ b/crates/rmcp/src/transport/async_rw.rs @@ -51,11 +51,6 @@ where pub type TransportWriter = FramedWrite>>; -/// How long [`AsyncRwTransport`]'s `close` waits for the rest of an abandoned frame to be written -/// (best effort: a peer that is not reading within this time still gets a partial line). It also -/// delays closing the output, e.g. a child process's stdin, by up to this long when bytes are left. -const CLOSE_FLUSH_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(500); - /// Default cap on the size of a single incoming line (one JSON-RPC message) for /// [`AsyncRwTransport`]. /// @@ -801,7 +796,7 @@ where // stopped reading cannot hold the shutdown, and a write error or the timeout still leaves // the line partial. if let Some(mut framed) = write.take() { - let _ = tokio::time::timeout(CLOSE_FLUSH_TIMEOUT, framed.flush()).await; + super::flush_before_close::, _>(&mut framed).await; } Ok(()) } diff --git a/crates/rmcp/src/transport/sink_stream.rs b/crates/rmcp/src/transport/sink_stream.rs index 6286b53b3..8bf61c6a5 100644 --- a/crates/rmcp/src/transport/sink_stream.rs +++ b/crates/rmcp/src/transport/sink_stream.rs @@ -46,6 +46,15 @@ where } async fn close(&mut self) -> Result<(), Self::Error> { + // `send` is `SinkExt::send`, which leaves its message buffered in the sink if its future + // is dropped before the flush completes (the service loop abandons the progress write of + // a request the peer cancelled). Flush it before closing, so that the peer does not get a + // truncated or missing message. Best effort: once the lock is held, the flush is bounded + // by CLOSE_FLUSH_TIMEOUT, as in `AsyncRwTransport::close` (a send future that is still + // alive holds the lock until it ends or is dropped). The sink itself is not closed, as + // before. + let mut write = self.sink.lock().await; + super::flush_before_close::, _>(&mut *write).await; Ok(()) } } diff --git a/crates/rmcp/tests/test_sink_stream_flush.rs b/crates/rmcp/tests/test_sink_stream_flush.rs new file mode 100644 index 000000000..4a58a392c --- /dev/null +++ b/crates/rmcp/tests/test_sink_stream_flush.rs @@ -0,0 +1,497 @@ +//! `SinkStreamTransport::close` finishes a message that a dropped `send` left in the sink +//! (follow-up to #1558, which did this for `AsyncRwTransport`). +//! +//! `SinkStreamTransport::send` is `SinkExt::send`: `poll_ready`, `start_send`, `poll_flush`. If the +//! future is dropped during the flush (the service loop abandons the progress write of a request +//! the peer cancelled), the message has been accepted by the sink and stays there. Nothing else is +//! written for the session; the client closes its input, the server shuts down, and the peer must +//! get the message whole: neither truncated (a byte sink) nor missing (a sink that holds its items +//! until flushed). The close's flush is bounded, so a peer that stopped reading cannot hold the +//! shutdown. +#![cfg(feature = "server")] + +use std::{ + pin::Pin, + sync::{Arc, Mutex}, + task::{Context, Poll, Waker}, + time::Duration, +}; + +use futures::{Sink, StreamExt, stream::BoxStream}; +use rmcp::{ + ErrorData as McpError, RoleServer, ServerHandler, + model::{ + CallToolRequestParams, CallToolResponse, CallToolResult, CancelledNotificationParam, + ClientCapabilities, ClientJsonRpcMessage, ContentBlock, Implementation, + InitializeRequestParams, ProgressNotificationParam, ProtocolVersion, ServerCapabilities, + ServerConfig, ServerJsonRpcMessage, + }, + service::{NotificationContext, RequestContext, serve_directly}, + transport::{Transport, async_rw::JsonRpcMessageCodec, sink_stream::SinkStreamTransport}, +}; +use serde_json::{Value, json}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt, DuplexStream}, + sync::mpsc, +}; +use tokio_util::codec::{FramedRead, FramedWrite}; + +const WAIT: Duration = Duration::from_secs(10); + +/// Emits one progress notification, then waits for the cancellation and returns. +#[derive(Clone)] +struct Server { + cancelled: mpsc::UnboundedSender<()>, +} + +impl ServerHandler for Server { + fn get_info(&self) -> ServerConfig { + ServerConfig::new(ServerCapabilities::builder().enable_tools().build()) + } + + async fn call_tool( + &self, + _request: CallToolRequestParams, + context: RequestContext, + ) -> Result { + let token = context.meta.get_progress_token().expect("progress token"); + let _ = context + .peer + .notify_progress( + ProgressNotificationParam::new(token, 1.0) + .with_message("a progress message longer than the sixty-four byte pipe"), + ) + .await; + context.ct.cancelled().await; + Ok(CallToolResult::success(vec![ContentBlock::text("done")]).into()) + } + + async fn on_cancelled( + &self, + _notification: CancelledNotificationParam, + _context: NotificationContext, + ) { + let _ = self.cancelled.send(()); + } +} + +/// A sink that holds every accepted message, writing nothing in `start_send`, until it is +/// released; its `poll_flush` is pending until then, and afterwards writes the held messages (as +/// JSON text, one per message) to `out`. +#[derive(Clone, Default)] +struct Hold { + state: Arc>, +} + +#[derive(Default)] +struct HoldState { + held: Vec, + released: bool, + waker: Option, + out: Vec, +} + +impl Hold { + /// The peer starts reading: a pending or later flush writes the held messages. + fn release(&self) { + let mut s = self.state.lock().unwrap(); + s.released = true; + if let Some(w) = s.waker.take() { + w.wake(); + } + } + + fn out(&self) -> Vec { + self.state.lock().unwrap().out.clone() + } +} + +impl Sink for Hold { + type Error = std::io::Error; + + fn poll_ready(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + + fn start_send(self: Pin<&mut Self>, item: ServerJsonRpcMessage) -> Result<(), Self::Error> { + self.state.lock().unwrap().held.push(item); + Ok(()) + } + + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let mut s = self.state.lock().unwrap(); + if s.held.is_empty() { + return Poll::Ready(Ok(())); + } + if !s.released { + s.waker = Some(cx.waker().clone()); + return Poll::Pending; + } + let held = std::mem::take(&mut s.held); + s.out + .extend(held.iter().map(|m| serde_json::to_string(m).unwrap())); + Poll::Ready(Ok(())) + } + + fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.poll_flush(cx) + } +} + +/// The transport under test, reporting (in order) when the first poll of the progress send returns +/// `Pending` (`progress_pending`), the end of the input (`"eof"`), the drop of the unfinished +/// progress send future (`"progress dropped"`) and the start of `close` (`"close"`). +struct Latched { + inner: T, + progress_pending: mpsc::UnboundedSender<()>, + events: mpsc::UnboundedSender<&'static str>, +} + +/// Reports `"progress dropped"` when dropped before `done` is set. +struct DropGuard { + done: bool, + events: mpsc::UnboundedSender<&'static str>, +} + +impl Drop for DropGuard { + fn drop(&mut self) { + if !self.done { + let _ = self.events.send("progress dropped"); + } + } +} + +impl Transport for Latched +where + T: Transport + Send, +{ + type Error = T::Error; + + fn send( + &mut self, + item: ServerJsonRpcMessage, + ) -> impl Future> + Send + 'static { + let value = serde_json::to_value(&item).expect("serializable message"); + let progress = value["method"] == "notifications/progress"; + let mut latch = progress.then(|| self.progress_pending.clone()); + let mut guard = progress.then(|| DropGuard { + done: false, + events: self.events.clone(), + }); + let mut send = Box::pin(self.inner.send(item)); + std::future::poll_fn(move |cx| { + let poll = send.as_mut().poll(cx); + if let Some(latch) = latch.take() + && poll.is_pending() + { + let _ = latch.send(()); + } + if poll.is_ready() + && let Some(guard) = guard.as_mut() + { + guard.done = true; + } + poll + }) + } + + fn receive(&mut self) -> impl Future> { + let events = self.events.clone(); + let receive = self.inner.receive(); + async move { + let message = receive.await; + if message.is_none() { + let _ = events.send("eof"); + } + message + } + } + + async fn close(&mut self) -> Result<(), Self::Error> { + let _ = self.events.send("close"); + self.inner.close().await + } +} + +/// Runs a test body inside a `LocalSet` (the service loop's `spawn_local` under `local`). +async fn in_local_set(body: impl Future) { + tokio::task::LocalSet::new().run_until(body).await; +} + +async fn line(w: &mut DuplexStream, message: Value) { + let mut bytes = serde_json::to_vec(&message).unwrap(); + bytes.push(b'\n'); + w.write_all(&bytes).await.unwrap(); +} + +struct Session { + client_in: DuplexStream, + server: rmcp::service::RunningService, + cancelled: mpsc::UnboundedReceiver<()>, + events: mpsc::UnboundedReceiver<&'static str>, +} + +/// A server over `SinkStreamTransport::new(sink, )`. The tool call is +/// sent and its progress send is pending when this returns. +async fn session_on(sink: S) -> Session +where + S: Sink + Send + Unpin + 'static, + S::Error: std::error::Error + Send + Sync + 'static, +{ + let (cancelled_tx, cancelled) = mpsc::unbounded_channel(); + let (latch, mut progress_pending) = mpsc::unbounded_channel(); + let (events_tx, events) = mpsc::unbounded_channel(); + let (mut client_in, from_client) = tokio::io::duplex(4096); + let stream: BoxStream<'static, ClientJsonRpcMessage> = FramedRead::new( + from_client, + JsonRpcMessageCodec::::new(), + ) + .filter_map(|r| std::future::ready(r.ok())) + .boxed(); + let server = serve_directly::( + Server { + cancelled: cancelled_tx, + }, + Latched { + inner: SinkStreamTransport::new(sink, stream), + progress_pending: latch, + events: events_tx, + }, + Some( + InitializeRequestParams::new( + ClientCapabilities::default(), + Implementation::new("sink-stream-flush-test", "0.0.0"), + ) + .with_protocol_version(ProtocolVersion::V_2025_11_25), + ), + ); + line( + &mut client_in, + json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", + "params": {"name": "t", "arguments": {}, "_meta": {"progressToken": "t1"}}}), + ) + .await; + tokio::time::timeout(WAIT, progress_pending.recv()) + .await + .expect("progress send pending in time") + .expect("transport alive"); + Session { + client_in, + server, + cancelled, + events, + } +} + +/// The codec's sink over a 64-byte pipe: the progress frame is longer than the pipe. +fn framed( + out: DuplexStream, +) -> FramedWrite> { + FramedWrite::new(out, JsonRpcMessageCodec::::new()) +} + +async fn cancel(client_in: &mut DuplexStream) { + line( + client_in, + json!({"jsonrpc": "2.0", "method": "notifications/cancelled", + "params": {"requestId": 1, "reason": "stop"}}), + ) + .await; +} + +/// Every line is a whole JSON message, and the progress notification is one of them. +fn assert_whole_with_progress(lines: &[String], tail_newline: bool) { + assert!(tail_newline, "the output ends inside a message: {lines:?}"); + let mut progress = 0; + for l in lines { + let v: Value = serde_json::from_str(l) + .unwrap_or_else(|e| panic!("a partial message on the wire ({e}): {l:?}")); + if v["method"] == "notifications/progress" { + progress += 1; + } + } + assert_eq!(progress, 1, "the progress notification, once: {lines:?}"); +} + +fn split(bytes: &[u8]) -> (Vec, bool) { + let text = String::from_utf8_lossy(bytes).into_owned(); + let whole = text.is_empty() || text.ends_with('\n'); + (text.lines().map(str::to_owned).collect(), whole) +} + +fn read_all(mut out: DuplexStream) -> tokio::task::JoinHandle> { + tokio::spawn(async move { + let mut bytes = Vec::new(); + out.read_to_end(&mut bytes).await.unwrap(); + bytes + }) +} + +async fn stop(server: rmcp::service::RunningService) { + tokio::time::timeout(WAIT, server.waiting()) + .await + .expect("server stops in time") + .expect("server stops"); +} + +/// 1. A byte sink (`FramedWrite` over a 64-byte pipe): the abandoned progress frame is partly +/// written; `close` finishes it, so the peer reads it whole. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn framed_write_progress_abandoned_mid_flush_is_not_left_partial() { + in_local_set(framed_write_body()).await; +} + +async fn framed_write_body() { + let (server_out, client_out) = tokio::io::duplex(64); + let mut s = session_on(framed(server_out)).await; + cancel(&mut s.client_in).await; + tokio::time::timeout(WAIT, s.cancelled.recv()) + .await + .expect("cancellation handled in time") + .expect("server alive"); + let reader = read_all(client_out); + drop(s.client_in); + stop(s.server).await; + let bytes = tokio::time::timeout(WAIT, reader) + .await + .expect("output read in time") + .unwrap(); + let (lines, whole) = split(&bytes); + assert_whole_with_progress(&lines, whole); +} + +/// 2. A sink that holds an accepted message entirely until it is flushed (nothing written in +/// `start_send`): the abandoned progress notification is in the sink, not on the wire. The peer +/// starts reading after the cancellation; nothing else is sent, so only `close`'s flush delivers +/// it. Right outcome: delivered once, whole (not missing). +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn holding_sink_abandoned_progress_is_delivered_at_close() { + in_local_set(holding_sink_body()).await; +} + +async fn holding_sink_body() { + let hold = Hold::default(); + let mut s = session_on(hold.clone()).await; + assert!( + hold.out().is_empty(), + "written before the flush: {:?}", + hold.out() + ); + cancel(&mut s.client_in).await; + tokio::time::timeout(WAIT, s.cancelled.recv()) + .await + .expect("cancellation handled in time") + .expect("server alive"); + hold.release(); + drop(s.client_in); + stop(s.server).await; + assert_whole_with_progress(&hold.out(), true); +} + +/// 3. A peer that stops reading: the close's flush is bounded (`CLOSE_FLUSH_TIMEOUT`, 500 ms), so +/// the server stops within the drain deadline on EOF (5 s) plus 500 ms plus slack, for a byte sink +/// over a full pipe and for a sink that is never released. Shutdown timing only. +/// +/// This is a guard, not a regression test: it also passes on the base commit, where `close()` +/// returned without touching the sink. It exists so that a future flush that can hang is caught. +#[tokio::test(start_paused = true)] +async fn close_flush_is_bounded_when_the_peer_stops_reading() { + in_local_set(bounded_body()).await; +} + +async fn bounded_body() { + let budget = Duration::from_secs(5) + Duration::from_millis(500) + Duration::from_secs(1); + // the byte sink: the peer keeps its read half and never reads + let (server_out, client_out) = tokio::io::duplex(64); + let mut s = session_on(framed(server_out)).await; + cancel(&mut s.client_in).await; + let started = tokio::time::Instant::now(); + drop(s.client_in); + let r = tokio::time::timeout(budget, s.server.waiting()).await; + assert!( + r.is_ok(), + "framed: stopped only after {:?}", + started.elapsed() + ); + r.unwrap().expect("server stops"); + println!("framed: stopped after {:?} (virtual)", started.elapsed()); + drop(client_out); + // the holding sink, never released + let hold = Hold::default(); + let mut s = session_on(hold.clone()).await; + cancel(&mut s.client_in).await; + let started = tokio::time::Instant::now(); + drop(s.client_in); + let r = tokio::time::timeout(budget, s.server.waiting()).await; + assert!( + r.is_ok(), + "hold: stopped only after {:?}", + started.elapsed() + ); + r.unwrap().expect("server stops"); + println!("hold: stopped after {:?} (virtual)", started.elapsed()); + assert!( + hold.out().is_empty(), + "delivered without a release: {:?}", + hold.out() + ); +} + +/// 4. EOF before the abandoned send is dropped: the input ends while the progress send is pending +/// and no cancel is sent, so the loop drains with the send pending, the drain deadline (5 s, +/// paused time) drops it, and `close` runs after. The peer reads (or the sink is released) only +/// once the drop is reported; the message still arrives whole, for both sinks. +#[tokio::test(start_paused = true)] +async fn progress_dropped_after_eof_is_delivered_at_close() { + in_local_set(eof_first_body()).await; +} + +async fn until_dropped(events: &mut mpsc::UnboundedReceiver<&'static str>) -> Vec<&'static str> { + let mut seen = Vec::new(); + while !seen.contains(&"progress dropped") { + let e = tokio::time::timeout(WAIT, events.recv()) + .await + .expect("the progress send dropped in time") + .expect("transport alive"); + seen.push(e); + } + seen +} + +async fn eof_first_body() { + // the byte sink + let (server_out, client_out) = tokio::io::duplex(64); + let mut s = session_on(framed(server_out)).await; + let started = tokio::time::Instant::now(); + drop(s.client_in); + assert_eq!( + until_dropped(&mut s.events).await, + ["eof", "progress dropped"] + ); + assert!( + started.elapsed() >= Duration::from_secs(5), + "{:?}", + started.elapsed() + ); + let reader = read_all(client_out); + stop(s.server).await; + assert_eq!(s.events.recv().await, Some("close"), "close after the drop"); + let bytes = tokio::time::timeout(WAIT, reader) + .await + .expect("output read in time") + .unwrap(); + let (lines, whole) = split(&bytes); + assert_whole_with_progress(&lines, whole); + // the holding sink + let hold = Hold::default(); + let mut s = session_on(hold.clone()).await; + drop(s.client_in); + assert_eq!( + until_dropped(&mut s.events).await, + ["eof", "progress dropped"] + ); + hold.release(); + stop(s.server).await; + assert_eq!(s.events.recv().await, Some("close"), "close after the drop"); + assert_whole_with_progress(&hold.out(), true); +}