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 credential: Option<String>,
41 next_id: AtomicI64,
42}
43
44impl RpcHttpClient {
45 /// Build a client targeting `base_url` (no trailing slash), reusing the
46 /// caller-supplied pooled `reqwest::Client`.
47 ///
48 /// #5439: resolves the daemon credential for `base_url` once, here, rather
49 /// than at each request — `daemon_credential_for` is where the "never send
50 /// the local token off loopback" rule lives, and resolving it once means a
51 /// later request site cannot bypass it by reading the token itself.
52 pub fn new(http: reqwest::Client, base_url: String) -> Self {
53 let credential = super::discovery::daemon_credential_for(&base_url);
54 Self {
55 http,
56 base_url,
57 credential,
58 next_id: AtomicI64::new(1),
59 }
60 }
61
62 /// The credential to present to this daemon, if any.
63 ///
64 /// Why: the SSE readers (`engine_state::pump_session_events`,
65 /// `workstream_subscription`) build their own `GET`s against
66 /// [`RpcHttpClient::http`] and must attach the SAME credential this client
67 /// resolved — reading it independently would duplicate the loopback gate.
68 /// Test: `rpc_tests::call_sends_the_bearer_credential`.
69 pub fn credential(&self) -> Option<&str> {
70 self.credential.as_deref()
71 }
72
73 /// Attach this client's credential to `req`, if it has one.
74 ///
75 /// What: sets `Authorization: Bearer <token>`; a client with no credential
76 /// sends no header and receives the daemon's `401`, which surfaces as an
77 /// ordinary transport-level failure rather than a special case.
78 /// Test: `rpc_tests::call_sends_the_bearer_credential`,
79 /// `rpc_tests::call_sends_no_header_without_a_credential`.
80 pub fn authorize(&self, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
81 match &self.credential {
82 Some(token) => req.bearer_auth(token),
83 None => req,
84 }
85 }
86
87 /// The daemon base URL this client targets (e.g.
88 /// `http://127.0.0.1:7882`) — callers building SSE URLs
89 /// (`{base}/sessions/{id}/events`) read this rather than duplicating it.
90 pub fn base_url(&self) -> &str {
91 &self.base_url
92 }
93
94 /// The shared pooled HTTP client — callers building their own requests
95 /// (the SSE routes, which aren't JSON-RPC) reuse this rather than
96 /// constructing a second `reqwest::Client` (defeating the connection
97 /// pool).
98 pub fn http(&self) -> &reqwest::Client {
99 &self.http
100 }
101
102 /// Call `method` with `params` against `POST {base_url}/rpc`, waiting
103 /// (bounded by [`DEFAULT_CALL_TIMEOUT`]) for the matching response.
104 ///
105 /// Why: the one call every `session.*`/`task.*`/`workstream.*` RPC in
106 /// this engine goes through.
107 /// What: mints a monotonic id, builds the `Request` envelope, POSTs it,
108 /// decodes the `Response` envelope, and returns `Ok(result)` or maps a
109 /// JSON-RPC error object onto [`EngineError::Rpc`]. A transport-level
110 /// failure (connect/timeout/decode) maps onto [`EngineError::Transport`].
111 /// Test: `rpc_tests::call_returns_result_on_success`,
112 /// `rpc_tests::call_maps_rpc_error_envelope`,
113 /// `rpc_tests::call_maps_transport_failure`.
114 pub async fn call(&self, method: &str, params: Value) -> Result<Value, EngineError> {
115 let id = self.next_id.fetch_add(1, Ordering::Relaxed);
116 let req = Request {
117 jsonrpc: Some("2.0".to_string()),
118 id: Some(serde_json::json!(id)),
119 method: method.to_string(),
120 params: Some(params),
121 };
122 let url = format!("{}/rpc", self.base_url);
123 let resp = self
124 .authorize(self.http.post(&url))
125 .json(&req)
126 .timeout(DEFAULT_CALL_TIMEOUT)
127 .send()
128 .await
129 .map_err(|source| EngineError::Transport {
130 url: url.clone(),
131 source,
132 })?;
133 let body: Response = resp
134 .json()
135 .await
136 .map_err(|source| EngineError::Transport { url, source })?;
137 if let Some(err) = body.error {
138 return Err(EngineError::Rpc {
139 code: err.code,
140 message: err.message,
141 data: err.data,
142 });
143 }
144 Ok(body.result.unwrap_or(Value::Null))
145 }
146}
147
148#[cfg(test)]
149mod rpc_tests {
150 use super::*;
151 use serde_json::json;
152 use wiremock::matchers::{header, method, path};
153 use wiremock::{Mock, MockServer, ResponseTemplate};
154
155 /// #5439: the daemon's every route requires a credential, so the client's
156 /// `POST /rpc` must carry one — a client that forgot it would see `401`
157 /// on every call.
158 ///
159 /// `RpcHttpClient::new` resolves the credential from the environment or
160 /// the token file, neither of which a test may rely on, so this drives
161 /// [`RpcHttpClient::authorize`] against a client built with an explicit
162 /// credential and asserts the header on the wire.
163 #[tokio::test]
164 async fn call_sends_the_bearer_credential() {
165 let server = MockServer::start().await;
166 Mock::given(method("POST"))
167 .and(path("/rpc"))
168 .and(header("authorization", "Bearer test-credential"))
169 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
170 "jsonrpc": "2.0",
171 "id": 1,
172 "result": {"pong": true},
173 })))
174 .mount(&server)
175 .await;
176
177 let mut client = RpcHttpClient::new(reqwest::Client::new(), server.uri());
178 client.credential = Some("test-credential".to_string());
179 assert_eq!(client.credential(), Some("test-credential"));
180 let result = client.call("ping", json!({})).await.expect("call");
181 assert_eq!(result, json!({"pong": true}));
182 }
183
184 /// A client with no credential must send NO `Authorization` header rather
185 /// than an empty or placeholder one — an empty bearer would be a
186 /// malformed credential the daemon rejects with a confusing shape.
187 #[tokio::test]
188 async fn call_sends_no_header_without_a_credential() {
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": {"pong": true},
196 })))
197 .mount(&server)
198 .await;
199
200 let mut client = RpcHttpClient::new(reqwest::Client::new(), server.uri());
201 client.credential = None;
202 client.call("ping", json!({})).await.expect("call");
203
204 let requests = server
205 .received_requests()
206 .await
207 .expect("wiremock records requests");
208 assert_eq!(requests.len(), 1);
209 assert!(
210 requests[0].headers.get("authorization").is_none(),
211 "a credential-less client must send no Authorization header"
212 );
213 }
214
215 /// A successful `POST /rpc` call must return the envelope's `result`.
216 #[tokio::test]
217 async fn call_returns_result_on_success() {
218 let server = MockServer::start().await;
219 Mock::given(method("POST"))
220 .and(path("/rpc"))
221 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
222 "jsonrpc": "2.0",
223 "id": 1,
224 "result": {"pong": true},
225 })))
226 .mount(&server)
227 .await;
228
229 let client = RpcHttpClient::new(reqwest::Client::new(), server.uri());
230 let result = client.call("ping", json!({})).await.expect("call");
231 assert_eq!(result, json!({"pong": true}));
232 }
233
234 /// A JSON-RPC error envelope must map onto `EngineError::Rpc`, carrying
235 /// the code/message through verbatim.
236 #[tokio::test]
237 async fn call_maps_rpc_error_envelope() {
238 let server = MockServer::start().await;
239 Mock::given(method("POST"))
240 .and(path("/rpc"))
241 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
242 "jsonrpc": "2.0",
243 "id": 1,
244 "error": {"code": -32002, "message": "workstream not found"},
245 })))
246 .mount(&server)
247 .await;
248
249 let client = RpcHttpClient::new(reqwest::Client::new(), server.uri());
250 let err = client
251 .call("workstream.get", json!({"id": "missing"}))
252 .await
253 .expect_err("must be an error");
254 match err {
255 EngineError::Rpc { code, message, .. } => {
256 assert_eq!(code, -32002);
257 assert_eq!(message, "workstream not found");
258 }
259 other => panic!("expected EngineError::Rpc, got {other:?}"),
260 }
261 }
262
263 /// A transport-level failure (daemon unreachable) must map onto
264 /// `EngineError::Transport`, not panic or silently swallow the error.
265 #[tokio::test]
266 async fn call_maps_transport_failure() {
267 // Nothing is listening on this port — a real connection failure.
268 let client = RpcHttpClient::new(reqwest::Client::new(), "http://127.0.0.1:1".to_string());
269 let err = client
270 .call("ping", json!({}))
271 .await
272 .expect_err("must be an error");
273 assert!(matches!(err, EngineError::Transport { .. }));
274 }
275
276 /// Two calls in sequence must use two DIFFERENT ids — proves the
277 /// monotonic counter actually advances (a daemon matching on id would
278 /// otherwise silently misroute a second in-flight call).
279 #[tokio::test]
280 async fn successive_calls_use_distinct_ids() {
281 let server = MockServer::start().await;
282 Mock::given(method("POST"))
283 .and(path("/rpc"))
284 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
285 "jsonrpc": "2.0",
286 "id": 1,
287 "result": {},
288 })))
289 .mount(&server)
290 .await;
291
292 let client = RpcHttpClient::new(reqwest::Client::new(), server.uri());
293 client.call("ping", json!({})).await.expect("call 1");
294 client.call("ping", json!({})).await.expect("call 2");
295
296 let requests = server.received_requests().await.expect("received");
297 assert_eq!(requests.len(), 2);
298 let ids: Vec<i64> = requests
299 .iter()
300 .map(|r| {
301 let body: Value = r.body_json().expect("body json");
302 body["id"].as_i64().expect("id")
303 })
304 .collect();
305 assert_ne!(ids[0], ids[1]);
306 }
307}