Skip to content
Open
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
139 changes: 133 additions & 6 deletions crates/rmcp/src/transport/common/client_side_sse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -463,12 +463,25 @@ where
}
this.connector
.handle_stream_error(&e, this.last_event_id.as_deref());
let retrying = this
.connector
.retry_connection(this.last_event_id.as_deref());
SseAutoReconnectStreamState::Retrying {
retry_times: 0,
retrying,
let interval = this
.retry_policy
.retry(0)
.map(|interval| this.server_retry_interval.unwrap_or(interval));
if let Some(interval) = interval {
tracing::debug!(
?interval,
"sse stream errored, waiting before reconnecting"
);
SseAutoReconnectStreamState::WaitingNextRetry {
sleep: tokio::time::sleep(interval),
retry_times: 0,
}
} else {
tracing::debug!("sse stream errored, no reconnect policy");
this.state.set(SseAutoReconnectStreamState::Terminated);
return Poll::Ready(
this.connector.map_fatal_stream_error(e).map(Err),
);
}
}
None => {
Expand Down Expand Up @@ -497,6 +510,7 @@ where
}
} else {
tracing::debug!("sse stream terminated, no reconnect policy");
this.state.set(SseAutoReconnectStreamState::Terminated);
return Poll::Ready(None);
}
}
Expand Down Expand Up @@ -945,4 +959,117 @@ mod tests {
assert!(policy.retry(2).is_some());
assert!(policy.retry(3).is_none());
}

#[tokio::test]
async fn never_retry_does_not_reconnect_after_stream_error() {
let source = futures::stream::iter([Err::<Bytes, _>(std::io::Error::new(
std::io::ErrorKind::ConnectionReset,
"connection reset",
))]);
let attempts = Arc::new(AtomicUsize::new(0));
let connector = CountingReconnect {
attempts: attempts.clone(),
};
let stream = SseAutoReconnectStream::new(
bounded_sse_stream(source, 1024),
connector,
Arc::new(NeverRetry),
);
let mut stream = std::pin::pin!(stream);

let result = stream.next().await;

assert!(matches!(result, Some(Err(TestReconnectError::Sse(_)))));
assert_eq!(attempts.load(Ordering::Relaxed), 0);
assert!(stream.next().await.is_none());
}

#[tokio::test]
async fn max_times_zero_does_not_reconnect_after_stream_error() {
let source = futures::stream::iter([Err::<Bytes, _>(std::io::Error::new(
std::io::ErrorKind::ConnectionReset,
"connection reset",
))]);
let attempts = Arc::new(AtomicUsize::new(0));
let connector = CountingReconnect {
attempts: attempts.clone(),
};
let stream = SseAutoReconnectStream::new(
bounded_sse_stream(source, 1024),
connector,
Arc::new(FixedInterval {
max_times: Some(0),
duration: Duration::ZERO,
}),
);
let mut stream = std::pin::pin!(stream);

let result = stream.next().await;

assert!(matches!(result, Some(Err(TestReconnectError::Sse(_)))));
assert_eq!(attempts.load(Ordering::Relaxed), 0);
}

#[tokio::test(start_paused = true)]
async fn server_retry_interval_applies_after_stream_error() {
let source = futures::stream::iter([
Ok::<Bytes, std::io::Error>(Bytes::from_static(b"id: 1\nretry: 5000\ndata: \n\n")),
Err(std::io::Error::new(
std::io::ErrorKind::ConnectionReset,
"connection reset",
)),
]);
let reconnects = Arc::new(std::sync::Mutex::new(Vec::new()));
let stream = SseAutoReconnectStream::new(
bounded_sse_stream(source, 1024),
ClosingReconnect {
reconnects: reconnects.clone(),
},
Arc::new(ExponentialBackoff::default()),
);
let mut stream = std::pin::pin!(stream);
let start = tokio::time::Instant::now();

assert!(matches!(stream.next().await, Some(Ok(_))));

let reconnects = reconnects.lock().unwrap();
let offsets: Vec<_> = reconnects.iter().map(|at| *at - start).collect();
assert_eq!(
offsets,
[Duration::from_secs(5)],
"the server's retry interval should be respected after a stream error"
);
}

#[tokio::test]
async fn graceful_close_with_never_retry_transitions_to_terminated() {
let polls = Arc::new(AtomicUsize::new(0));
let polls_clone = polls.clone();
// A non-fused inner stream that returns `None` on the first poll and
// yields a valid JSON-RPC notification if polled again. Without
// transitioning to `Terminated`, a second `poll_next` polls the inner
// stream again and surfaces `Some(Ok(_))`.
let inner: BoxedSseResponse = futures::stream::poll_fn(move |_cx| {
if polls_clone.fetch_add(1, Ordering::Relaxed) == 0 {
Poll::Ready(None)
} else {
let sse = Sse::default()
.data(r#"{"jsonrpc":"2.0","method":"notifications/tools/list_changed"}"#);
Poll::Ready(Some(Ok(sse)))
}
})
.boxed();

let attempts = Arc::new(AtomicUsize::new(0));
let connector = CountingReconnect {
attempts: attempts.clone(),
};
let stream = SseAutoReconnectStream::new(inner, connector, Arc::new(NeverRetry));
let mut stream = std::pin::pin!(stream);

assert!(stream.next().await.is_none());
assert!(stream.next().await.is_none());
assert_eq!(polls.load(Ordering::Relaxed), 1);
assert_eq!(attempts.load(Ordering::Relaxed), 0);
}
}