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