Skip to main content

trusty_code/jsonrpc/
router.rs

1//! Method-name -> async-handler registry and the JSON-RPC dispatch algorithm.
2//!
3//! Why: the transport loop (`crate::serve::transport`) only knows how to
4//! turn bytes into a `trusty_mcp::Request` and a `Response` back
5//! into bytes; it must not know *which* methods exist. The [`Router`] is
6//! the seam in between: handlers register under a method name once, and
7//! every future ticket that adds a method (`session.*` #2054, `task.*`
8//! #2056, `harness.describe` #2066) does so with one `router.register(...)`
9//! call, never touching the transport or the dispatch algorithm.
10//!
11//! What: [`MethodHandler`] is an object-safe async-handler trait, blanket
12//! implemented for any `Fn(Value, ConnectionContext) -> Future<Output =
13//! Result<Value, RpcError>>` (so plain `async fn(Value, ConnectionContext)
14//! -> Result<Value, RpcError>` items and closures both register directly,
15//! no adapter boilerplate). Every handler receives a
16//! [`ConnectionContext`](super::context::ConnectionContext) — most (`ping`,
17//! `health`, `session.list`, …) ignore it; `session.attach` (#2054) uses it
18//! to push server-initiated notifications back to the calling connection.
19//! Threading it through uniformly keeps one call signature for every
20//! method rather than a second handler trait carved out for streaming
21//! methods. [`Router::dispatch`] implements the JSON-RPC 2.0 error model
22//! end-to-end for methods it knows about:
23//!   - `-32600 Invalid Request` — non-`"2.0"` `jsonrpc` version, or an empty
24//!     method name.
25//!   - `-32601 Method not found` — no handler registered under the name.
26//!   - handler-returned [`RpcError`] (typically `-32602`/`-32603`, or a
27//!     #2054 domain code like `-32007 session_not_found`) is copied onto
28//!     the wire error verbatim, `data` included.
29//!   - `-32700 Parse error` is produced by [`Router::dispatch_json`], not
30//!     [`Router::dispatch`] — the STDIO transport (`crate::serve::transport`,
31//!     one JSON object per line) and the HTTP transport
32//!     (`crate::serve::http`, one JSON object per `POST /rpc` body) both
33//!     receive raw bytes rather than an already-parsed `Request`, and both
34//!     need the exact same "parse or -32700" behaviour. Centralising it here
35//!     means the error message and code can never drift between the two
36//!     wire formats.
37//!
38//! Per JSON-RPC 2.0 §4.1, a request with no `id` is a *notification*: the
39//! server must never reply, even with an error, though the handler (if one
40//! matches) still executes for its side effects. `dispatch` computes the
41//! response normally and then swaps in `Response::suppressed()` at the end
42//! when the original request had no `id`.
43//!
44//! Test: see `tests` below — one case per error code, a notification that
45//! still executes its handler but suppresses the reply, and a successful
46//! round trip.
47
48use std::collections::HashMap;
49use std::future::Future;
50use std::pin::Pin;
51use std::sync::Arc;
52
53use serde_json::Value;
54use trusty_mcp::{Request, Response, error_codes};
55
56use super::context::ConnectionContext;
57use super::error::RpcError;
58
59/// A boxed, pinned future returned by a method handler.
60type HandlerFuture = Pin<Box<dyn Future<Output = Result<Value, RpcError>> + Send>>;
61
62/// Object-safe async handler for one JSON-RPC method.
63///
64/// Why: `Router` stores handlers as trait objects (`Arc<dyn MethodHandler>`)
65/// so methods of different concrete closure/fn types can share one registry.
66/// Async fns are not directly object-safe, hence the `call` -> boxed-future
67/// indirection.
68/// What: implemented for `Self` by the blanket impl below whenever `Self` is
69/// `Fn(Value, ConnectionContext) -> Fut` with `Fut: Future<Output =
70/// Result<Value, RpcError>>` — callers never need to implement this trait
71/// by hand.
72/// Test: exercised indirectly by every `router::tests` case and by
73/// `crate::serve::methods::tests`.
74pub trait MethodHandler: Send + Sync {
75    /// Invoke the handler with the request's `params` (defaulted to `Null`
76    /// when the wire request omitted them) and the calling connection's
77    /// context.
78    fn call(&self, params: Value, ctx: ConnectionContext) -> HandlerFuture;
79}
80
81impl<F, Fut> MethodHandler for F
82where
83    F: Fn(Value, ConnectionContext) -> Fut + Send + Sync,
84    Fut: Future<Output = Result<Value, RpcError>> + Send + 'static,
85{
86    fn call(&self, params: Value, ctx: ConnectionContext) -> HandlerFuture {
87        Box::pin(self(params, ctx))
88    }
89}
90
91/// Method-name -> handler registry and JSON-RPC 2.0 dispatcher.
92///
93/// Why: the single seam between both transports and tcode's business
94/// methods. See the module docs for the extensibility rationale.
95/// What: a thin `HashMap<String, Arc<dyn MethodHandler>>` plus `dispatch`.
96/// Test: `router::tests::*`.
97#[derive(Default)]
98pub struct Router {
99    handlers: HashMap<String, Arc<dyn MethodHandler>>,
100}
101
102impl Router {
103    /// Construct an empty router.
104    ///
105    /// Why: callers assemble a router by registering methods immediately
106    /// after construction (see `crate::serve::build_router`).
107    /// What: returns a `Router` with no registered methods.
108    /// Test: `dispatch_unknown_method_returns_method_not_found` uses a
109    /// router with exactly one registered method to prove unregistered
110    /// names are still rejected.
111    pub fn new() -> Self {
112        Self {
113            handlers: HashMap::new(),
114        }
115    }
116
117    /// Register a method handler under `method`.
118    ///
119    /// Why: the sole way new JSON-RPC methods enter the dispatcher.
120    /// Re-registering the same name replaces the previous handler (last
121    /// write wins) rather than erroring, since duplicate registration is a
122    /// programmer error caught by tests, not a runtime condition to guard.
123    /// What: inserts `handler` into the registry; returns `&mut Self` so
124    /// call sites can chain multiple `.register(...)` calls.
125    /// Test: `dispatch_registered_method_returns_handler_result`.
126    pub fn register(
127        &mut self,
128        method: impl Into<String>,
129        handler: impl MethodHandler + 'static,
130    ) -> &mut Self {
131        self.handlers.insert(method.into(), Arc::new(handler));
132        self
133    }
134
135    /// Every registered method name, sorted.
136    ///
137    /// Why (#6637): `crate::serve::uds::JsonRpcFallback` mounts this whole
138    /// table behind one catch-all rather than re-registering each name, so
139    /// nothing else could say what that catch-all actually covers.
140    /// `uds_tests::fallback_dispatches_every_jsonrpc_router_method` reads the
141    /// list from here and calls each name over a real socket, which is what
142    /// turns "the fallback is mounted" into something a test can check.
143    /// What: the keys of the handler map, sorted so a failure names the same
144    /// method on every run.
145    /// Test: `uds_tests::fallback_dispatches_every_jsonrpc_router_method`.
146    pub fn method_names(&self) -> Vec<&str> {
147        let mut names: Vec<&str> = self.handlers.keys().map(String::as_str).collect();
148        names.sort_unstable();
149        names
150    }
151
152    /// Dispatch a parsed JSON-RPC request, returning the response to write
153    /// back on the wire (or a suppressed response for notifications).
154    ///
155    /// Why: the single entry point each transport calls per request. See
156    /// the module docs for the full error-code contract.
157    /// What: validates the envelope, looks up the handler, awaits it with
158    /// `ctx` in hand, and maps the result onto a `Response` — suppressing
159    /// the reply entirely when `req.id` was absent (a notification).
160    /// Test: `router::tests::*` (one case per code path).
161    pub async fn dispatch(&self, req: Request, ctx: &ConnectionContext) -> Response {
162        let is_notification = req.id.is_none();
163        let response = self.dispatch_replyable(&req, ctx).await;
164        if is_notification {
165            Response::suppressed()
166        } else {
167            response
168        }
169    }
170
171    /// Compute the reply for `req` as if it were not a notification.
172    ///
173    /// Why: split out of `dispatch` so notification suppression is a single
174    /// decision made once, after the (possibly side-effecting) handler has
175    /// already run — matching JSON-RPC 2.0 §4.1's "notifications still
176    /// execute, they just never get a reply" semantics.
177    /// What: envelope validation, method lookup, handler invocation, result
178    /// mapping. Never suppresses.
179    /// Test: covered transitively via `dispatch`'s tests.
180    async fn dispatch_replyable(&self, req: &Request, ctx: &ConnectionContext) -> Response {
181        let id = req.id.clone();
182
183        if let Some(version) = &req.jsonrpc
184            && version != "2.0"
185        {
186            return Response::err(
187                id,
188                error_codes::INVALID_REQUEST,
189                format!("unsupported jsonrpc version \"{version}\" (expected \"2.0\")"),
190            );
191        }
192        if req.method.trim().is_empty() {
193            return Response::err(id, error_codes::INVALID_REQUEST, "method must not be empty");
194        }
195
196        let Some(handler) = self.handlers.get(req.method.as_str()) else {
197            return Response::err(
198                id,
199                error_codes::METHOD_NOT_FOUND,
200                format!("method not found: {}", req.method),
201            );
202        };
203
204        let params = req.params.clone().unwrap_or(Value::Null);
205        match handler.call(params, ctx.clone()).await {
206            Ok(result) => Response::ok(id, result),
207            Err(e) => {
208                let mut resp = Response::err(id, e.code, e.message);
209                if let Some(err) = resp.error.as_mut() {
210                    err.data = e.data;
211                }
212                resp
213            }
214        }
215    }
216
217    /// Parse `raw` as a single JSON-RPC request and dispatch it, mapping a
218    /// JSON parse failure onto `-32700 Parse error` instead of propagating.
219    ///
220    /// Why: both wire transports (STDIO lines, HTTP request bodies) receive
221    /// raw bytes rather than an already-parsed `Request`; this is the one
222    /// place "parse or -32700" is implemented, so the message/code can never
223    /// drift between them. See the module docs for the full rationale.
224    /// What: `serde_json::from_slice::<Request>(raw)` then [`Self::dispatch`].
225    /// On parse failure, returns `Response::err(None, error_codes::PARSE_ERROR,
226    /// ...)` without ever invoking a handler — the request `id` is
227    /// unrecoverable from malformed JSON, so the response carries a `null`
228    /// id per the JSON-RPC 2.0 spec.
229    /// Test: `dispatch_json_valid_request_dispatches`,
230    /// `dispatch_json_malformed_bytes_return_parse_error`.
231    pub async fn dispatch_json(&self, raw: &[u8], ctx: &ConnectionContext) -> Response {
232        match serde_json::from_slice::<Request>(raw) {
233            Ok(req) => self.dispatch(req, ctx).await,
234            Err(e) => Response::err(
235                None,
236                error_codes::PARSE_ERROR,
237                format!("invalid JSON-RPC: {e}"),
238            ),
239        }
240    }
241}
242
243#[cfg(test)]
244mod tests {
245    use super::*;
246    use serde_json::json;
247    use std::sync::atomic::{AtomicBool, Ordering};
248    use tokio::sync::mpsc;
249
250    fn req(id: Option<Value>, method: &str, params: Option<Value>) -> Request {
251        Request {
252            jsonrpc: Some("2.0".to_string()),
253            id,
254            method: method.to_string(),
255            params,
256        }
257    }
258
259    /// A throwaway context for tests that don't care about notifications.
260    fn test_ctx() -> ConnectionContext {
261        let (tx, _rx) = mpsc::unbounded_channel();
262        ConnectionContext::new(tx)
263    }
264
265    /// A registered method must return its handler's `Ok` result verbatim.
266    #[tokio::test]
267    async fn dispatch_registered_method_returns_handler_result() {
268        let mut router = Router::new();
269        router.register(
270            "ping",
271            |_params: Value, _ctx: ConnectionContext| async move { Ok(json!({"pong": true})) },
272        );
273
274        let resp = router
275            .dispatch(req(Some(json!(1)), "ping", None), &test_ctx())
276            .await;
277        assert!(resp.error.is_none(), "expected ok, got {:?}", resp.error);
278        assert_eq!(resp.result, Some(json!({"pong": true})));
279        assert_eq!(resp.id, Some(json!(1)));
280        assert!(!resp.suppress);
281    }
282
283    /// Unregistered methods must return `-32601 Method not found`.
284    #[tokio::test]
285    async fn dispatch_unknown_method_returns_method_not_found() {
286        let mut router = Router::new();
287        router.register(
288            "ping",
289            |_params: Value, _ctx: ConnectionContext| async move { Ok(json!({})) },
290        );
291
292        let resp = router
293            .dispatch(req(Some(json!(2)), "definitely_missing", None), &test_ctx())
294            .await;
295        let err = resp.error.expect("expected an error response");
296        assert_eq!(err.code, error_codes::METHOD_NOT_FOUND);
297        assert!(err.message.contains("definitely_missing"));
298    }
299
300    /// A non-`"2.0"` `jsonrpc` field must return `-32600 Invalid Request`.
301    #[tokio::test]
302    async fn dispatch_wrong_jsonrpc_version_returns_invalid_request() {
303        let router = Router::new();
304        let mut r = req(Some(json!(3)), "ping", None);
305        r.jsonrpc = Some("1.0".to_string());
306
307        let resp = router.dispatch(r, &test_ctx()).await;
308        let err = resp.error.expect("expected an error response");
309        assert_eq!(err.code, error_codes::INVALID_REQUEST);
310    }
311
312    /// An empty method name must return `-32600 Invalid Request`.
313    #[tokio::test]
314    async fn dispatch_empty_method_returns_invalid_request() {
315        let router = Router::new();
316        let resp = router
317            .dispatch(req(Some(json!(4)), "", None), &test_ctx())
318            .await;
319        let err = resp.error.expect("expected an error response");
320        assert_eq!(err.code, error_codes::INVALID_REQUEST);
321    }
322
323    /// A handler-returned `RpcError` must be copied onto the wire error,
324    /// `data` included.
325    #[tokio::test]
326    async fn dispatch_handler_error_maps_to_response_error() {
327        let mut router = Router::new();
328        router.register(
329            "boom",
330            |_params: Value, _ctx: ConnectionContext| async move {
331                Err(RpcError::invalid_params("bad field").with_data(json!({"field": "name"})))
332            },
333        );
334
335        let resp = router
336            .dispatch(req(Some(json!(5)), "boom", None), &test_ctx())
337            .await;
338        let err = resp.error.expect("expected an error response");
339        assert_eq!(err.code, error_codes::INVALID_PARAMS);
340        assert_eq!(err.message, "bad field");
341        assert_eq!(err.data, Some(json!({"field": "name"})));
342    }
343
344    /// A notification (no `id`) must still execute its handler's side
345    /// effect but the reply must be suppressed.
346    #[tokio::test]
347    async fn dispatch_notification_executes_handler_but_suppresses_reply() {
348        static RAN: AtomicBool = AtomicBool::new(false);
349        let mut router = Router::new();
350        router.register(
351            "notify_me",
352            |_params: Value, _ctx: ConnectionContext| async move {
353                RAN.store(true, Ordering::SeqCst);
354                Ok(json!({}))
355            },
356        );
357
358        let resp = router
359            .dispatch(req(None, "notify_me", None), &test_ctx())
360            .await;
361        assert!(resp.suppress, "notifications must suppress the reply");
362        assert!(
363            RAN.load(Ordering::SeqCst),
364            "notification handler must still run"
365        );
366    }
367
368    /// `params` must default to `Null` when the wire request omits them.
369    #[tokio::test]
370    async fn dispatch_missing_params_defaults_to_null() {
371        let mut router = Router::new();
372        router.register(
373            "echo_params",
374            |params: Value, _ctx: ConnectionContext| async move { Ok(params) },
375        );
376
377        let resp = router
378            .dispatch(req(Some(json!(6)), "echo_params", None), &test_ctx())
379            .await;
380        assert_eq!(resp.result, Some(Value::Null));
381    }
382
383    /// `dispatch_json` on well-formed bytes must behave exactly like
384    /// `dispatch` on the parsed request.
385    #[tokio::test]
386    async fn dispatch_json_valid_request_dispatches() {
387        let mut router = Router::new();
388        router.register(
389            "ping",
390            |_params: Value, _ctx: ConnectionContext| async move { Ok(json!({"pong": true})) },
391        );
392
393        let raw = br#"{"jsonrpc":"2.0","id":1,"method":"ping"}"#;
394        let resp = router.dispatch_json(raw, &test_ctx()).await;
395        assert_eq!(resp.result, Some(json!({"pong": true})));
396    }
397
398    /// Malformed bytes must map to `-32700 Parse error`, not a panic.
399    #[tokio::test]
400    async fn dispatch_json_malformed_bytes_return_parse_error() {
401        let router = Router::new();
402        let resp = router.dispatch_json(b"not json at all", &test_ctx()).await;
403        let err = resp.error.expect("expected a parse error");
404        assert_eq!(err.code, error_codes::PARSE_ERROR);
405    }
406
407    /// The context passed to `dispatch` must be the exact one the handler
408    /// receives (proven by round-tripping a value through its notify sender).
409    #[tokio::test]
410    async fn dispatch_passes_the_given_context_to_the_handler() {
411        let mut router = Router::new();
412        router.register(
413            "push_via_ctx",
414            |_params: Value, ctx: ConnectionContext| async move {
415                let _ = ctx.notify.send(json!({"pushed": true}));
416                Ok(json!({}))
417            },
418        );
419
420        let (tx, mut rx) = mpsc::unbounded_channel();
421        let ctx = ConnectionContext::new(tx);
422        let _ = router
423            .dispatch(req(Some(json!(7)), "push_via_ctx", None), &ctx)
424            .await;
425        assert_eq!(rx.try_recv().unwrap(), json!({"pushed": true}));
426    }
427}