Skip to main content

rpc_io/
router.rs

1//! [`Router`]: which handler answers which method, and what a handler gets:
2//! [`Params`] and a [`Context`]. [`Event`]s report what the endpoint did on
3//! its own.
4
5use std::{
6    collections::BTreeMap,
7    fmt,
8    sync::{Arc, OnceLock},
9    time::Duration,
10};
11
12use jsonx_lib::{Parser, Value};
13
14use crate::{
15    error::Error,
16    error_object::ErrorObject,
17    framing::FrameError,
18    handles::{Call, Peer, Responder},
19    id::Id,
20    link::{Link, Scope, Turn},
21    raw::{Json, Raw},
22};
23
24/// A request handler. The `String` is a buffer the endpoint keeps for it to
25/// encode a result into (and borrow it from) instead of allocating one.
26pub(crate) type RequestFn<S> = Box<
27    dyn for<'b> FnMut(
28            &mut S,
29            Params<'_>,
30            &mut Context<'_>,
31            &'b mut String,
32        ) -> Result<Json<'b>, ErrorObject>
33        + Send,
34>;
35pub(crate) type DeferredFn<S> =
36    Box<dyn FnMut(&mut S, Params<'_>, &mut Context<'_>, Responder) + Send>;
37/// A notification handler; `Err` when it could not read its params (a typed
38/// handler), which is reported, not answered.
39pub(crate) type NotificationFn<S> =
40    Box<dyn FnMut(&mut S, Params<'_>, &mut Context<'_>) -> Result<(), ErrorObject> + Send>;
41pub(crate) type EventFn<S> = Box<dyn FnMut(&mut S, &Event<'_>) + Send>;
42pub(crate) type InterceptFn<S> =
43    Box<dyn FnMut(&mut S, &str, Option<&Id<'_>>, &Params<'_>) -> Result<(), ErrorObject> + Send>;
44
45/// How a request method is answered.
46pub(crate) enum RequestHandler<S> {
47    /// By the handler's return value.
48    Now(RequestFn<S>),
49    /// Through a [`Responder`], now or later.
50    Deferred(DeferredFn<S>),
51}
52
53/// Which handler answers which method.
54///
55/// Handlers receive the endpoint's state `S` (`&mut`), the call's
56/// [`Params`], and a [`Context`] for talking back. They run one at a time, in
57/// the order messages arrive, on the endpoint's thread. A request handler's
58/// `Ok` value (anything that converts into [`Json`]) becomes the result and
59/// its `Err` the error; a [deferred](Router::deferred) handler answers through
60/// a [`Responder`] instead.
61///
62/// A panic in any handler is contained: a request is answered with
63/// `INTERNAL_ERROR` (the panic message goes to [`Event::Panicked`], never to
64/// the peer), a notification gets nothing, and the session carries on. The
65/// state may be left half-updated by the panicking handler; the endpoint does
66/// not try to repair it. Containment needs `panic = "unwind"` (Rust's
67/// default): under `panic = "abort"` a handler panic ends the process.
68///
69/// Requests for methods with no request handler are answered with
70/// `METHOD_NOT_FOUND`. Notifications for methods with no notification handler
71/// are ignored (reported as [`Event::UnknownNotification`]): requests and
72/// notifications are registered separately, as LSP and MCP use them.
73///
74/// # Examples
75///
76/// ```
77/// use rpc_io::jsonx::json;
78/// use rpc_io::{ErrorObject, Router};
79///
80/// #[derive(Default)]
81/// struct Counter { hits: u64 }
82///
83/// let router = Router::new()
84///     .request("add", |_: &mut Counter, params, _| {
85///         let p = params.parse()?;
86///         match (p[0].as_i64(), p[1].as_i64()) {
87///             (Some(a), Some(b)) => Ok(json!(a + b)),
88///             _ => Err(ErrorObject::invalid_params("expected two integers")),
89///         }
90///     })
91///     .notification("hit", |state, _, _| state.hits += 1);
92/// assert!(router.has_request("add"));
93/// assert!(router.has_notification("hit"));
94/// ```
95pub struct Router<S> {
96    pub(crate) requests: BTreeMap<Box<str>, RequestHandler<S>>,
97    pub(crate) notifications: BTreeMap<Box<str>, NotificationFn<S>>,
98    pub(crate) on_event: Option<EventFn<S>>,
99    pub(crate) intercept: Option<InterceptFn<S>>,
100}
101
102impl<S> Router<S> {
103    /// A router with no handlers.
104    ///
105    /// # Examples
106    ///
107    /// ```
108    /// let router: rpc_io::Router<()> = rpc_io::Router::new();
109    /// assert!(!router.has_request("anything"));
110    /// ```
111    #[must_use]
112    pub fn new() -> Self {
113        Self {
114            requests: BTreeMap::new(),
115            notifications: BTreeMap::new(),
116            on_event: None,
117            intercept: None,
118        }
119    }
120
121    /// Answers requests for `method` with `handler`'s return value,
122    /// replacing any request handler registered for it before.
123    ///
124    /// # Examples
125    ///
126    /// ```
127    /// use rpc_io::{Endpoint, Router};
128    ///
129    /// let router = Router::new().request("ping", |_, _, _| Ok("pong"));
130    /// let (tx, rx) = std::sync::mpsc::channel::<String>();
131    /// Endpoint::new(tx, router, ()).handle(br#"{"jsonrpc":"2.0","id":1,"method":"ping"}"#)?;
132    /// assert_eq!(rx.try_recv().ok().as_deref(), Some(r#"{"jsonrpc":"2.0","id":1,"result":"pong"}"#));
133    /// # Ok::<(), rpc_io::Error>(())
134    /// ```
135    #[must_use]
136    pub fn request<F, J>(self, method: &str, mut handler: F) -> Self
137    where
138        F: FnMut(&mut S, Params<'_>, &mut Context<'_>) -> Result<J, ErrorObject> + Send + 'static,
139        J: Into<Json<'static>>,
140    {
141        self.request_into(method, move |state, params, cx, _out| {
142            handler(state, params, cx).map(Into::into)
143        })
144    }
145
146    /// Registers a request handler that may encode its result into the
147    /// endpoint's result buffer.
148    pub(crate) fn request_into<F>(mut self, method: &str, handler: F) -> Self
149    where
150        F: for<'b> FnMut(
151                &mut S,
152                Params<'_>,
153                &mut Context<'_>,
154                &'b mut String,
155            ) -> Result<Json<'b>, ErrorObject>
156            + Send
157            + 'static,
158    {
159        let _replaced = self
160            .requests
161            .insert(method.into(), RequestHandler::Now(Box::new(handler)));
162        self
163    }
164
165    /// Answers requests for `method` through a [`Responder`] the handler
166    /// receives: now, from a later message, or from another thread. The
167    /// request stays in flight (and cancellable by the peer) until answered;
168    /// at most [`Config::max_in_flight`](crate::Config) can be, and more are
169    /// refused with `SERVER_OVERLOADED`.
170    ///
171    /// # Examples
172    ///
173    /// ```
174    /// use rpc_io::Router;
175    ///
176    /// let router: Router<()> = Router::new().deferred("index", |_, params, _, responder| {
177    ///     let params = params.into_owned(); // keep it beyond this call
178    ///     std::thread::spawn(move || {
179    ///         let _ = params;
180    ///         responder.ok("indexed").ok();
181    ///     });
182    /// });
183    /// assert!(router.has_request("index"));
184    /// ```
185    #[must_use]
186    pub fn deferred<F>(mut self, method: &str, handler: F) -> Self
187    where
188        F: FnMut(&mut S, Params<'_>, &mut Context<'_>, Responder) + Send + 'static,
189    {
190        let _replaced = self
191            .requests
192            .insert(method.into(), RequestHandler::Deferred(Box::new(handler)));
193        self
194    }
195
196    /// Handles notifications for `method`, replacing any notification handler
197    /// registered for it before.
198    ///
199    /// # Examples
200    ///
201    /// ```
202    /// use rpc_io::{Endpoint, Router};
203    ///
204    /// let router = Router::new().notification("log", |seen: &mut Vec<String>, params, _| {
205    ///     seen.push(params.raw().map(|r| r.as_str().to_owned()).unwrap_or_default());
206    /// });
207    /// let (tx, rx) = std::sync::mpsc::channel::<String>();
208    /// let mut endpoint = Endpoint::new(tx, router, Vec::new());
209    /// endpoint.handle(br#"{"jsonrpc":"2.0","method":"log","params":["hi"]}"#)?;
210    /// assert_eq!(endpoint.state(), &["[\"hi\"]"]);
211    /// assert!(rx.try_recv().is_err()); // notifications are never answered
212    /// # Ok::<(), rpc_io::Error>(())
213    /// ```
214    #[must_use]
215    pub fn notification<F>(self, method: &str, mut handler: F) -> Self
216    where
217        F: FnMut(&mut S, Params<'_>, &mut Context<'_>) + Send + 'static,
218    {
219        self.notification_with(method, move |state, params, cx| {
220            handler(state, params, cx);
221            Ok(())
222        })
223    }
224
225    /// Registers a notification handler that may refuse its params.
226    pub(crate) fn notification_with<F>(mut self, method: &str, handler: F) -> Self
227    where
228        F: FnMut(&mut S, Params<'_>, &mut Context<'_>) -> Result<(), ErrorObject> + Send + 'static,
229    {
230        let _replaced = self.notifications.insert(method.into(), Box::new(handler));
231        self
232    }
233
234    /// Calls `hook` for every [`Event`]: things the endpoint handled on its
235    /// own that an application may want to log. Runs on the endpoint's thread;
236    /// a panic in it is contained and ignored.
237    ///
238    /// # Examples
239    ///
240    /// ```
241    /// use rpc_io::{Endpoint, Event, Router};
242    ///
243    /// let router = Router::new().on_event(|log: &mut Vec<String>, event| {
244    ///     if let Event::UnknownNotification { method } = event {
245    ///         log.push(method.to_string());
246    ///     }
247    /// });
248    /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
249    /// let mut endpoint = Endpoint::new(tx, router, Vec::new());
250    /// endpoint.handle(br#"{"jsonrpc":"2.0","method":"nobody/listens"}"#)?;
251    /// assert_eq!(endpoint.state(), &["nobody/listens"]);
252    /// # Ok::<(), rpc_io::Error>(())
253    /// ```
254    #[must_use]
255    pub fn on_event<F>(mut self, hook: F) -> Self
256    where
257        F: FnMut(&mut S, &Event<'_>) + Send + 'static,
258    {
259        self.on_event = Some(Box::new(hook));
260        self
261    }
262
263    /// Runs `hook` before every call the router would route: each request
264    /// and each notification, after the gate and cancellation have had their
265    /// say and before the handler is looked up. `Ok(())` lets the call
266    /// through; `Err(error)` refuses it: a request is answered with `error`,
267    /// a notification is dropped and reported as [`Event::Refused`]. The
268    /// place for authorization, rate limits, or an audit log. The hook gets
269    /// the state, the method, the id (`None` for a notification), and the
270    /// params; a panic in it is contained as a handler's would be.
271    /// Registering a hook again replaces it.
272    ///
273    /// # Examples
274    ///
275    /// ```
276    /// use rpc_io::{Endpoint, ErrorCode, ErrorObject, Router};
277    ///
278    /// #[derive(Default)]
279    /// struct Session { calls: u32, admin: bool }
280    ///
281    /// let router = Router::new()
282    ///     .request("admin/reset", |_: &mut Session, _, _| Ok(()))
283    ///     .request("ping", |_, _, _| Ok("pong"))
284    ///     .intercept(|session, method, _id, _params| {
285    ///         session.calls += 1;
286    ///         if method.starts_with("admin/") && !session.admin {
287    ///             return Err(ErrorObject::new(ErrorCode(1003), "forbidden"));
288    ///         }
289    ///         Ok(())
290    ///     });
291    /// let (tx, rx) = std::sync::mpsc::channel::<String>();
292    /// let mut endpoint = Endpoint::new(tx, router, Session::default());
293    /// endpoint.handle(br#"{"jsonrpc":"2.0","id":1,"method":"admin/reset"}"#)?;
294    /// endpoint.handle(br#"{"jsonrpc":"2.0","id":2,"method":"ping"}"#)?;
295    /// let replies: Vec<String> = rx.try_iter().collect();
296    /// assert_eq!(replies[0], r#"{"jsonrpc":"2.0","id":1,"error":{"code":1003,"message":"forbidden"}}"#);
297    /// assert_eq!(replies[1], r#"{"jsonrpc":"2.0","id":2,"result":"pong"}"#);
298    /// assert_eq!(endpoint.state().calls, 2);
299    /// # Ok::<(), rpc_io::Error>(())
300    /// ```
301    #[must_use]
302    pub fn intercept<F>(mut self, hook: F) -> Self
303    where
304        F: FnMut(&mut S, &str, Option<&Id<'_>>, &Params<'_>) -> Result<(), ErrorObject>
305            + Send
306            + 'static,
307    {
308        self.intercept = Some(Box::new(hook));
309        self
310    }
311
312    /// Whether a request handler is registered for `method`.
313    ///
314    /// # Examples
315    ///
316    /// ```
317    /// let router: rpc_io::Router<()> = rpc_io::Router::new().request("a", |_, _, _| Ok(()));
318    /// assert!(router.has_request("a"));
319    /// assert!(!router.has_notification("a"));
320    /// ```
321    #[must_use]
322    pub fn has_request(&self, method: &str) -> bool {
323        self.requests.contains_key(method)
324    }
325
326    /// Whether a notification handler is registered for `method`.
327    ///
328    /// # Examples
329    ///
330    /// ```
331    /// let router: rpc_io::Router<()> = rpc_io::Router::new().notification("n", |_, _, _| {});
332    /// assert!(router.has_notification("n"));
333    /// ```
334    #[must_use]
335    pub fn has_notification(&self, method: &str) -> bool {
336        self.notifications.contains_key(method)
337    }
338}
339
340impl<S> Default for Router<S> {
341    fn default() -> Self {
342        Self::new()
343    }
344}
345
346impl<S> fmt::Debug for Router<S> {
347    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
348        f.debug_struct("Router")
349            .field("requests", &self.requests.keys().collect::<Vec<_>>())
350            .field(
351                "notifications",
352                &self.notifications.keys().collect::<Vec<_>>(),
353            )
354            .finish_non_exhaustive()
355    }
356}
357
358/// A call's `params`: validated, kept as a slice of the message, parsed only
359/// when asked.
360///
361/// # Examples
362///
363/// ```
364/// use rpc_io::{Endpoint, Router};
365///
366/// let router = Router::new().request("pos", |_, params, _| {
367///     let p = params.parse()?; // `INVALID_PARAMS` if over the parser's budgets
368///     let line = p["line"].as_u64().ok_or_else(|| {
369///         rpc_io::ErrorObject::invalid_params("`line` must be a non-negative integer")
370///     })?;
371///     Ok(line + 1)
372/// });
373/// let (tx, rx) = std::sync::mpsc::channel::<String>();
374/// Endpoint::new(tx, router, ()).handle(br#"{"jsonrpc":"2.0","id":1,"method":"pos","params":{"line":9}}"#)?;
375/// assert_eq!(rx.try_recv().ok().as_deref(), Some(r#"{"jsonrpc":"2.0","id":1,"result":10}"#));
376/// # Ok::<(), rpc_io::Error>(())
377/// ```
378#[derive(Clone, Debug)]
379pub struct Params<'a> {
380    raw: Option<Raw<'a>>,
381    parser: Parser,
382}
383
384impl<'a> Params<'a> {
385    pub(crate) fn new(raw: Option<Raw<'a>>, parser: Parser) -> Self {
386        Self { raw, parser }
387    }
388
389    /// The parser with the endpoint's budgets.
390    pub(crate) fn parser(&self) -> Parser {
391        self.parser
392    }
393
394    /// The params' JSON text, `None` when absent.
395    pub(crate) fn text(&self) -> Option<&str> {
396        self.raw.as_ref().map(Raw::as_str)
397    }
398
399    /// Parses the params (an array or an object; `null` when absent), with
400    /// the endpoint's JSON budgets and duplicate keys refused. The value
401    /// borrows from the message.
402    ///
403    /// # Errors
404    ///
405    /// An `INVALID_PARAMS` [`ErrorObject`] saying why, ready to return with
406    /// `?`.
407    ///
408    /// # Examples
409    ///
410    /// ```
411    /// use rpc_io::{Endpoint, Router};
412    ///
413    /// let router = Router::new().request("dup", |_, params, _| params.parse().map(|_| ()));
414    /// let (tx, rx) = std::sync::mpsc::channel::<String>();
415    /// Endpoint::new(tx, router, ()).handle(br#"{"jsonrpc":"2.0","id":1,"method":"dup","params":{"a":1,"a":2}}"#)?;
416    /// assert!(rx.try_recv().is_ok_and(|m| m.contains("-32602")));
417    /// # Ok::<(), rpc_io::Error>(())
418    /// ```
419    pub fn parse(&self) -> Result<Value<'_>, ErrorObject> {
420        match &self.raw {
421            Some(raw) => raw.parse_with(&self.parser).map_err(ErrorObject::from),
422            None => Ok(Value::Null),
423        }
424    }
425
426    /// The params as raw JSON text, `None` when absent.
427    ///
428    /// # Examples
429    ///
430    /// ```
431    /// use rpc_io::{Endpoint, Router};
432    ///
433    /// let router = Router::new().request("echo", |_, params, _| {
434    ///     Ok(params.raw().map(|r| r.clone().into_owned()).unwrap_or(rpc_io::Raw::NULL))
435    /// });
436    /// let (tx, rx) = std::sync::mpsc::channel::<String>();
437    /// Endpoint::new(tx, router, ()).handle(br#"{"jsonrpc":"2.0","id":1,"method":"echo","params":[1, 2]}"#)?;
438    /// assert_eq!(rx.try_recv().ok().as_deref(), Some(r#"{"jsonrpc":"2.0","id":1,"result":[1, 2]}"#));
439    /// # Ok::<(), rpc_io::Error>(())
440    /// ```
441    #[must_use]
442    pub fn raw(&self) -> Option<&Raw<'a>> {
443        self.raw.as_ref()
444    }
445
446    /// Whether params were sent.
447    ///
448    /// # Examples
449    ///
450    /// ```
451    /// use rpc_io::{Endpoint, Router};
452    ///
453    /// let router = Router::new().request("m", |_, params, _| Ok(params.is_present()));
454    /// let (tx, rx) = std::sync::mpsc::channel::<String>();
455    /// Endpoint::new(tx, router, ()).handle(br#"{"jsonrpc":"2.0","id":1,"method":"m"}"#)?;
456    /// assert!(rx.try_recv().is_ok_and(|m| m.ends_with(r#""result":false}"#)));
457    /// # Ok::<(), rpc_io::Error>(())
458    /// ```
459    #[must_use]
460    pub fn is_present(&self) -> bool {
461        self.raw.is_some()
462    }
463
464    /// Copies the params so they can outlive the message, to move them to
465    /// another thread.
466    ///
467    /// # Examples
468    ///
469    /// ```
470    /// use rpc_io::{Params, Router};
471    ///
472    /// let router = Router::<Vec<Params<'static>>>::new().notification("keep", |kept, params, _| {
473    ///     kept.push(params.into_owned());
474    /// });
475    /// # let _ = router;
476    /// ```
477    #[must_use]
478    pub fn into_owned(self) -> Params<'static> {
479        Params {
480            raw: self.raw.map(Raw::into_owned),
481            parser: self.parser,
482        }
483    }
484
485    /// The params as raw JSON, `None` when absent.
486    ///
487    /// # Examples
488    ///
489    /// ```
490    /// use rpc_io::{Endpoint, Router};
491    ///
492    /// // Forward a request's params to the peer unchanged: no parse, no re-serialization.
493    /// let router = Router::new().notification("relay", |_, params, cx| {
494    ///     let raw = params.into_raw().unwrap_or(rpc_io::Raw::NULL);
495    ///     cx.notify("relayed", raw).ok();
496    /// });
497    /// let (tx, rx) = std::sync::mpsc::channel::<String>();
498    /// Endpoint::new(tx, router, ()).handle(br#"{"jsonrpc":"2.0","method":"relay","params":{"k": [1]}}"#)?;
499    /// assert_eq!(rx.try_recv().ok().as_deref(), Some(r#"{"jsonrpc":"2.0","method":"relayed","params":{"k": [1]}}"#));
500    /// # Ok::<(), rpc_io::Error>(())
501    /// ```
502    #[must_use]
503    pub fn into_raw(self) -> Option<Raw<'a>> {
504        self.raw
505    }
506}
507
508/// What a handler can reach while it runs: the method and id it is handling,
509/// and a channel back to the peer.
510///
511/// Messages sent through a context during a request go out before that
512/// request's response, in the order they were sent.
513///
514/// # Examples
515///
516/// ```
517/// use rpc_io::{Endpoint, Router};
518///
519/// let router = Router::new().request("work", |_, _, cx| {
520///     cx.notify("progress", rpc_io::jsonx::json!({ "method": cx.method() }))?;
521///     Ok(())
522/// });
523/// let (tx, rx) = std::sync::mpsc::channel::<String>();
524/// Endpoint::new(tx, router, ()).handle(br#"{"jsonrpc":"2.0","id":1,"method":"work"}"#)?;
525/// let sent: Vec<String> = rx.try_iter().collect();
526/// assert_eq!(sent[0], r#"{"jsonrpc":"2.0","method":"progress","params":{"method":"work"}}"#);
527/// assert_eq!(sent[1], r#"{"jsonrpc":"2.0","id":1,"result":null}"#);
528/// # Ok::<(), rpc_io::Error>(())
529/// ```
530pub struct Context<'a> {
531    link: &'a Arc<dyn Link>,
532    stop: &'a mut bool,
533    id: Option<&'a Id<'a>>,
534    method: &'a str,
535    /// For a deferred request (answered through a `Responder`), its serial.
536    deferred: Option<u64>,
537    /// Set when a request answered by the handler's return value has its
538    /// response written; made only if a scoped progress handle asks for it.
539    /// A `OnceLock` rather than a `OnceCell`, so `Context` stays `Sync`.
540    turn: OnceLock<Arc<Turn>>,
541}
542
543impl<'a> Context<'a> {
544    pub(crate) fn new(
545        link: &'a Arc<dyn Link>,
546        stop: &'a mut bool,
547        id: Option<&'a Id<'a>>,
548        method: &'a str,
549        deferred: Option<u64>,
550    ) -> Self {
551        Self {
552            link,
553            stop,
554            id,
555            method,
556            deferred,
557            turn: OnceLock::new(),
558        }
559    }
560
561    /// The request this call is, for a notification that must not outlive
562    /// it; `None` for a notification.
563    pub(crate) fn scope(&self) -> Option<Scope> {
564        let id = self.id?;
565        Some(match self.deferred {
566            Some(serial) => Scope::Deferred {
567                id: id.clone().into_owned(),
568                serial,
569            },
570            None => Scope::Turn(Arc::clone(self.turn.get_or_init(|| Arc::new(Turn::new())))),
571        })
572    }
573
574    /// A [`Notifier`](crate::Notifier) bound to the request being handled:
575    /// it sends while the request is in flight and refuses once it is
576    /// answered (for a request answered by the handler's return value, as
577    /// soon as the handler returns) or cancelled. `None` for a notification.
578    ///
579    /// # Examples
580    ///
581    /// ```
582    /// use rpc_io::{Endpoint, Error, Notifier, Router};
583    ///
584    /// let router = Router::new().request("work", |kept: &mut Option<Notifier>, _, cx| {
585    ///     let notifier = cx.notifier();
586    ///     if let Some(n) = &notifier {
587    ///         n.notify("working", ())?;
588    ///     }
589    ///     *kept = notifier;
590    ///     Ok("done")
591    /// });
592    /// let (tx, rx) = std::sync::mpsc::channel::<String>();
593    /// let mut endpoint = Endpoint::new(tx, router, None);
594    /// endpoint.handle(br#"{"jsonrpc":"2.0","id":1,"method":"work"}"#)?;
595    /// assert_eq!(rx.try_iter().count(), 2); // the notification, then the result
596    /// let late = endpoint.state().as_ref().map(|n| n.notify("working", ()));
597    /// assert!(matches!(late, Some(Err(Error::AlreadyAnswered))));
598    /// # Ok::<(), rpc_io::Error>(())
599    /// ```
600    #[must_use]
601    pub fn notifier(&self) -> Option<crate::Notifier> {
602        self.scope()
603            .map(|scope| crate::Notifier::new(self.peer(), scope))
604    }
605
606    /// The flag to set when the response is written, if a scoped handle
607    /// took one.
608    pub(crate) fn take_turn(&mut self) -> Option<Arc<Turn>> {
609        self.turn.take()
610    }
611
612    /// The method being handled.
613    ///
614    /// # Examples
615    ///
616    /// ```
617    /// let router: rpc_io::Router<()> = rpc_io::Router::new().request("m", |_, _, cx| Ok(cx.method().len()));
618    /// # let _ = router;
619    /// ```
620    #[must_use]
621    pub fn method(&self) -> &str {
622        self.method
623    }
624
625    /// The id of the request being handled; `None` for a notification.
626    ///
627    /// # Examples
628    ///
629    /// ```
630    /// let router: rpc_io::Router<()> =
631    ///     rpc_io::Router::new().request("m", |_, _, cx| Ok(cx.id().and_then(|id| id.as_i64())));
632    /// # let _ = router;
633    /// ```
634    #[must_use]
635    pub fn id(&self) -> Option<&Id<'a>> {
636        self.id
637    }
638
639    /// Sends a notification to the peer; see [`Peer::notify`].
640    ///
641    /// # Errors
642    ///
643    /// As [`Peer::notify`].
644    ///
645    /// # Examples
646    ///
647    /// ```
648    /// let router: rpc_io::Router<()> = rpc_io::Router::new().notification("n", |_, _, cx| {
649    ///     cx.notify("ack", ()).ok();
650    /// });
651    /// # let _ = router;
652    /// ```
653    pub fn notify<'j>(&self, method: &str, params: impl Into<Json<'j>>) -> Result<(), Error> {
654        Peer::new(Arc::clone(self.link)).notify(method, params)
655    }
656
657    /// Sends a request to the peer; see [`Peer::request`]. Its [`Call`]
658    /// cannot be waited on here (the answer arrives on this thread, after the
659    /// handler returns): keep it and [`try_wait`](Call::try_wait) later, or
660    /// wait on another thread.
661    ///
662    /// # Errors
663    ///
664    /// As [`Peer::request`].
665    ///
666    /// # Examples
667    ///
668    /// ```
669    /// use rpc_io::{Call, Router};
670    ///
671    /// let router = Router::<Vec<Call>>::new().notification("initialized", |calls, _, cx| {
672    ///     if let Ok(call) = cx.request("workspace/configuration", rpc_io::jsonx::json!({ "items": [] })) {
673    ///         calls.push(call);
674    ///     }
675    /// });
676    /// # let _ = router;
677    /// ```
678    pub fn request<'j>(&self, method: &str, params: impl Into<Json<'j>>) -> Result<Call, Error> {
679        Peer::new(Arc::clone(self.link)).request(method, params)
680    }
681
682    /// Sends a request with a timeout; see [`Peer::request_with_timeout`].
683    ///
684    /// # Errors
685    ///
686    /// As [`Peer::request`].
687    ///
688    /// # Examples
689    ///
690    /// ```
691    /// use std::time::Duration;
692    ///
693    /// let router: rpc_io::Router<()> = rpc_io::Router::new().notification("n", |_, _, cx| {
694    ///     let _call = cx.request_with_timeout("ask", (), Duration::from_secs(1));
695    /// });
696    /// # let _ = router;
697    /// ```
698    pub fn request_with_timeout<'j>(
699        &self,
700        method: &str,
701        params: impl Into<Json<'j>>,
702        timeout: Duration,
703    ) -> Result<Call, Error> {
704        Peer::new(Arc::clone(self.link)).request_with_timeout(method, params, timeout)
705    }
706
707    /// A [`Peer`] for this connection, to keep or move to another thread.
708    ///
709    /// # Examples
710    ///
711    /// ```
712    /// use rpc_io::{Peer, Router};
713    ///
714    /// let router: Router<Option<Peer>> = Router::new().notification("hello", |slot, _, cx| {
715    ///     *slot = Some(cx.peer());
716    /// });
717    /// # let _ = router;
718    /// ```
719    #[must_use]
720    pub fn peer(&self) -> Peer {
721        Peer::new(Arc::clone(self.link))
722    }
723
724    /// Stops the endpoint after this message: [`Endpoint::run`](crate::Endpoint::run)
725    /// returns [`End::Stopped`](crate::End) and
726    /// [`Endpoint::handle`](crate::Endpoint::handle) returns
727    /// [`Flow::Stop`](crate::Flow). A response to the current request is still
728    /// sent.
729    ///
730    /// # Examples
731    ///
732    /// ```
733    /// use rpc_io::{Endpoint, Flow, Router};
734    ///
735    /// let router = Router::new().notification("exit", |_, _, cx| cx.stop());
736    /// let (tx, _rx) = std::sync::mpsc::channel::<String>();
737    /// let mut endpoint = Endpoint::new(tx, router, ());
738    /// assert_eq!(endpoint.handle(br#"{"jsonrpc":"2.0","method":"exit"}"#)?, Flow::Stop);
739    /// # Ok::<(), rpc_io::Error>(())
740    /// ```
741    pub fn stop(&mut self) {
742        *self.stop = true;
743    }
744}
745
746impl fmt::Debug for Context<'_> {
747    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
748        f.debug_struct("Context")
749            .field("method", &self.method)
750            .field("id", &self.id)
751            .finish_non_exhaustive()
752    }
753}
754
755/// Something the endpoint handled on its own, reported to
756/// [`Router::on_event`] so an application can log it.
757///
758/// # Examples
759///
760/// ```
761/// use rpc_io::Event;
762///
763/// fn describe(event: &Event<'_>) -> String {
764///     match event {
765///         Event::Panicked { method, message } => format!("`{method}` panicked: {message}"),
766///         other => format!("{other:?}"),
767///     }
768/// }
769/// assert_eq!(describe(&Event::Panicked { method: "m", message: "boom" }), "`m` panicked: boom");
770/// ```
771#[derive(Clone, Debug)]
772#[non_exhaustive]
773pub enum Event<'a> {
774    /// A handler panicked. A request was answered with `INTERNAL_ERROR`
775    /// (without the panic message, which may hold details the peer should not
776    /// see); the message is here.
777    Panicked {
778        /// The method whose handler panicked.
779        method: &'a str,
780        /// The panic message, clipped, or a placeholder.
781        message: &'a str,
782    },
783    /// A malformed message arrived: answered with `error` if it was
784    /// request-like, dropped if it was a malformed response to one of our
785    /// requests (which then ends with `CallError::InvalidResponse`).
786    Invalid {
787        /// What was wrong.
788        error: &'a ErrorObject,
789        /// Whether it was answered.
790        answered: bool,
791    },
792    /// A notification for a method with no notification handler.
793    UnknownNotification {
794        /// The method.
795        method: &'a str,
796    },
797    /// A notification dropped because it arrived before the
798    /// [`Gate`](crate::Gate) opened.
799    Dropped {
800        /// The method.
801        method: &'a str,
802    },
803    /// A response whose id matches none of our outstanding requests (late,
804    /// repeated, or forged).
805    Unmatched {
806        /// The id it carried.
807        id: &'a Id<'a>,
808    },
809    /// An error response with a `null` id: the peer could not read something
810    /// we sent.
811    PeerError {
812        /// The peer's error.
813        error: &'a ErrorObject,
814    },
815    /// A message over [`Limits::max_message_bytes`](crate::Limits) was skipped
816    /// unread, and answered with `INVALID_REQUEST` under a `null` id.
817    Oversized {
818        /// The framing error with the sizes.
819        error: FrameError,
820    },
821    /// The peer cancelled one of its requests that was in flight.
822    Cancelled {
823        /// The cancelled request's id.
824        id: &'a Id<'a>,
825    },
826    /// A notification refused by the router's
827    /// [interceptor](Router::intercept); it was not handled.
828    Refused {
829        /// The method.
830        method: &'a str,
831        /// The interceptor's error.
832        error: &'a ErrorObject,
833    },
834    /// A notification's params did not fit what its handler takes (a typed
835    /// handler: [`Router::notification_json`], or `notification_typed` with
836    /// the `serde` feature); the handler was not called.
837    InvalidParams {
838        /// The method.
839        method: &'a str,
840        /// What did not fit, as an `INVALID_PARAMS` error.
841        error: &'a ErrorObject,
842    },
843}