use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicI64, Ordering};
use std::time::Duration;
use serde::de::DeserializeOwned;
use serde_json::{Value, json};
use trusty_common::uds::{FramedStream, send_framed_request, send_framed_stream_request};
use trusty_mcp::Response;
use super::error::EngineError;
pub const DEFAULT_CALL_TIMEOUT: Duration = Duration::from_secs(15);
pub const STREAM_FRAME_TIMEOUT: Duration = Duration::from_secs(900);
pub struct UdsRpcClient {
socket: PathBuf,
next_id: AtomicI64,
stream_frame_timeout: Duration,
}
impl UdsRpcClient {
pub fn new(socket: impl Into<PathBuf>) -> Self {
Self {
socket: socket.into(),
next_id: AtomicI64::new(1),
stream_frame_timeout: STREAM_FRAME_TIMEOUT,
}
}
pub fn with_stream_frame_timeout(mut self, timeout: Duration) -> Self {
self.stream_frame_timeout = timeout;
self
}
pub fn socket(&self) -> &Path {
&self.socket
}
pub async fn call(&self, method: &str, params: Value) -> Result<Value, EngineError> {
let request = json!({
"jsonrpc": "2.0",
"id": self.next_id.fetch_add(1, Ordering::Relaxed),
"method": method,
"params": params,
});
let response: Response = send_framed_request(&self.socket, &request, DEFAULT_CALL_TIMEOUT)
.await
.map_err(|source| EngineError::Transport {
socket: self.socket.clone(),
source: Box::new(source),
})?;
match (response.result, response.error) {
(Some(result), _) => Ok(result),
(None, Some(error)) => Err(EngineError::Rpc {
code: error.code,
message: error.message,
data: error.data,
}),
(None, None) => Err(EngineError::Malformed(format!(
"{method}: response carried neither result nor error"
))),
}
}
pub async fn open_stream<T: DeserializeOwned>(
&self,
method: &str,
params: Value,
) -> Result<FramedStream<T>, EngineError> {
let request = json!({
"jsonrpc": "2.0",
"id": self.next_id.fetch_add(1, Ordering::Relaxed),
"method": method,
"params": params,
"stream": true,
});
send_framed_stream_request(&self.socket, &request, self.stream_frame_timeout)
.await
.map_err(|source| EngineError::Transport {
socket: self.socket.clone(),
source: Box::new(source),
})
}
}