trusty_code/tui_client/uds_rpc.rs
1//! [`UdsRpcClient`]: the JSON-RPC client `tcode tui` drives the daemon with,
2//! over the daemon's hardened Unix socket (#6637).
3//!
4//! Why: this replaces `RpcHttpClient`, which spoke `POST {base}/rpc` and
5//! carried the #5439 bearer token because a loopback TCP port is reachable by
6//! any process on the machine. The socket is `0600` inside a `0700` directory
7//! and every accepted connection runs a peer-uid check, so there is no
8//! credential to resolve, no `Authorization` header to attach, and no
9//! `TCODE_DAEMON_URL` to discover — the path is
10//! `trusty_common::daemon_addr::daemon_socket_path`, which is the same one
11//! `crate::serve::uds` binds.
12//!
13//! What: [`UdsRpcClient::call`] keeps the exact `(method, params) ->
14//! Result<Value, EngineError>` signature `engine.rs` and `engine_state.rs`
15//! already call, so the transport swap is invisible above this file.
16//! [`UdsRpcClient::open_stream`] is the streaming half that replaces the SSE
17//! reader: one dial per stream, then frames until the server writes its
18//! terminal one.
19//!
20//! **Every call is its own connection**, unlike the pooled `reqwest::Client`
21//! this replaces. That is the transport's shape, not a regression: a UDS
22//! connect is a couple of syscalls against a local inode, with no handshake to
23//! amortise, and `trusty_common::uds::server`'s wire contract is one request
24//! frame per connection.
25//!
26//! Test: `engine_tests::*` for the parts that need no daemon;
27//! `tests/tui_client_engine.rs` drives this against a real socket.
28
29use std::path::{Path, PathBuf};
30use std::sync::atomic::{AtomicI64, Ordering};
31use std::time::Duration;
32
33use serde::de::DeserializeOwned;
34use serde_json::{Value, json};
35use trusty_common::uds::{FramedStream, send_framed_request, send_framed_stream_request};
36use trusty_mcp::Response;
37
38use super::error::EngineError;
39
40/// How long one unary call waits for its response frame.
41///
42/// Every method this client calls (`session.*`, `task.run`, `workstream.*`) is
43/// a fast, synchronous handler — `task.run` reserves its execution slot and
44/// returns rather than blocking on the model — so a hang here means a real
45/// daemon-side regression, not a slow but legitimate call.
46pub const DEFAULT_CALL_TIMEOUT: Duration = Duration::from_secs(15);
47
48/// How long a stream may go without a frame before the reader gives up.
49///
50/// Why fifteen minutes rather than the forty-five seconds the SSE reader used:
51/// axum sent a keep-alive comment roughly every fifteen seconds, so silence on
52/// the wire genuinely meant a dead connection. This transport sends nothing
53/// between frames, so a quiet session — one long tool call, a workstream with
54/// no activity — would be cut by a short budget. A socket whose peer is gone
55/// reports a read failure immediately rather than timing out, so this bounds
56/// one thing: a daemon that accepted the connection and then wedged.
57///
58/// It is what keeps #3494's property — a hung daemon must not hang the client
59/// forever — true on this transport. The HTTP shape of that bug (accepted, but
60/// response headers never sent) has no dial-time analogue here: a UDS connect
61/// against a bound socket either completes at once or fails at once. What
62/// remains is silence after the connection is up, which this bounds and
63/// `session_events_tests::session_stream_silence_is_bounded_not_infinite`
64/// asserts. Timing out is cheap on both streams: `session.events` reconnects
65/// with `after_seq` and loses nothing, `workstream.events` re-subscribes bare.
66pub const STREAM_FRAME_TIMEOUT: Duration = Duration::from_secs(900);
67
68/// See module docs.
69pub struct UdsRpcClient {
70 socket: PathBuf,
71 next_id: AtomicI64,
72 stream_frame_timeout: Duration,
73}
74
75impl UdsRpcClient {
76 /// A client dialling `socket`.
77 pub fn new(socket: impl Into<PathBuf>) -> Self {
78 Self {
79 socket: socket.into(),
80 next_id: AtomicI64::new(1),
81 stream_frame_timeout: STREAM_FRAME_TIMEOUT,
82 }
83 }
84
85 /// Override the per-frame stream budget.
86 ///
87 /// Why: [`STREAM_FRAME_TIMEOUT`] is fifteen minutes, and
88 /// `session_events_tests::session_stream_silence_is_bounded_not_infinite`
89 /// has to observe the budget expire. Spending fifteen real minutes to
90 /// prove a bound exists is not a test; a paused clock cannot help either,
91 /// because the reader is parked on a socket read rather than on a timer.
92 pub fn with_stream_frame_timeout(mut self, timeout: Duration) -> Self {
93 self.stream_frame_timeout = timeout;
94 self
95 }
96
97 /// The socket this client dials — read by callers building an error
98 /// message or a reconnect, never to bypass this client.
99 pub fn socket(&self) -> &Path {
100 &self.socket
101 }
102
103 /// Call `method` with `params`, waiting (bounded by
104 /// [`DEFAULT_CALL_TIMEOUT`]) for the one response frame.
105 ///
106 /// Why: the single call every `session.*`/`task.*`/`workstream.*` RPC in
107 /// this engine goes through.
108 /// What: mints a monotonic id, writes one JSON-RPC frame, and returns
109 /// `Ok(result)` or maps the JSON-RPC error object onto
110 /// [`EngineError::Rpc`]. A dial, write, read or decode failure maps onto
111 /// [`EngineError::Transport`].
112 ///
113 /// # Errors
114 ///
115 /// [`EngineError::Transport`] for a transport failure, [`EngineError::Rpc`]
116 /// for the daemon's own error envelope, [`EngineError::Malformed`] for a
117 /// response carrying neither `result` nor `error`.
118 ///
119 /// Test: `tests/tui_client_engine.rs::tui_engine_end_to_end_with_http_port_closed`.
120 pub async fn call(&self, method: &str, params: Value) -> Result<Value, EngineError> {
121 let request = json!({
122 "jsonrpc": "2.0",
123 "id": self.next_id.fetch_add(1, Ordering::Relaxed),
124 "method": method,
125 "params": params,
126 });
127 let response: Response = send_framed_request(&self.socket, &request, DEFAULT_CALL_TIMEOUT)
128 .await
129 .map_err(|source| EngineError::Transport {
130 socket: self.socket.clone(),
131 source: Box::new(source),
132 })?;
133 match (response.result, response.error) {
134 (Some(result), _) => Ok(result),
135 (None, Some(error)) => Err(EngineError::Rpc {
136 code: error.code,
137 message: error.message,
138 data: error.data,
139 }),
140 (None, None) => Err(EngineError::Malformed(format!(
141 "{method}: response carried neither result nor error"
142 ))),
143 }
144 }
145
146 /// Open a streaming call and return its frame reader.
147 ///
148 /// What: sets the `"stream": true` flag
149 /// `trusty_common::uds::server`'s wire contract negotiates on, and hands
150 /// back a [`FramedStream`] whose per-frame budget is
151 /// [`STREAM_FRAME_TIMEOUT`]. A method that does not stream answers one
152 /// ordinary response frame, which the reader reports as
153 /// `UdsRpcError::NotAStream` rather than decoding as an item.
154 ///
155 /// # Errors
156 ///
157 /// [`EngineError::Transport`] for a dial or write failure. Everything after
158 /// the stream opens is reported per frame, by the reader.
159 ///
160 /// Test: `tests/tui_client_engine.rs::tui_engine_end_to_end_with_http_port_closed`.
161 pub async fn open_stream<T: DeserializeOwned>(
162 &self,
163 method: &str,
164 params: Value,
165 ) -> Result<FramedStream<T>, EngineError> {
166 let request = json!({
167 "jsonrpc": "2.0",
168 "id": self.next_id.fetch_add(1, Ordering::Relaxed),
169 "method": method,
170 "params": params,
171 "stream": true,
172 });
173 send_framed_stream_request(&self.socket, &request, self.stream_frame_timeout)
174 .await
175 .map_err(|source| EngineError::Transport {
176 socket: self.socket.clone(),
177 source: Box::new(source),
178 })
179 }
180}