use std::future::Future;
use std::sync::Arc;
use anyhow::Result;
use serde::Serialize;
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader};
use tokio::sync::mpsc;
use tracing::info;
use crate::jsonrpc::{ConnectionContext, Router};
pub async fn run_stdio_loop(router: Router) -> Result<()> {
let router = Arc::new(router);
let (notify_tx, notify_rx) = mpsc::unbounded_channel();
let ctx = ConnectionContext::new(notify_tx);
run_loop(
router,
tokio::io::stdin(),
tokio::io::stdout(),
trusty_common::shutdown_signal(),
ctx,
notify_rx,
)
.await
}
#[allow(clippy::too_many_arguments)]
async fn run_loop<R, W, Sh>(
router: Arc<Router>,
reader: R,
mut writer: W,
shutdown: Sh,
ctx: ConnectionContext,
mut notify_rx: mpsc::UnboundedReceiver<serde_json::Value>,
) -> Result<()>
where
R: AsyncRead + Unpin,
W: AsyncWrite + Unpin,
Sh: Future<Output = ()>,
{
tokio::pin!(shutdown);
let mut lines = BufReader::new(reader).lines();
loop {
tokio::select! {
biased;
() = &mut shutdown => {
info!("tcode serve: shutdown signal received, stopping");
break;
}
notification = notify_rx.recv() => {
let Some(notification) = notification else {
continue;
};
write_json_line(&mut writer, ¬ification).await?;
}
line = lines.next_line() => {
let Some(line) = line? else {
info!("tcode serve: stdin EOF, stopping");
break;
};
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
let response = router.dispatch_json(trimmed.as_bytes(), &ctx).await;
if response.suppress {
continue;
}
write_json_line(&mut writer, &response).await?;
}
}
}
Ok(())
}
async fn write_json_line<W: AsyncWrite + Unpin, T: Serialize>(
writer: &mut W,
value: &T,
) -> Result<()> {
let serialised = serde_json::to_string(value)?;
writer.write_all(serialised.as_bytes()).await?;
writer.write_all(b"\n").await?;
writer.flush().await?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use tokio::io::AsyncReadExt;
use trusty_mcp::error_codes;
fn router_with_ping() -> Arc<Router> {
let mut router = Router::new();
router.register(
"ping",
|_params: serde_json::Value, _ctx: ConnectionContext| async move {
Ok(json!({"pong": true}))
},
);
Arc::new(router)
}
fn test_ctx() -> (
ConnectionContext,
mpsc::UnboundedReceiver<serde_json::Value>,
) {
let (tx, rx) = mpsc::unbounded_channel();
(ConnectionContext::new(tx), rx)
}
#[tokio::test]
async fn run_loop_dispatches_and_writes_response() {
let router = router_with_ping();
let (mut input_tx, input_rx) = tokio::io::duplex(4096);
let (output_tx, mut output_rx) = tokio::io::duplex(4096);
let (ctx, notify_rx) = test_ctx();
input_tx
.write_all(b"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\"}\n")
.await
.unwrap();
drop(input_tx);
run_loop(
router,
input_rx,
output_tx,
std::future::pending::<()>(),
ctx,
notify_rx,
)
.await
.expect("loop must return Ok on EOF");
let mut out = Vec::new();
output_rx.read_to_end(&mut out).await.unwrap();
let line = String::from_utf8(out).unwrap();
let resp: serde_json::Value = serde_json::from_str(line.trim()).unwrap();
assert_eq!(resp["result"], json!({"pong": true}));
assert_eq!(resp["id"], 1);
}
#[tokio::test]
async fn run_loop_malformed_json_returns_parse_error() {
let router = router_with_ping();
let (mut input_tx, input_rx) = tokio::io::duplex(4096);
let (output_tx, mut output_rx) = tokio::io::duplex(4096);
let (ctx, notify_rx) = test_ctx();
input_tx.write_all(b"not json at all\n").await.unwrap();
drop(input_tx);
run_loop(
router,
input_rx,
output_tx,
std::future::pending::<()>(),
ctx,
notify_rx,
)
.await
.expect("loop must return Ok on EOF even after a parse error");
let mut out = Vec::new();
output_rx.read_to_end(&mut out).await.unwrap();
let resp: serde_json::Value =
serde_json::from_str(String::from_utf8(out).unwrap().trim()).unwrap();
assert_eq!(resp["error"]["code"], error_codes::PARSE_ERROR);
}
#[tokio::test]
async fn run_loop_notification_writes_nothing() {
let router = router_with_ping();
let (mut input_tx, input_rx) = tokio::io::duplex(4096);
let (output_tx, mut output_rx) = tokio::io::duplex(4096);
let (ctx, notify_rx) = test_ctx();
input_tx
.write_all(b"{\"jsonrpc\":\"2.0\",\"method\":\"ping\"}\n")
.await
.unwrap();
drop(input_tx);
run_loop(
router,
input_rx,
output_tx,
std::future::pending::<()>(),
ctx,
notify_rx,
)
.await
.expect("loop must return Ok on EOF");
let mut out = Vec::new();
output_rx.read_to_end(&mut out).await.unwrap();
assert!(
out.is_empty(),
"a notification must not produce a response line"
);
}
#[tokio::test]
async fn run_loop_exits_on_eof_when_shutdown_never_fires() {
let router = router_with_ping();
let (ctx, notify_rx) = test_ctx();
let result = run_loop(
router,
tokio::io::empty(),
tokio::io::sink(),
std::future::pending::<()>(),
ctx,
notify_rx,
)
.await;
assert!(result.is_ok(), "loop must return Ok on EOF: {result:?}");
}
#[tokio::test]
async fn run_loop_shutdown_signal_takes_priority_over_pending_input() {
let router = router_with_ping();
let (mut input_tx, input_rx) = tokio::io::duplex(4096);
let (output_tx, _output_rx) = tokio::io::duplex(4096);
let (ctx, notify_rx) = test_ctx();
input_tx
.write_all(b"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\"}\n")
.await
.unwrap();
drop(input_tx);
let result = tokio::time::timeout(
std::time::Duration::from_secs(5),
run_loop(
router,
input_rx,
output_tx,
std::future::ready(()),
ctx,
notify_rx,
),
)
.await;
assert!(
result.is_ok(),
"loop must return promptly once the shutdown future is ready"
);
assert!(result.unwrap().is_ok());
}
#[tokio::test]
async fn run_loop_forwards_queued_notifications_to_the_wire() {
let router = router_with_ping();
let (_input_tx, input_rx) = tokio::io::duplex(4096);
let (output_tx, mut output_rx) = tokio::io::duplex(4096);
let (tx, rx) = mpsc::unbounded_channel();
let ctx = ConnectionContext::new(tx);
let notification = json!({
"jsonrpc": "2.0",
"method": "session.event",
"params": {"session_id": "s-1", "event": {"type": "session_input", "input": "hi"}},
});
ctx.notify.send(notification.clone()).unwrap();
let shutdown = async { tokio::time::sleep(std::time::Duration::from_millis(100)).await };
run_loop(router, input_rx, output_tx, shutdown, ctx, rx)
.await
.expect("loop must return Ok once shutdown fires");
let mut out = Vec::new();
output_rx.read_to_end(&mut out).await.unwrap();
let line: serde_json::Value =
serde_json::from_str(String::from_utf8(out).unwrap().trim()).unwrap();
assert_eq!(line, notification);
}
}