trusty_code/tui_client/rpc.rs
1//! [`RpcHttpClient`]: a pooled JSON-RPC 2.0 client speaking `POST {base}/rpc`
2//! against a long-lived `tcode serve --http` daemon (issue #3415).
3//!
4//! Why: mirrors `crate::cli_client::stdio::StdioRpcClient`'s role over
5//! STDIO — one place that builds the wire request, sends it, and unwraps the
6//! envelope — but over HTTP against an ALREADY-RUNNING daemon instead of a
7//! per-call spawned child. Reuses the exact same wire types
8//! (`trusty_mcp::{Request, Response}`) `StdioRpcClient` and
9//! `crate::serve::http::rpc_handler` already use, so there is exactly one
10//! `Request`/`Response` shape in this crate regardless of transport.
11//! What: [`RpcHttpClient::call`] mints a monotonic request id, POSTs the
12//! envelope, and unwraps the response into either `Ok(result)` or an
13//! [`EngineError::Rpc`]/[`EngineError::Transport`]. Holds one
14//! `reqwest::Client` for its whole lifetime (pooled keep-alive connections,
15//! DOC-50 §3.4 point 5) — callers needing the SSE routes (`sse.rs`) reuse
16//! the SAME client via [`RpcHttpClient::http`] rather than building a second
17//! one.
18//! Test: `rpc_tests::*` against a `wiremock` mock server.
19
20use std::sync::atomic::{AtomicI64, Ordering};
21
22use serde_json::Value;
23use trusty_mcp::{Request, Response};
24
25use super::error::EngineError;
26
27/// How long a single `POST /rpc` call waits for a response before giving
28/// up. Every method this client calls today (`session.*`, `task.run`,
29/// `workstream.*`) is a fast, synchronous handler — `task.run` reserves its
30/// execution slot and returns immediately rather than blocking on the LLM
31/// run (mirrors `crate::cli_client::stdio::DEFAULT_CALL_TIMEOUT`'s docs) —
32/// so a real hang here means a genuine daemon-side regression, not a slow
33/// but legitimate call.
34pub const DEFAULT_CALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
35
36/// See module docs.
37pub struct RpcHttpClient {
38 http: reqwest::Client,
39 base_url: String,
40 next_id: AtomicI64,
41}
42
43impl RpcHttpClient {
44 /// Build a client targeting `base_url` (no trailing slash), reusing the
45 /// caller-supplied pooled `reqwest::Client`.
46 pub fn new(http: reqwest::Client, base_url: String) -> Self {
47 Self {
48 http,
49 base_url,
50 next_id: AtomicI64::new(1),
51 }
52 }
53
54 /// The daemon base URL this client targets (e.g.
55 /// `http://127.0.0.1:7882`) — callers building SSE URLs
56 /// (`{base}/sessions/{id}/events`) read this rather than duplicating it.
57 pub fn base_url(&self) -> &str {
58 &self.base_url
59 }
60
61 /// The shared pooled HTTP client — callers building their own requests
62 /// (the SSE routes, which aren't JSON-RPC) reuse this rather than
63 /// constructing a second `reqwest::Client` (defeating the connection
64 /// pool).
65 pub fn http(&self) -> &reqwest::Client {
66 &self.http
67 }
68
69 /// Call `method` with `params` against `POST {base_url}/rpc`, waiting
70 /// (bounded by [`DEFAULT_CALL_TIMEOUT`]) for the matching response.
71 ///
72 /// Why: the one call every `session.*`/`task.*`/`workstream.*` RPC in
73 /// this engine goes through.
74 /// What: mints a monotonic id, builds the `Request` envelope, POSTs it,
75 /// decodes the `Response` envelope, and returns `Ok(result)` or maps a
76 /// JSON-RPC error object onto [`EngineError::Rpc`]. A transport-level
77 /// failure (connect/timeout/decode) maps onto [`EngineError::Transport`].
78 /// Test: `rpc_tests::call_returns_result_on_success`,
79 /// `rpc_tests::call_maps_rpc_error_envelope`,
80 /// `rpc_tests::call_maps_transport_failure`.
81 pub async fn call(&self, method: &str, params: Value) -> Result<Value, EngineError> {
82 let id = self.next_id.fetch_add(1, Ordering::Relaxed);
83 let req = Request {
84 jsonrpc: Some("2.0".to_string()),
85 id: Some(serde_json::json!(id)),
86 method: method.to_string(),
87 params: Some(params),
88 };
89 let url = format!("{}/rpc", self.base_url);
90 let resp = self
91 .http
92 .post(&url)
93 .json(&req)
94 .timeout(DEFAULT_CALL_TIMEOUT)
95 .send()
96 .await
97 .map_err(|source| EngineError::Transport {
98 url: url.clone(),
99 source,
100 })?;
101 let body: Response = resp
102 .json()
103 .await
104 .map_err(|source| EngineError::Transport { url, source })?;
105 if let Some(err) = body.error {
106 return Err(EngineError::Rpc {
107 code: err.code,
108 message: err.message,
109 data: err.data,
110 });
111 }
112 Ok(body.result.unwrap_or(Value::Null))
113 }
114}
115
116#[cfg(test)]
117mod rpc_tests {
118 use super::*;
119 use serde_json::json;
120 use wiremock::matchers::{method, path};
121 use wiremock::{Mock, MockServer, ResponseTemplate};
122
123 /// A successful `POST /rpc` call must return the envelope's `result`.
124 #[tokio::test]
125 async fn call_returns_result_on_success() {
126 let server = MockServer::start().await;
127 Mock::given(method("POST"))
128 .and(path("/rpc"))
129 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
130 "jsonrpc": "2.0",
131 "id": 1,
132 "result": {"pong": true},
133 })))
134 .mount(&server)
135 .await;
136
137 let client = RpcHttpClient::new(reqwest::Client::new(), server.uri());
138 let result = client.call("ping", json!({})).await.expect("call");
139 assert_eq!(result, json!({"pong": true}));
140 }
141
142 /// A JSON-RPC error envelope must map onto `EngineError::Rpc`, carrying
143 /// the code/message through verbatim.
144 #[tokio::test]
145 async fn call_maps_rpc_error_envelope() {
146 let server = MockServer::start().await;
147 Mock::given(method("POST"))
148 .and(path("/rpc"))
149 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
150 "jsonrpc": "2.0",
151 "id": 1,
152 "error": {"code": -32002, "message": "workstream not found"},
153 })))
154 .mount(&server)
155 .await;
156
157 let client = RpcHttpClient::new(reqwest::Client::new(), server.uri());
158 let err = client
159 .call("workstream.get", json!({"id": "missing"}))
160 .await
161 .expect_err("must be an error");
162 match err {
163 EngineError::Rpc { code, message, .. } => {
164 assert_eq!(code, -32002);
165 assert_eq!(message, "workstream not found");
166 }
167 other => panic!("expected EngineError::Rpc, got {other:?}"),
168 }
169 }
170
171 /// A transport-level failure (daemon unreachable) must map onto
172 /// `EngineError::Transport`, not panic or silently swallow the error.
173 #[tokio::test]
174 async fn call_maps_transport_failure() {
175 // Nothing is listening on this port — a real connection failure.
176 let client = RpcHttpClient::new(reqwest::Client::new(), "http://127.0.0.1:1".to_string());
177 let err = client
178 .call("ping", json!({}))
179 .await
180 .expect_err("must be an error");
181 assert!(matches!(err, EngineError::Transport { .. }));
182 }
183
184 /// Two calls in sequence must use two DIFFERENT ids — proves the
185 /// monotonic counter actually advances (a daemon matching on id would
186 /// otherwise silently misroute a second in-flight call).
187 #[tokio::test]
188 async fn successive_calls_use_distinct_ids() {
189 let server = MockServer::start().await;
190 Mock::given(method("POST"))
191 .and(path("/rpc"))
192 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
193 "jsonrpc": "2.0",
194 "id": 1,
195 "result": {},
196 })))
197 .mount(&server)
198 .await;
199
200 let client = RpcHttpClient::new(reqwest::Client::new(), server.uri());
201 client.call("ping", json!({})).await.expect("call 1");
202 client.call("ping", json!({})).await.expect("call 2");
203
204 let requests = server.received_requests().await.expect("received");
205 assert_eq!(requests.len(), 2);
206 let ids: Vec<i64> = requests
207 .iter()
208 .map(|r| {
209 let body: Value = r.body_json().expect("body json");
210 body["id"].as_i64().expect("id")
211 })
212 .collect();
213 assert_ne!(ids[0], ids[1]);
214 }
215}