Skip to content
Open
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
161 changes: 149 additions & 12 deletions crates/rmcp/src/transport/streamable_http_server/session/local.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,14 @@ pub struct EventId {
index: usize,
}

impl EventId {
/// The index of the first event to replay on resume. `Last-Event-ID`
/// names the last event the client received, so replay starts after it.
fn next_index(&self) -> usize {
self.index.saturating_add(1)
}
}

impl std::fmt::Display for EventId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.index)?;
Expand Down Expand Up @@ -269,7 +277,10 @@ impl CachedTx {
session_id: &SessionId,
event_store: Option<Arc<dyn EventStore>>,
) -> Self {
Self::new(tx, None, 0, format!("{session_id}:common"), event_store)
// Index 0 is the priming event that opens a standalone stream, which
// is not cached. Events start at 1, so `Last-Event-ID: 0` always
// means that no event has been read yet.
Self::new(tx, None, 1, format!("{session_id}:common"), event_store)
}

fn next_event_id(&self) -> EventId {
Expand Down Expand Up @@ -328,7 +339,8 @@ impl CachedTx {
});
}

async fn sync(&mut self, index: usize) -> Result<(), SessionError> {
/// Replays the cached events whose index is at least `from_index`.
async fn sync(&mut self, from_index: usize) -> Result<(), SessionError> {
let Some(front) = self.cache.front() else {
return Ok(());
};
Expand All @@ -337,7 +349,7 @@ impl CachedTx {
.as_deref()
.unwrap_or_default()
.parse::<EventId>()?;
let sync_index = index.saturating_sub(front_event_id.index);
let sync_index = from_index.saturating_sub(front_event_id.index);
if sync_index > self.cache.len() {
// invalid index
return Err(SessionError::InvalidEventId);
Expand Down Expand Up @@ -698,8 +710,7 @@ impl LocalSessionWorker {
let is_completed = request_wise.completed_at.is_some();
let (tx, rx) = tokio::sync::mpsc::channel(self.session_config.channel_capacity);
request_wise.tx.tx = tx;
let index = last_event_id.index;
request_wise.tx.sync(index).await?;
request_wise.tx.sync(last_event_id.next_index()).await?;
if is_completed {
// Drop the sender after replaying so the stream ends
// instead of hanging indefinitely.
Expand All @@ -712,7 +723,7 @@ impl LocalSessionWorker {
})
}
None => {
self.resume_or_shadow_common(Some(last_event_id.index))
self.resume_or_shadow_common(Some(last_event_id.next_index()))
.await
}
}
Expand All @@ -721,16 +732,17 @@ impl LocalSessionWorker {
async fn establish_common_channel(
&mut self,
) -> Result<StreamableHttpMessageReceiver, SessionError> {
let last_event_index = self.event_store.is_none().then_some(0);
self.resume_or_shadow_common(last_event_index).await
// A new stream has read nothing: replay the whole cache.
let from_index = self.event_store.is_none().then_some(0);
self.resume_or_shadow_common(from_index).await
}

/// Resume the common channel, or create a shadow stream if the primary is
/// still active.
///
/// When the primary common channel is dead (receiver dropped), replace it
/// so this stream becomes the new primary notification channel. Cached
/// messages are replayed from `last_event_index` so the client receives
/// messages are replayed from `from_index` so the client receives
/// any events it missed (including server-initiated requests).
///
/// When the primary is still active, create a "shadow" stream — an idle SSE
Expand All @@ -739,7 +751,7 @@ impl LocalSessionWorker {
/// killing each other by repeatedly replacing the common channel sender.
async fn resume_or_shadow_common(
&mut self,
last_event_index: Option<usize>,
from_index: Option<usize>,
) -> Result<StreamableHttpMessageReceiver, SessionError> {
let is_replacing_dead_primary = self.common.tx.is_closed();
let capacity = if is_replacing_dead_primary {
Expand All @@ -752,8 +764,8 @@ impl LocalSessionWorker {
// Primary common channel is dead — replace it.
tracing::debug!("Replacing dead common channel with new primary");
self.common.tx = tx;
if let Some(last_event_index) = last_event_index {
self.common.sync(last_event_index).await?;
if let Some(from_index) = from_index {
self.common.sync(from_index).await?;
}
} else {
// Primary common channel is still active. Create a shadow stream
Expand Down Expand Up @@ -1963,3 +1975,128 @@ mod completed_channel_resume_tests {
drop(handle);
}
}

#[cfg(test)]
mod resume_replay_tests {
use super::*;
use crate::model::{NumberOrString, ProgressNotification, ToolListChangedNotification};

/// Takes what a resume has replayed. `sync` sends before `resume` returns,
/// so nothing is still on its way when this runs.
fn replayed_ids(receiver: &mut StreamableHttpMessageReceiver) -> Vec<String> {
let mut ids = Vec::new();
while let Ok(event) = receiver.inner.try_recv() {
ids.push(event.event_id.expect("cached events carry an id"));
}
ids
}

fn progress(token: &ProgressToken, progress: f64) -> ServerJsonRpcMessage {
ServerJsonRpcMessage::notification(
ProgressNotification::new(ProgressNotificationParam::new(token.clone(), progress))
.into(),
)
}

fn tool_list_changed() -> ServerJsonRpcMessage {
ServerJsonRpcMessage::notification(ToolListChangedNotification::default().into())
}

#[tokio::test]
async fn request_wise_resume_replays_only_events_after_last_event_id() {
let (_handle, mut worker) = create_local_session("test-session", SessionConfig::default());
let mut receiver = worker.establish_request_wise_channel().await.unwrap();
let http_request_id = receiver.http_request_id.unwrap();
let token = ProgressToken(NumberOrString::Number(9));
worker.register_resource(ResourceKey::ProgressToken(token.clone()), http_request_id);

worker
.handle_server_message(progress(&token, 1.0))
.await
.unwrap();
worker
.handle_server_message(progress(&token, 2.0))
.await
.unwrap();
// The priming event, then the two progress notifications.
assert_eq!(replayed_ids(&mut receiver), ["0/0", "1/0", "2/0"]);
drop(receiver);

// The client read up to the first progress notification.
let mut resumed = worker.resume("1/0".parse().unwrap()).await.unwrap();
assert_eq!(replayed_ids(&mut resumed), ["2/0"]);
drop(resumed);

// The client read everything: there is nothing to replay.
let mut resumed = worker.resume("2/0".parse().unwrap()).await.unwrap();
assert!(replayed_ids(&mut resumed).is_empty());
drop(resumed);

// The client read only the priming event.
let mut resumed = worker.resume("0/0".parse().unwrap()).await.unwrap();
assert_eq!(replayed_ids(&mut resumed), ["1/0", "2/0"]);
}

#[tokio::test]
async fn request_wise_resume_rejects_an_event_id_that_was_never_sent() {
let (_handle, mut worker) = create_local_session("test-session", SessionConfig::default());
let receiver = worker.establish_request_wise_channel().await.unwrap();
drop(receiver);

// Only the priming event `0/0` exists.
let result = worker.resume("1/0".parse().unwrap()).await;
assert!(matches!(result, Err(SessionError::InvalidEventId)));
}

#[tokio::test]
async fn common_resume_replays_only_events_after_last_event_id() {
let (_handle, mut worker) = create_local_session("test-session", SessionConfig::default());
let mut receiver = worker.establish_common_channel().await.unwrap();
worker
.handle_server_message(tool_list_changed())
.await
.unwrap();
worker
.handle_server_message(tool_list_changed())
.await
.unwrap();
let sent = replayed_ids(&mut receiver);
assert_eq!(sent.len(), 2);
// `0` is the id of the priming event that opens a standalone stream.
// An event must not share it, or `Last-Event-ID: 0` could not tell
// "read the priming event only" from "read the first event".
assert!(!sent.contains(&"0".to_owned()), "{sent:?}");
drop(receiver);

// The client read up to the first event.
let mut resumed = worker.resume(sent[0].parse().unwrap()).await.unwrap();
assert_eq!(replayed_ids(&mut resumed), [sent[1].as_str()]);
drop(resumed);

// The client read everything: there is nothing to replay.
let mut resumed = worker.resume(sent[1].parse().unwrap()).await.unwrap();
assert!(replayed_ids(&mut resumed).is_empty());
drop(resumed);

// The client read only the priming event.
let mut resumed = worker.resume("0".parse().unwrap()).await.unwrap();
assert_eq!(replayed_ids(&mut resumed), sent);
}

#[tokio::test]
async fn new_standalone_stream_replays_every_cached_event() {
let (_handle, mut worker) = create_local_session("test-session", SessionConfig::default());
// Sent before any standalone stream is open: cached for the first one.
worker
.handle_server_message(tool_list_changed())
.await
.unwrap();
worker
.handle_server_message(tool_list_changed())
.await
.unwrap();

let mut receiver = worker.establish_common_channel().await.unwrap();
assert_eq!(replayed_ids(&mut receiver).len(), 2);
}
}
60 changes: 57 additions & 3 deletions crates/rmcp/tests/test_sse_concurrent_streams.rs
Original file line number Diff line number Diff line change
Expand Up @@ -695,8 +695,9 @@ async fn dropping_shadows_does_not_affect_primary() {
// ─── Tests: Cache replay on dead primary replacement ─────────────────────────

/// When a notification is sent while the primary is alive, then the primary
/// dies and a new GET resumes with Last-Event-ID "0", the replacement primary
/// should receive the cached notification via sync() replay.
/// dies and a new GET resumes with Last-Event-ID "0" (the priming event, so the
/// client has read no notification yet), the replacement primary should
/// receive the cached notification via sync() replay.
#[tokio::test]
async fn dead_primary_replacement_replays_cached_events() {
let ct = CancellationToken::new();
Expand All @@ -722,7 +723,7 @@ async fn dead_primary_replacement_replays_cached_events() {
tokio::time::sleep(Duration::from_millis(100)).await;

// Resume with Last-Event-ID "0" — primary is dead, should replace it
// and replay cached events from index 0
// and replay every cached event after the priming event
let get_resume = open_resume_get(&client, &url, &session_id, "0").await;
assert_eq!(get_resume.status(), 200);

Expand All @@ -735,6 +736,59 @@ async fn dead_primary_replacement_replays_cached_events() {
ct.cancel();
}

/// `Last-Event-ID` names the last event the client received, so a resume
/// replays only what came after it. Replaying that event again would hand
/// the client a message it has already processed.
#[tokio::test]
async fn resume_does_not_replay_the_event_named_by_last_event_id() {
let ct = CancellationToken::new();
let trigger = Arc::new(Notify::new());
let url = start_test_server(ct.clone(), trigger.clone()).await;
let client = reqwest::Client::new();

let session_id = initialize_session(&client, &url).await;
send_initialized_notification(&client, &url, &session_id).await;
tokio::time::sleep(Duration::from_millis(200)).await;

// First GET — becomes primary
let get1 = open_standalone_get(&client, &url, &session_id).await;
assert_eq!(get1.status(), 200);
tokio::time::sleep(Duration::from_millis(100)).await;

// The client reads the notification and remembers its event id.
trigger.notify_one();
let mut stream = get1.bytes_stream();
let mut received = String::new();
let last_event_id = tokio::time::timeout(Duration::from_secs(3), async {
loop {
let chunk = stream.next().await.expect("stream open").expect("chunk");
received.push_str(&String::from_utf8_lossy(&chunk));
let id = received
.split("\n\n")
.filter(|event| event.contains("tools/list_changed"))
.find_map(|event| event.lines().find_map(|line| line.strip_prefix("id:")));
if let Some(id) = id {
break id.trim().to_owned();
}
}
})
.await
.expect("primary should receive the notification with an event id");

// Drop primary, then resume from the notification the client already has.
drop(stream);
tokio::time::sleep(Duration::from_millis(100)).await;
let get_resume = open_resume_get(&client, &url, &session_id, &last_event_id).await;
assert_eq!(get_resume.status(), 200);

assert!(
!wait_for_sse_event(get_resume, "tools/list_changed", Duration::from_millis(500)).await,
"the event named by Last-Event-ID {last_event_id:?} must not be replayed"
);

ct.cancel();
}

// ─── Tests: Shadow stream limits ─────────────────────────────────────────────

/// Opening more than 32 shadow streams should not crash or reject — the server
Expand Down