use std::sync::atomic::{AtomicI64, Ordering};
use serde_json::Value;
use trusty_mcp::{Request, Response};
use super::error::EngineError;
pub const DEFAULT_CALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
pub struct RpcHttpClient {
http: reqwest::Client,
base_url: String,
credential: Option<String>,
next_id: AtomicI64,
}
impl RpcHttpClient {
pub fn new(http: reqwest::Client, base_url: String) -> Self {
let credential = super::discovery::daemon_credential_for(&base_url);
Self {
http,
base_url,
credential,
next_id: AtomicI64::new(1),
}
}
pub fn credential(&self) -> Option<&str> {
self.credential.as_deref()
}
pub fn authorize(&self, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
match &self.credential {
Some(token) => req.bearer_auth(token),
None => req,
}
}
pub fn base_url(&self) -> &str {
&self.base_url
}
pub fn http(&self) -> &reqwest::Client {
&self.http
}
pub async fn call(&self, method: &str, params: Value) -> Result<Value, EngineError> {
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
let req = Request {
jsonrpc: Some("2.0".to_string()),
id: Some(serde_json::json!(id)),
method: method.to_string(),
params: Some(params),
};
let url = format!("{}/rpc", self.base_url);
let resp = self
.authorize(self.http.post(&url))
.json(&req)
.timeout(DEFAULT_CALL_TIMEOUT)
.send()
.await
.map_err(|source| EngineError::Transport {
url: url.clone(),
source,
})?;
let body: Response = resp
.json()
.await
.map_err(|source| EngineError::Transport { url, source })?;
if let Some(err) = body.error {
return Err(EngineError::Rpc {
code: err.code,
message: err.message,
data: err.data,
});
}
Ok(body.result.unwrap_or(Value::Null))
}
}
#[cfg(test)]
mod rpc_tests {
use super::*;
use serde_json::json;
use wiremock::matchers::{header, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
#[tokio::test]
async fn call_sends_the_bearer_credential() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/rpc"))
.and(header("authorization", "Bearer test-credential"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"jsonrpc": "2.0",
"id": 1,
"result": {"pong": true},
})))
.mount(&server)
.await;
let mut client = RpcHttpClient::new(reqwest::Client::new(), server.uri());
client.credential = Some("test-credential".to_string());
assert_eq!(client.credential(), Some("test-credential"));
let result = client.call("ping", json!({})).await.expect("call");
assert_eq!(result, json!({"pong": true}));
}
#[tokio::test]
async fn call_sends_no_header_without_a_credential() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/rpc"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"jsonrpc": "2.0",
"id": 1,
"result": {"pong": true},
})))
.mount(&server)
.await;
let mut client = RpcHttpClient::new(reqwest::Client::new(), server.uri());
client.credential = None;
client.call("ping", json!({})).await.expect("call");
let requests = server
.received_requests()
.await
.expect("wiremock records requests");
assert_eq!(requests.len(), 1);
assert!(
requests[0].headers.get("authorization").is_none(),
"a credential-less client must send no Authorization header"
);
}
#[tokio::test]
async fn call_returns_result_on_success() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/rpc"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"jsonrpc": "2.0",
"id": 1,
"result": {"pong": true},
})))
.mount(&server)
.await;
let client = RpcHttpClient::new(reqwest::Client::new(), server.uri());
let result = client.call("ping", json!({})).await.expect("call");
assert_eq!(result, json!({"pong": true}));
}
#[tokio::test]
async fn call_maps_rpc_error_envelope() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/rpc"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"jsonrpc": "2.0",
"id": 1,
"error": {"code": -32002, "message": "workstream not found"},
})))
.mount(&server)
.await;
let client = RpcHttpClient::new(reqwest::Client::new(), server.uri());
let err = client
.call("workstream.get", json!({"id": "missing"}))
.await
.expect_err("must be an error");
match err {
EngineError::Rpc { code, message, .. } => {
assert_eq!(code, -32002);
assert_eq!(message, "workstream not found");
}
other => panic!("expected EngineError::Rpc, got {other:?}"),
}
}
#[tokio::test]
async fn call_maps_transport_failure() {
let client = RpcHttpClient::new(reqwest::Client::new(), "http://127.0.0.1:1".to_string());
let err = client
.call("ping", json!({}))
.await
.expect_err("must be an error");
assert!(matches!(err, EngineError::Transport { .. }));
}
#[tokio::test]
async fn successive_calls_use_distinct_ids() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/rpc"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"jsonrpc": "2.0",
"id": 1,
"result": {},
})))
.mount(&server)
.await;
let client = RpcHttpClient::new(reqwest::Client::new(), server.uri());
client.call("ping", json!({})).await.expect("call 1");
client.call("ping", json!({})).await.expect("call 2");
let requests = server.received_requests().await.expect("received");
assert_eq!(requests.len(), 2);
let ids: Vec<i64> = requests
.iter()
.map(|r| {
let body: Value = r.body_json().expect("body json");
body["id"].as_i64().expect("id")
})
.collect();
assert_ne!(ids[0], ids[1]);
}
}