use std::collections::VecDeque;
use std::path::Path;
use std::process::Stdio;
use std::time::Duration;
use serde_json::Value;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, Lines};
use tokio::process::{Child, ChildStdin, ChildStdout};
use tokio::time::timeout;
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,
}
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,
lines: Lines<BufReader<ChildStdout>>,
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,
lines: BufReader::new(stdout).lines(),
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 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 value.get("id").and_then(Value::as_i64) == Some(id) {
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);
}
}
}
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> {
self.lines
.next_line()
.await
.map_err(RpcClientError::Io)?
.ok_or(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());
}
}