use std::collections::VecDeque;
use std::path::Path;
use std::process::Stdio;
use std::time::Duration;
use serde_json::Value;
use tokio::io::{AsyncWriteExt, BufReader};
use tokio::process::{Child, ChildStdin, ChildStdout};
use tokio::time::timeout;
use trusty_common::stdio_mcp_client::capped_line::{CappedLine, read_capped_line};
use trusty_common::stdio_mcp_client::{MAX_LINE_BYTES, is_response_to, log_field};
use trusty_mcp::Request;
use crate::events::SessionEventEnvelope;
pub const DEFAULT_CALL_TIMEOUT: Duration = Duration::from_secs(15);
#[derive(Debug, thiserror::Error)]
pub enum RpcClientError {
#[error("failed to spawn `{0}`: {1}")]
Spawn(String, #[source] std::io::Error),
#[error("daemon connection closed unexpectedly")]
ConnectionClosed,
#[error("failed to read from daemon: {0}")]
Io(#[source] std::io::Error),
#[error("malformed response from daemon: {0}")]
MalformedResponse(String),
#[error("daemon returned an error ({code}): {message}")]
Rpc {
code: i32,
message: String,
data: Option<Value>,
},
#[error("timed out waiting for the daemon to respond")]
Timeout,
#[error("daemon sent a line over the {0}-byte cap; line discarded")]
LineTooLong(usize),
}
fn logged_method(frame: &Value) -> String {
log_field(frame.get("method").and_then(Value::as_str).unwrap_or(""))
}
fn build_request(id: i64, method: &str, params: Value) -> Request {
Request {
jsonrpc: Some("2.0".to_string()),
id: Some(serde_json::json!(id)),
method: method.to_string(),
params: Some(params),
}
}
fn classify_notification(value: &Value) -> Option<SessionEventEnvelope> {
if value.get("method").and_then(|m| m.as_str()) != Some("session.event") {
return None;
}
serde_json::from_value(value.get("params")?.clone()).ok()
}
pub struct StdioRpcClient {
child: Child,
stdin: ChildStdin,
stdout: BufReader<ChildStdout>,
line_buf: Vec<u8>,
discard_line: bool,
next_id: i64,
pending_notifications: VecDeque<SessionEventEnvelope>,
}
impl StdioRpcClient {
pub fn spawn(tcode_exe: &Path, project: &Path) -> Result<Self, RpcClientError> {
let mut child = tokio::process::Command::new(tcode_exe)
.arg("serve")
.arg("--project")
.arg(project)
.arg("--stdio")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.kill_on_drop(true)
.spawn()
.map_err(|e| RpcClientError::Spawn(tcode_exe.display().to_string(), e))?;
let stdin = child.stdin.take().ok_or(RpcClientError::ConnectionClosed)?;
let stdout = child
.stdout
.take()
.ok_or(RpcClientError::ConnectionClosed)?;
Ok(Self {
child,
stdin,
stdout: BufReader::new(stdout),
line_buf: Vec::new(),
discard_line: false,
next_id: 1,
pending_notifications: VecDeque::new(),
})
}
pub async fn call(&mut self, method: &str, params: Value) -> Result<Value, RpcClientError> {
timeout(DEFAULT_CALL_TIMEOUT, self.call_inner(method, params))
.await
.map_err(|_| RpcClientError::Timeout)?
}
async fn call_inner(&mut self, method: &str, params: Value) -> Result<Value, RpcClientError> {
let id = self.next_id;
self.next_id += 1;
let id_value = Value::from(id);
let req = build_request(id, method, params);
let mut line = serde_json::to_string(&req)
.map_err(|e| RpcClientError::MalformedResponse(e.to_string()))?;
line.push('\n');
self.stdin
.write_all(line.as_bytes())
.await
.map_err(RpcClientError::Io)?;
self.stdin.flush().await.map_err(RpcClientError::Io)?;
loop {
let raw = self.read_raw_line().await?;
let value: Value = serde_json::from_str(&raw)
.map_err(|e| RpcClientError::MalformedResponse(format!("{e}: {raw}")))?;
if is_response_to(&value, &id_value) {
if let Some(err) = value.get("error").filter(|e| !e.is_null()) {
return Err(RpcClientError::Rpc {
code: err.get("code").and_then(Value::as_i64).unwrap_or(0) as i32,
message: err
.get("message")
.and_then(|m| m.as_str())
.unwrap_or_default()
.to_string(),
data: err.get("data").cloned(),
});
}
return Ok(value.get("result").cloned().unwrap_or(Value::Null));
}
if let Some(envelope) = classify_notification(&value) {
self.pending_notifications.push_back(envelope);
} else if value.get("id") == Some(&id_value) {
let method = logged_method(&value);
tracing::warn!(id, %method, "StdioRpcClient: skipping non-response frame with the awaited id");
} else {
tracing::debug!(id, "StdioRpcClient: skipping non-matching frame");
}
}
}
pub async fn next_notification(
&mut self,
wait: Duration,
) -> Result<Option<SessionEventEnvelope>, RpcClientError> {
if let Some(envelope) = self.pending_notifications.pop_front() {
return Ok(Some(envelope));
}
match timeout(wait, self.read_raw_line()).await {
Ok(Ok(raw)) => {
let value: Value = serde_json::from_str(&raw)
.map_err(|e| RpcClientError::MalformedResponse(format!("{e}: {raw}")))?;
Ok(classify_notification(&value))
}
Ok(Err(e)) => Err(e),
Err(_) => Ok(None),
}
}
async fn read_raw_line(&mut self) -> Result<String, RpcClientError> {
let read = read_capped_line(
&mut self.stdout,
&mut self.line_buf,
&mut self.discard_line,
MAX_LINE_BYTES,
)
.await
.map_err(RpcClientError::Io)?;
match read {
CappedLine::Line(bytes) => {
let line = String::from_utf8(bytes)
.map_err(|e| RpcClientError::MalformedResponse(e.to_string()))?;
Ok(line.trim_end_matches(['\n', '\r']).to_string())
}
CappedLine::TooLong => Err(RpcClientError::LineTooLong(MAX_LINE_BYTES)),
CappedLine::Eof => Err(RpcClientError::ConnectionClosed),
}
}
pub async fn shutdown(mut self, grace: Duration) -> Result<(), RpcClientError> {
drop(self.stdin);
match timeout(grace, self.child.wait()).await {
Ok(Ok(_status)) => Ok(()),
Ok(Err(e)) => Err(RpcClientError::Io(e)),
Err(_) => {
let _ = self.child.start_kill();
Ok(())
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn build_request_uses_2_0_and_given_id() {
let req = build_request(7, "session.list", json!({}));
assert_eq!(req.jsonrpc.as_deref(), Some("2.0"));
assert_eq!(req.id, Some(json!(7)));
assert_eq!(req.method, "session.list");
}
#[test]
fn classify_notification_recognises_session_event() {
let line = json!({
"method": "session.event",
"params": {
"session_id": "s-1",
"seq": 1,
"at": "2024-01-01T00:00:00Z",
"kind": "session_started",
"event": {"type": "session_started", "session_id": "s-1", "project": "p"},
}
});
let envelope = classify_notification(&line).expect("must classify as a notification");
assert_eq!(envelope.session_id, "s-1");
assert_eq!(envelope.kind, "session_started");
}
#[test]
fn classify_notification_ignores_other_shapes() {
let response = json!({"jsonrpc": "2.0", "id": 1, "result": {}});
assert!(classify_notification(&response).is_none());
let other_method = json!({"method": "ping", "params": {}});
assert!(classify_notification(&other_method).is_none());
let malformed_params = json!({"method": "session.event", "params": {"not": "an envelope"}});
assert!(classify_notification(&malformed_params).is_none());
}
#[tokio::test]
#[cfg(unix)]
async fn call_skips_server_request_with_matching_id() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().expect("tempdir");
let exe = dir.path().join("fake-tcode");
let script = "#!/bin/sh\nread -r l\n\
printf '{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"roots/list\"}\\n'\n\
printf '{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"x\",\"error\":{\"code\":-1,\"message\":\"m\"}}\\n'\n\
printf '{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"answer\":\"real\"}}\\n'\n\
sleep 5\n";
std::fs::write(&exe, script).expect("write script");
std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).expect("chmod");
let mut client = StdioRpcClient::spawn(&exe, dir.path()).expect("spawn");
let result = client
.call("session.list", json!({}))
.await
.expect("the real response");
assert_eq!(result, json!({ "answer": "real" }));
}
#[test]
fn logged_method_truncates_long_method() {
let frame = json!({"id": 1, "method": "m".repeat(10_000)});
let shown = logged_method(&frame);
assert_eq!(shown, format!("{}…(+9936)", "m".repeat(64)));
assert_eq!(
logged_method(&json!({"method": "roots/list"})),
"roots/list"
);
}
#[cfg(unix)]
fn fake_child(body: &str) -> (tempfile::TempDir, StdioRpcClient) {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().expect("tempdir");
let exe = dir.path().join("fake-tcode");
std::fs::write(&exe, format!("#!/bin/sh\n{body}")).expect("write script");
std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).expect("chmod");
let client = StdioRpcClient::spawn(&exe, dir.path()).expect("spawn");
(dir, client)
}
#[cfg(unix)]
fn oversize_line_sh() -> String {
format!(
"head -c {} /dev/zero | tr '\\000' x; printf '\\n'\n",
MAX_LINE_BYTES + 1
)
}
#[tokio::test]
#[cfg(unix)]
async fn oversize_line_errors_with_line_too_long() {
let (_dir, mut client) = fake_child(&format!("read -r l\n{}sleep 5\n", oversize_line_sh()));
let err = client
.call("session.list", json!({}))
.await
.expect_err("oversize");
assert!(
matches!(err, RpcClientError::LineTooLong(MAX_LINE_BYTES)),
"got {err:?}"
);
}
#[tokio::test]
#[cfg(unix)]
async fn oversize_line_errors_then_next_call_resyncs() {
let body = format!(
"read -r l\n{}printf '{{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":1}}\\n'\n\
read -r l\nprintf '{{\"jsonrpc\":\"2.0\",\"id\":2,\"result\":{{\"ok\":true}}}}\\n'\nsleep 5\n",
oversize_line_sh()
);
let (_dir, mut client) = fake_child(&body);
let first = client.call("session.list", json!({})).await;
assert!(
matches!(first, Err(RpcClientError::LineTooLong(_))),
"got {first:?}"
);
let second = client
.call("session.list", json!({}))
.await
.expect("resynced");
assert_eq!(second, json!({ "ok": true }));
}
}