trusty_code/serve/transport.rs
1//! STDIO JSON-RPC transport loop for `tcode serve --stdio` (#2053, #2054).
2//!
3//! Why: matches the ecosystem's line-delimited JSON-RPC-over-stdio framing
4//! — the same convention `trusty-search` (`mcp::stdio::run`) and
5//! `trusty-memory` (`commands::serve_stdio_bridge::run_stdio_bridge`) use,
6//! both built on the shared `trusty_mcp` primitives — while adding
7//! graceful shutdown per the workspace's connection-safe daemon-restart
8//! convention (issue #534): the loop stops accepting new input on SIGTERM/
9//! SIGINT but always finishes whatever request is already in-flight before
10//! returning, and it never crashes on malformed input — a `serde_json`
11//! parse failure becomes a `-32700 Parse error` JSON-RPC response instead of
12//! propagating and killing the process. Shutdown detection itself is the
13//! shared `trusty_common::shutdown_signal()` helper — the exact function
14//! `trusty-memory`'s `run_http_on` and `trusty-search`'s HTTP daemon install
15//! via `axum::serve(...).with_graceful_shutdown(...)` (see
16//! `crate::serve::http::run_http`) — rather than a second, STDIO-specific
17//! signal handler.
18//!
19//! #2054 adds a THIRD `select!` arm: STDIO is a single long-lived
20//! connection for the whole process lifetime, so one
21//! [`ConnectionContext`](crate::jsonrpc::ConnectionContext) is built once
22//! per process and its notify receiver is polled alongside input lines and
23//! the shutdown signal. Whenever `session.attach`'s background forwarder
24//! (`crate::session::registry`) pushes a server-initiated notification, it
25//! is written to stdout interleaved with ordinary request/response lines —
26//! exactly the "stdout: JSON-RPC 2.0 responses + event notifications
27//! (NDJSON)" wire model the vision spec's §4.2 describes.
28//!
29//! What: [`run_stdio_loop`] wires the real `tokio::io::stdin()`/`stdout()`
30//! against a [`Router`]. The generic [`run_loop`] underneath accepts any
31//! `AsyncRead`/`AsyncWrite` pair plus a shutdown future so tests can drive
32//! it over an in-memory pipe without touching real stdio or process signals.
33//! Logging goes to stderr only (via `tracing`) — stdout carries only
34//! JSON-RPC response/notification lines, never log output.
35//!
36//! Test: `transport::tests::*` drive `run_loop` over an in-memory duplex
37//! pipe (successful dispatch, malformed JSON, notification suppression,
38//! EOF exit, shutdown-signal-triggered early exit, and a server-initiated
39//! notification pushed via the connection's notify channel).
40
41use std::future::Future;
42use std::sync::Arc;
43
44use anyhow::Result;
45use serde::Serialize;
46use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader};
47use tokio::sync::mpsc;
48use tracing::info;
49
50use crate::jsonrpc::{ConnectionContext, Router};
51
52/// Read JSON-RPC 2.0 requests line-by-line from stdin, dispatch each through
53/// `router`, and write the response to stdout — interleaved with any
54/// server-initiated notifications pushed via this connection's
55/// [`ConnectionContext`]. Returns on stdin EOF or on receipt of SIGTERM/
56/// SIGINT.
57///
58/// Why: the single entry point `crate::serve::run_stdio` calls once the
59/// router is assembled.
60/// What: thin wrapper over [`run_loop`] binding the real process stdio, a
61/// fresh long-lived [`ConnectionContext`], and the shared
62/// `trusty_common::shutdown_signal()`.
63/// Test: exercised end-to-end (minus real signals/stdio) by `run_loop`'s
64/// tests below.
65pub async fn run_stdio_loop(router: Router) -> Result<()> {
66 let router = Arc::new(router);
67 let (notify_tx, notify_rx) = mpsc::unbounded_channel();
68 let ctx = ConnectionContext::new(notify_tx);
69 run_loop(
70 router,
71 tokio::io::stdin(),
72 tokio::io::stdout(),
73 trusty_common::shutdown_signal(),
74 ctx,
75 notify_rx,
76 )
77 .await
78}
79
80/// Generic version of [`run_stdio_loop`] parameterised over the reader,
81/// writer, shutdown future, and connection context.
82///
83/// Why: lets unit tests substitute an in-memory duplex pipe, a
84/// deterministic shutdown future, and drive the notify channel directly
85/// instead of real stdio/signals/a spawned forwarder.
86/// What: reads newline-delimited JSON one line at a time; blank lines are
87/// skipped; malformed JSON produces a `-32700 Parse error` response;
88/// suppressed responses (notifications received AS a request, e.g. a
89/// client-sent notification) are never written. A third `select!` arm
90/// drains `notify_rx` and writes whatever arrives (already a complete
91/// JSON-RPC object — a response or a server-initiated notification)
92/// verbatim. `select!` is `biased` so shutdown always wins a simultaneous
93/// race against input or a queued notification, guaranteeing prompt
94/// shutdown.
95/// Test: `run_loop_dispatches_and_writes_response`,
96/// `run_loop_malformed_json_returns_parse_error`,
97/// `run_loop_notification_writes_nothing`,
98/// `run_loop_exits_on_eof_when_shutdown_never_fires`,
99/// `run_loop_shutdown_signal_takes_priority_over_pending_input`,
100/// `run_loop_forwards_queued_notifications_to_the_wire`.
101#[allow(clippy::too_many_arguments)]
102async fn run_loop<R, W, Sh>(
103 router: Arc<Router>,
104 reader: R,
105 mut writer: W,
106 shutdown: Sh,
107 ctx: ConnectionContext,
108 mut notify_rx: mpsc::UnboundedReceiver<serde_json::Value>,
109) -> Result<()>
110where
111 R: AsyncRead + Unpin,
112 W: AsyncWrite + Unpin,
113 Sh: Future<Output = ()>,
114{
115 tokio::pin!(shutdown);
116 let mut lines = BufReader::new(reader).lines();
117
118 loop {
119 tokio::select! {
120 biased;
121 () = &mut shutdown => {
122 info!("tcode serve: shutdown signal received, stopping");
123 break;
124 }
125 notification = notify_rx.recv() => {
126 let Some(notification) = notification else {
127 // All senders dropped (should not happen while `ctx` is
128 // alive, but treat it the same as "nothing more to send"
129 // rather than erroring).
130 continue;
131 };
132 write_json_line(&mut writer, ¬ification).await?;
133 }
134 line = lines.next_line() => {
135 let Some(line) = line? else {
136 info!("tcode serve: stdin EOF, stopping");
137 break;
138 };
139 let trimmed = line.trim();
140 if trimmed.is_empty() {
141 continue;
142 }
143 let response = router.dispatch_json(trimmed.as_bytes(), &ctx).await;
144 if response.suppress {
145 continue;
146 }
147 write_json_line(&mut writer, &response).await?;
148 }
149 }
150 }
151 Ok(())
152}
153
154/// Write one JSON-serialisable value as a single NDJSON line and flush.
155///
156/// Why: both ordinary `Response`s and server-initiated notifications
157/// (plain `serde_json::Value`) go out over the same stdout stream — this is
158/// the one place that owns "serialise, newline, flush" for either shape.
159/// Flushing per-line matters for STDIO transports — without it, lines can
160/// sit in a buffer indefinitely when stdout isn't a TTY.
161/// What: serialise, write, `\n`, flush.
162/// Test: covered by every `run_loop_*` test that asserts on written bytes.
163async fn write_json_line<W: AsyncWrite + Unpin, T: Serialize>(
164 writer: &mut W,
165 value: &T,
166) -> Result<()> {
167 let serialised = serde_json::to_string(value)?;
168 writer.write_all(serialised.as_bytes()).await?;
169 writer.write_all(b"\n").await?;
170 writer.flush().await?;
171 Ok(())
172}
173
174#[cfg(test)]
175mod tests {
176 use super::*;
177 use serde_json::json;
178 use tokio::io::AsyncReadExt;
179 use trusty_mcp::error_codes;
180
181 fn router_with_ping() -> Arc<Router> {
182 let mut router = Router::new();
183 router.register(
184 "ping",
185 |_params: serde_json::Value, _ctx: ConnectionContext| async move {
186 Ok(json!({"pong": true}))
187 },
188 );
189 Arc::new(router)
190 }
191
192 /// Build a throwaway context + a pre-drained notify receiver, for tests
193 /// that don't exercise the notification path.
194 fn test_ctx() -> (
195 ConnectionContext,
196 mpsc::UnboundedReceiver<serde_json::Value>,
197 ) {
198 let (tx, rx) = mpsc::unbounded_channel();
199 (ConnectionContext::new(tx), rx)
200 }
201
202 /// A well-formed request must produce exactly one NDJSON response line
203 /// with the handler's result.
204 #[tokio::test]
205 async fn run_loop_dispatches_and_writes_response() {
206 let router = router_with_ping();
207 let (mut input_tx, input_rx) = tokio::io::duplex(4096);
208 let (output_tx, mut output_rx) = tokio::io::duplex(4096);
209 let (ctx, notify_rx) = test_ctx();
210
211 input_tx
212 .write_all(b"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\"}\n")
213 .await
214 .unwrap();
215 drop(input_tx); // EOF after the one line
216
217 run_loop(
218 router,
219 input_rx,
220 output_tx,
221 std::future::pending::<()>(),
222 ctx,
223 notify_rx,
224 )
225 .await
226 .expect("loop must return Ok on EOF");
227
228 let mut out = Vec::new();
229 output_rx.read_to_end(&mut out).await.unwrap();
230 let line = String::from_utf8(out).unwrap();
231 let resp: serde_json::Value = serde_json::from_str(line.trim()).unwrap();
232 assert_eq!(resp["result"], json!({"pong": true}));
233 assert_eq!(resp["id"], 1);
234 }
235
236 /// Malformed JSON must produce a `-32700 Parse error` response, not a
237 /// crash.
238 #[tokio::test]
239 async fn run_loop_malformed_json_returns_parse_error() {
240 let router = router_with_ping();
241 let (mut input_tx, input_rx) = tokio::io::duplex(4096);
242 let (output_tx, mut output_rx) = tokio::io::duplex(4096);
243 let (ctx, notify_rx) = test_ctx();
244
245 input_tx.write_all(b"not json at all\n").await.unwrap();
246 drop(input_tx);
247
248 run_loop(
249 router,
250 input_rx,
251 output_tx,
252 std::future::pending::<()>(),
253 ctx,
254 notify_rx,
255 )
256 .await
257 .expect("loop must return Ok on EOF even after a parse error");
258
259 let mut out = Vec::new();
260 output_rx.read_to_end(&mut out).await.unwrap();
261 let resp: serde_json::Value =
262 serde_json::from_str(String::from_utf8(out).unwrap().trim()).unwrap();
263 assert_eq!(resp["error"]["code"], error_codes::PARSE_ERROR);
264 }
265
266 /// A notification (no `id`) must produce no output line at all.
267 #[tokio::test]
268 async fn run_loop_notification_writes_nothing() {
269 let router = router_with_ping();
270 let (mut input_tx, input_rx) = tokio::io::duplex(4096);
271 let (output_tx, mut output_rx) = tokio::io::duplex(4096);
272 let (ctx, notify_rx) = test_ctx();
273
274 input_tx
275 .write_all(b"{\"jsonrpc\":\"2.0\",\"method\":\"ping\"}\n")
276 .await
277 .unwrap();
278 drop(input_tx);
279
280 run_loop(
281 router,
282 input_rx,
283 output_tx,
284 std::future::pending::<()>(),
285 ctx,
286 notify_rx,
287 )
288 .await
289 .expect("loop must return Ok on EOF");
290
291 let mut out = Vec::new();
292 output_rx.read_to_end(&mut out).await.unwrap();
293 assert!(
294 out.is_empty(),
295 "a notification must not produce a response line"
296 );
297 }
298
299 /// EOF with a shutdown future that never fires must still return `Ok`.
300 #[tokio::test]
301 async fn run_loop_exits_on_eof_when_shutdown_never_fires() {
302 let router = router_with_ping();
303 let (ctx, notify_rx) = test_ctx();
304 let result = run_loop(
305 router,
306 tokio::io::empty(),
307 tokio::io::sink(),
308 std::future::pending::<()>(),
309 ctx,
310 notify_rx,
311 )
312 .await;
313 assert!(result.is_ok(), "loop must return Ok on EOF: {result:?}");
314 }
315
316 /// When the shutdown future is already ready, it must take priority
317 /// over a simultaneously-ready input line (biased `select!`), so the
318 /// loop returns promptly instead of draining all remaining input.
319 #[tokio::test]
320 async fn run_loop_shutdown_signal_takes_priority_over_pending_input() {
321 let router = router_with_ping();
322 let (mut input_tx, input_rx) = tokio::io::duplex(4096);
323 let (output_tx, _output_rx) = tokio::io::duplex(4096);
324 let (ctx, notify_rx) = test_ctx();
325
326 input_tx
327 .write_all(b"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\"}\n")
328 .await
329 .unwrap();
330 drop(input_tx);
331
332 let result = tokio::time::timeout(
333 std::time::Duration::from_secs(5),
334 run_loop(
335 router,
336 input_rx,
337 output_tx,
338 std::future::ready(()),
339 ctx,
340 notify_rx,
341 ),
342 )
343 .await;
344 assert!(
345 result.is_ok(),
346 "loop must return promptly once the shutdown future is ready"
347 );
348 assert!(result.unwrap().is_ok());
349 }
350
351 /// A value pushed onto the connection's notify channel (as
352 /// `session.attach`'s forwarder does) must be written to the wire
353 /// verbatim, interleaved with ordinary request/response traffic.
354 #[tokio::test]
355 async fn run_loop_forwards_queued_notifications_to_the_wire() {
356 let router = router_with_ping();
357 let (_input_tx, input_rx) = tokio::io::duplex(4096);
358 let (output_tx, mut output_rx) = tokio::io::duplex(4096);
359 let (tx, rx) = mpsc::unbounded_channel();
360 let ctx = ConnectionContext::new(tx);
361
362 let notification = json!({
363 "jsonrpc": "2.0",
364 "method": "session.event",
365 "params": {"session_id": "s-1", "event": {"type": "session_input", "input": "hi"}},
366 });
367 ctx.notify.send(notification.clone()).unwrap();
368
369 // Run the loop with a shutdown that fires shortly after — enough
370 // time for the notify arm to win a `select!` iteration and write
371 // the queued line, but bounded so the test can't hang if it doesn't.
372 let shutdown = async { tokio::time::sleep(std::time::Duration::from_millis(100)).await };
373 run_loop(router, input_rx, output_tx, shutdown, ctx, rx)
374 .await
375 .expect("loop must return Ok once shutdown fires");
376
377 let mut out = Vec::new();
378 output_rx.read_to_end(&mut out).await.unwrap();
379 let line: serde_json::Value =
380 serde_json::from_str(String::from_utf8(out).unwrap().trim()).unwrap();
381 assert_eq!(line, notification);
382 }
383}