use pretty_assertions::assert_eq;
use rmcp::model::{CallToolResult, ContentBlock};
use serde_json::{json, Map, Value};
use tokio::sync::oneshot;
use super::{Parked, CALL_WAIT, MAX_PARKED_CALLS};
async fn park(parked: &Parked, answer: &str) -> (oneshot::Sender<()>, CallToolResult) {
let (release, released) = oneshot::channel();
let answer = answer.to_owned();
let call = Box::pin(async move {
let _ = released.await;
CallToolResult::success(vec![ContentBlock::text(answer)])
});
(release, parked.run("slow", call).await)
}
fn parked_id(result: &CallToolResult) -> Option<String> {
let id = result.structured_content.as_ref()?.get("id")?;
id.as_str().map(str::to_owned)
}
fn text_of(result: &CallToolResult) -> (String, bool) {
let text = result
.content
.iter()
.filter_map(|block| block.as_text().map(|text| text.text.clone()))
.collect();
(text, result.is_error == Some(true))
}
fn await_args(id: &str) -> Map<String, Value> {
let Value::Object(arguments) = json!({"id": id}) else {
unreachable!("arguments are an object");
};
arguments
}
#[tokio::test(start_paused = true)]
async fn only_running_calls_count_toward_the_parked_limit() {
let parked = Parked::default();
let mut releases = Vec::new();
let mut ids = Vec::new();
for at in 0..MAX_PARKED_CALLS {
let (release, answer) = park(&parked, &format!("call {at}")).await;
releases.push(release);
ids.push(parked_id(&answer));
}
let (_refused_release, refused) = park(&parked, "over").await;
let first = ids[0].clone().unwrap_or_default();
let _ = releases.remove(0).send(());
let (_again_release, again) = park(&parked, "again").await;
let first_result = parked.wait(await_args(&first)).await;
assert_eq!(
(
ids.iter().filter(|id| id.is_some()).count(),
text_of(&refused),
parked_id(&again).is_some(),
text_of(&first_result),
),
(
MAX_PARKED_CALLS,
(
format!(
"rho's `slow` call is still running after {} s, but rho keeps at most \
{MAX_PARKED_CALLS} running calls waiting for `await` (MAX_PARKED_CALLS) \
and {MAX_PARKED_CALLS} run already, so this one cannot: rho shows its end, \
but its result will not reach you. Call `await` on the waiting calls first.",
CALL_WAIT.as_secs(),
),
true,
),
true,
("call 0".to_owned(), false),
)
);
}