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
100 changes: 45 additions & 55 deletions crates/rmcp/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1471,27 +1471,38 @@ where
ToSink(TxJsonRpcMessage<R>),
SendTaskResult(SendTaskResult),
ResponseSendTaskResult(Result<(), tokio::task::JoinError>),
Quit(QuitReason, Duration),
}

let mut sink_proxy_tx = Some(sink_proxy_tx);
let mut draining: Option<(QuitReason, tokio::time::Instant)> = None;
let quit_reason = loop {
if draining.is_some()
&& sink_proxy_rx.is_closed()
&& sink_proxy_rx.is_empty()
&& send_task_set.is_empty()
&& response_send_tasks.is_empty()
{
break draining.take().expect("draining").0;
}
let evt = if let Some(m) = batch_messages.pop_front() {
Event::PeerMessage(m)
} else {
tokio::select! {
m = sink_proxy_rx.recv(), if !sink_proxy_rx.is_closed() => {
m = sink_proxy_rx.recv(), if !sink_proxy_rx.is_closed() || !sink_proxy_rx.is_empty() => {
if let Some(m) = m {
Event::ToSink(m)
} else {
continue
}
}
m = transport.receive() => {
m = transport.receive(), if draining.is_none() => {
if let Some(m) = m {
Event::PeerMessage(m)
} else {
// input stream closed
tracing::info!("input stream terminated");
break QuitReason::Closed
Event::Quit(QuitReason::Closed, Duration::from_secs(5))
}
}
m = peer_rx.recv(), if !peer_rx.is_closed() => {
Expand All @@ -1509,6 +1520,9 @@ where
Err(e) => {
// join error, which is serious, we should quit.
tracing::error!(%e, "send request task encounter a tokio join error");
if draining.is_some() {
continue;
}
break QuitReason::JoinError(e)
}
Ok(result) => {
Expand All @@ -1521,15 +1535,30 @@ where
result.expect("non-empty response send task set")
)
}
_ = serve_loop_ct.cancelled() => {
_ = serve_loop_ct.cancelled(), if draining.is_none() => {
tracing::info!("task cancelled");
break QuitReason::Cancelled
Event::Quit(QuitReason::Cancelled, Duration::from_secs(2))
}
_ = async {
let (_, deadline) = draining.as_ref().expect("draining");
tokio::time::sleep_until(*deadline).await;
}, if draining.is_some() => {
tracing::warn!("timed out draining in-flight responses");
break draining.take().expect("draining").0;
}
}
};

tracing::trace!(?evt, "new event");
match evt {
Event::Quit(reason, timeout) => {
draining = Some((reason, tokio::time::Instant::now() + timeout));
// Only handler clones keep the response channel open now.
sink_proxy_tx.take();
// No further input will be read, so peer requests cannot finish.
// Notifications and response sends still run through this loop.
local_responder_pool.clear();
}
Event::SendTaskResult(SendTaskResult::Request { id, result }) => {
if let Err(e) = result
&& let Some(responder) = local_responder_pool.remove(&id) {
Expand Down Expand Up @@ -1588,6 +1617,10 @@ where
id,
responder,
}) => {
if draining.is_some() {
let _ = responder.send(Err(ServiceError::TransportClosed));
continue;
}
local_responder_pool.insert(id.clone(), PendingResponse {
responder,
is_subscription: R::is_subscription_request(&request),
Expand Down Expand Up @@ -1649,7 +1682,7 @@ where
}
{
let service = shared_service.clone();
let sink = sink_proxy_tx.clone();
let sink = sink_proxy_tx.as_ref().expect("not draining").clone();
let request_ct = serve_loop_ct.child_token();
let context_ct = request_ct.child_token();
local_ct_pool.insert(id.clone(), request_ct);
Expand Down Expand Up @@ -1829,57 +1862,14 @@ where
}
};

// Drain in-flight handler responses before closing the transport.
// When stdin EOF or cancellation arrives, spawned handler tasks may still
// be finishing. We need to:
// 1. Wait for response sends that were already spawned in the main loop
// 2. Drain any remaining handler responses from the channel
let drain_timeout = match &quit_reason {
QuitReason::Closed => Some(Duration::from_secs(5)),
QuitReason::Cancelled => Some(Duration::from_secs(2)),
_ => None,
};
if let Some(timeout_duration) = drain_timeout {
// Drop our sender so the channel closes once all handler task
// clones finish sending their responses (or are dropped).
drop(sink_proxy_tx);
let drain_result = tokio::time::timeout(timeout_duration, async {
// First, wait for any response sends already dispatched by the
// main loop (these hold transport write futures).
while let Some(result) = response_send_tasks.join_next().await {
if let Err(error) = result {
tracing::error!(%error, "response send task failed during drain");
}
}
// Then drain any handler responses still in the channel
// (handlers that finished after the loop broke).
while let Some(m) = sink_proxy_rx.recv().await {
if let Some(id) = match &m {
JsonRpcMessage::Response(response) => Some(&response.id),
JsonRpcMessage::Error(error) => error.id.as_ref(),
_ => None,
} {
let Some(ct) = local_ct_pool.remove(id) else {
tracing::debug!(%id, "dropping response for cancelled request");
continue;
};
ct.cancel();
}
if let Err(error) = transport.send(m).await {
tracing::error!(%error, "failed to send pending response during drain");
break;
}
}
})
.await;
if drain_result.is_err() {
tracing::warn!("timed out draining in-flight responses");
}
}

// Preserve the response drain above, then cancel any handlers still running.
// After the bounded response drain, cancel any handlers still running.
// EOF does not cancel the externally supplied service token.
serve_loop_ct.cancel();
drop(peer_rx);
// A pending send may hold the transport's writer lock. Abort and join
// those tasks before closing, especially when the drain timed out.
send_task_set.shutdown().await;
response_send_tasks.shutdown().await;

let sink_close_result = transport.close().await;
if let Err(e) = sink_close_result {
Expand Down
Loading