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_common::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_common::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    /// Dispatch a parsed JSON-RPC request, returning the response to write
136    /// back on the wire (or a suppressed response for notifications).
137    ///
138    /// Why: the single entry point each transport calls per request. See
139    /// the module docs for the full error-code contract.
140    /// What: validates the envelope, looks up the handler, awaits it with
141    /// `ctx` in hand, and maps the result onto a `Response` — suppressing
142    /// the reply entirely when `req.id` was absent (a notification).
143    /// Test: `router::tests::*` (one case per code path).
144    pub async fn dispatch(&self, req: Request, ctx: &ConnectionContext) -> Response {
145        let is_notification = req.id.is_none();
146        let response = self.dispatch_replyable(&req, ctx).await;
147        if is_notification {
148            Response::suppressed()
149        } else {
150            response
151        }
152    }
153
154    /// Compute the reply for `req` as if it were not a notification.
155    ///
156    /// Why: split out of `dispatch` so notification suppression is a single
157    /// decision made once, after the (possibly side-effecting) handler has
158    /// already run — matching JSON-RPC 2.0 §4.1's "notifications still
159    /// execute, they just never get a reply" semantics.
160    /// What: envelope validation, method lookup, handler invocation, result
161    /// mapping. Never suppresses.
162    /// Test: covered transitively via `dispatch`'s tests.
163    async fn dispatch_replyable(&self, req: &Request, ctx: &ConnectionContext) -> Response {
164        let id = req.id.clone();
165
166        if let Some(version) = &req.jsonrpc
167            && version != "2.0"
168        {
169            return Response::err(
170                id,
171                error_codes::INVALID_REQUEST,
172                format!("unsupported jsonrpc version \"{version}\" (expected \"2.0\")"),
173            );
174        }
175        if req.method.trim().is_empty() {
176            return Response::err(id, error_codes::INVALID_REQUEST, "method must not be empty");
177        }
178
179        let Some(handler) = self.handlers.get(req.method.as_str()) else {
180            return Response::err(
181                id,
182                error_codes::METHOD_NOT_FOUND,
183                format!("method not found: {}", req.method),
184            );
185        };
186
187        let params = req.params.clone().unwrap_or(Value::Null);
188        match handler.call(params, ctx.clone()).await {
189            Ok(result) => Response::ok(id, result),
190            Err(e) => {
191                let mut resp = Response::err(id, e.code, e.message);
192                if let Some(err) = resp.error.as_mut() {
193                    err.data = e.data;
194                }
195                resp
196            }
197        }
198    }
199
200    /// Parse `raw` as a single JSON-RPC request and dispatch it, mapping a
201    /// JSON parse failure onto `-32700 Parse error` instead of propagating.
202    ///
203    /// Why: both wire transports (STDIO lines, HTTP request bodies) receive
204    /// raw bytes rather than an already-parsed `Request`; this is the one
205    /// place "parse or -32700" is implemented, so the message/code can never
206    /// drift between them. See the module docs for the full rationale.
207    /// What: `serde_json::from_slice::<Request>(raw)` then [`Self::dispatch`].
208    /// On parse failure, returns `Response::err(None, error_codes::PARSE_ERROR,
209    /// ...)` without ever invoking a handler — the request `id` is
210    /// unrecoverable from malformed JSON, so the response carries a `null`
211    /// id per the JSON-RPC 2.0 spec.
212    /// Test: `dispatch_json_valid_request_dispatches`,
213    /// `dispatch_json_malformed_bytes_return_parse_error`.
214    pub async fn dispatch_json(&self, raw: &[u8], ctx: &ConnectionContext) -> Response {
215        match serde_json::from_slice::<Request>(raw) {
216            Ok(req) => self.dispatch(req, ctx).await,
217            Err(e) => Response::err(
218                None,
219                error_codes::PARSE_ERROR,
220                format!("invalid JSON-RPC: {e}"),
221            ),
222        }
223    }
224}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229    use serde_json::json;
230    use std::sync::atomic::{AtomicBool, Ordering};
231    use tokio::sync::mpsc;
232
233    fn req(id: Option<Value>, method: &str, params: Option<Value>) -> Request {
234        Request {
235            jsonrpc: Some("2.0".to_string()),
236            id,
237            method: method.to_string(),
238            params,
239        }
240    }
241
242    /// A throwaway context for tests that don't care about notifications.
243    fn test_ctx() -> ConnectionContext {
244        let (tx, _rx) = mpsc::unbounded_channel();
245        ConnectionContext::new(tx)
246    }
247
248    /// A registered method must return its handler's `Ok` result verbatim.
249    #[tokio::test]
250    async fn dispatch_registered_method_returns_handler_result() {
251        let mut router = Router::new();
252        router.register(
253            "ping",
254            |_params: Value, _ctx: ConnectionContext| async move { Ok(json!({"pong": true})) },
255        );
256
257        let resp = router
258            .dispatch(req(Some(json!(1)), "ping", None), &test_ctx())
259            .await;
260        assert!(resp.error.is_none(), "expected ok, got {:?}", resp.error);
261        assert_eq!(resp.result, Some(json!({"pong": true})));
262        assert_eq!(resp.id, Some(json!(1)));
263        assert!(!resp.suppress);
264    }
265
266    /// Unregistered methods must return `-32601 Method not found`.
267    #[tokio::test]
268    async fn dispatch_unknown_method_returns_method_not_found() {
269        let mut router = Router::new();
270        router.register(
271            "ping",
272            |_params: Value, _ctx: ConnectionContext| async move { Ok(json!({})) },
273        );
274
275        let resp = router
276            .dispatch(req(Some(json!(2)), "definitely_missing", None), &test_ctx())
277            .await;
278        let err = resp.error.expect("expected an error response");
279        assert_eq!(err.code, error_codes::METHOD_NOT_FOUND);
280        assert!(err.message.contains("definitely_missing"));
281    }
282
283    /// A non-`"2.0"` `jsonrpc` field must return `-32600 Invalid Request`.
284    #[tokio::test]
285    async fn dispatch_wrong_jsonrpc_version_returns_invalid_request() {
286        let router = Router::new();
287        let mut r = req(Some(json!(3)), "ping", None);
288        r.jsonrpc = Some("1.0".to_string());
289
290        let resp = router.dispatch(r, &test_ctx()).await;
291        let err = resp.error.expect("expected an error response");
292        assert_eq!(err.code, error_codes::INVALID_REQUEST);
293    }
294
295    /// An empty method name must return `-32600 Invalid Request`.
296    #[tokio::test]
297    async fn dispatch_empty_method_returns_invalid_request() {
298        let router = Router::new();
299        let resp = router
300            .dispatch(req(Some(json!(4)), "", None), &test_ctx())
301            .await;
302        let err = resp.error.expect("expected an error response");
303        assert_eq!(err.code, error_codes::INVALID_REQUEST);
304    }
305
306    /// A handler-returned `RpcError` must be copied onto the wire error,
307    /// `data` included.
308    #[tokio::test]
309    async fn dispatch_handler_error_maps_to_response_error() {
310        let mut router = Router::new();
311        router.register(
312            "boom",
313            |_params: Value, _ctx: ConnectionContext| async move {
314                Err(RpcError::invalid_params("bad field").with_data(json!({"field": "name"})))
315            },
316        );
317
318        let resp = router
319            .dispatch(req(Some(json!(5)), "boom", None), &test_ctx())
320            .await;
321        let err = resp.error.expect("expected an error response");
322        assert_eq!(err.code, error_codes::INVALID_PARAMS);
323        assert_eq!(err.message, "bad field");
324        assert_eq!(err.data, Some(json!({"field": "name"})));
325    }
326
327    /// A notification (no `id`) must still execute its handler's side
328    /// effect but the reply must be suppressed.
329    #[tokio::test]
330    async fn dispatch_notification_executes_handler_but_suppresses_reply() {
331        static RAN: AtomicBool = AtomicBool::new(false);
332        let mut router = Router::new();
333        router.register(
334            "notify_me",
335            |_params: Value, _ctx: ConnectionContext| async move {
336                RAN.store(true, Ordering::SeqCst);
337                Ok(json!({}))
338            },
339        );
340
341        let resp = router
342            .dispatch(req(None, "notify_me", None), &test_ctx())
343            .await;
344        assert!(resp.suppress, "notifications must suppress the reply");
345        assert!(
346            RAN.load(Ordering::SeqCst),
347            "notification handler must still run"
348        );
349    }
350
351    /// `params` must default to `Null` when the wire request omits them.
352    #[tokio::test]
353    async fn dispatch_missing_params_defaults_to_null() {
354        let mut router = Router::new();
355        router.register(
356            "echo_params",
357            |params: Value, _ctx: ConnectionContext| async move { Ok(params) },
358        );
359
360        let resp = router
361            .dispatch(req(Some(json!(6)), "echo_params", None), &test_ctx())
362            .await;
363        assert_eq!(resp.result, Some(Value::Null));
364    }
365
366    /// `dispatch_json` on well-formed bytes must behave exactly like
367    /// `dispatch` on the parsed request.
368    #[tokio::test]
369    async fn dispatch_json_valid_request_dispatches() {
370        let mut router = Router::new();
371        router.register(
372            "ping",
373            |_params: Value, _ctx: ConnectionContext| async move { Ok(json!({"pong": true})) },
374        );
375
376        let raw = br#"{"jsonrpc":"2.0","id":1,"method":"ping"}"#;
377        let resp = router.dispatch_json(raw, &test_ctx()).await;
378        assert_eq!(resp.result, Some(json!({"pong": true})));
379    }
380
381    /// Malformed bytes must map to `-32700 Parse error`, not a panic.
382    #[tokio::test]
383    async fn dispatch_json_malformed_bytes_return_parse_error() {
384        let router = Router::new();
385        let resp = router.dispatch_json(b"not json at all", &test_ctx()).await;
386        let err = resp.error.expect("expected a parse error");
387        assert_eq!(err.code, error_codes::PARSE_ERROR);
388    }
389
390    /// The context passed to `dispatch` must be the exact one the handler
391    /// receives (proven by round-tripping a value through its notify sender).
392    #[tokio::test]
393    async fn dispatch_passes_the_given_context_to_the_handler() {
394        let mut router = Router::new();
395        router.register(
396            "push_via_ctx",
397            |_params: Value, ctx: ConnectionContext| async move {
398                let _ = ctx.notify.send(json!({"pushed": true}));
399                Ok(json!({}))
400            },
401        );
402
403        let (tx, mut rx) = mpsc::unbounded_channel();
404        let ctx = ConnectionContext::new(tx);
405        let _ = router
406            .dispatch(req(Some(json!(7)), "push_via_ctx", None), &ctx)
407            .await;
408        assert_eq!(rx.try_recv().unwrap(), json!({"pushed": true}));
409    }
410}