Skip to main content

Router

Struct Router 

Source
pub struct Router<S> { /* private fields */ }
Available on crate feature std only.
Expand description

Which handler answers which method.

Handlers receive the endpoint’s state S (&mut), the call’s Params, and a Context for talking back. They run one at a time, in the order messages arrive, on the endpoint’s thread. A request handler’s Ok value (anything that converts into Json) becomes the result and its Err the error; a deferred handler answers through a Responder instead.

A panic in any handler is contained: a request is answered with INTERNAL_ERROR (the panic message goes to Event::Panicked, never to the peer), a notification gets nothing, and the session carries on. The state may be left half-updated by the panicking handler; the endpoint does not try to repair it. Containment needs panic = "unwind" (Rust’s default): under panic = "abort" a handler panic ends the process.

Requests for methods with no request handler are answered with METHOD_NOT_FOUND. Notifications for methods with no notification handler are ignored (reported as Event::UnknownNotification): requests and notifications are registered separately, as LSP and MCP use them.

§Examples

use jsonx_lib::json;
use rpc_io::{ErrorObject, Router};

#[derive(Default)]
struct Counter { hits: u64 }

let router = Router::new()
    .request("add", |_: &mut Counter, params, _| {
        let p = params.parse()?;
        match (p[0].as_i64(), p[1].as_i64()) {
            (Some(a), Some(b)) => Ok(json!(a + b)),
            _ => Err(ErrorObject::invalid_params("expected two integers")),
        }
    })
    .notification("hit", |state, _, _| state.hits += 1);
assert!(router.has_request("add"));
assert!(router.has_notification("hit"));

Implementations§

Source§

impl<S> Router<S>

Source

pub fn new() -> Self

A router with no handlers.

§Examples
let router: rpc_io::Router<()> = rpc_io::Router::new();
assert!(!router.has_request("anything"));
Source

pub fn request<F, J>(self, method: &str, handler: F) -> Self
where F: FnMut(&mut S, Params<'_>, &mut Context<'_>) -> Result<J, ErrorObject> + Send + 'static, J: Into<Json<'static>>,

Answers requests for method with handler’s return value, replacing any request handler registered for it before.

§Examples
use rpc_io::{Endpoint, Router};

let router = Router::new().request("ping", |_, _, _| Ok("pong"));
let (tx, rx) = std::sync::mpsc::channel::<String>();
Endpoint::new(tx, router, ()).handle(br#"{"jsonrpc":"2.0","id":1,"method":"ping"}"#)?;
assert_eq!(rx.try_recv().ok().as_deref(), Some(r#"{"jsonrpc":"2.0","id":1,"result":"pong"}"#));
Source

pub fn deferred<F>(self, method: &str, handler: F) -> Self
where F: FnMut(&mut S, Params<'_>, &mut Context<'_>, Responder) + Send + 'static,

Answers requests for method through a Responder the handler receives: now, from a later message, or from another thread. The request stays in flight (and cancellable by the peer) until answered; at most Config::max_in_flight can be, and more are refused with SERVER_OVERLOADED.

§Examples
use rpc_io::Router;

let router: Router<()> = Router::new().deferred("index", |_, params, _, responder| {
    let params = params.into_owned(); // keep it beyond this call
    std::thread::spawn(move || {
        let _ = params;
        responder.ok("indexed").ok();
    });
});
assert!(router.has_request("index"));
Source

pub fn notification<F>(self, method: &str, handler: F) -> Self
where F: FnMut(&mut S, Params<'_>, &mut Context<'_>) + Send + 'static,

Handles notifications for method, replacing any notification handler registered for it before.

§Examples
use rpc_io::{Endpoint, Router};

let router = Router::new().notification("log", |seen: &mut Vec<String>, params, _| {
    seen.push(params.raw().map(|r| r.as_str().to_owned()).unwrap_or_default());
});
let (tx, rx) = std::sync::mpsc::channel::<String>();
let mut endpoint = Endpoint::new(tx, router, Vec::new());
endpoint.handle(br#"{"jsonrpc":"2.0","method":"log","params":["hi"]}"#)?;
assert_eq!(endpoint.state(), &["[\"hi\"]"]);
assert!(rx.try_recv().is_err()); // notifications are never answered
Source

pub fn on_event<F>(self, hook: F) -> Self
where F: FnMut(&mut S, &Event<'_>) + Send + 'static,

Calls hook for every Event: things the endpoint handled on its own that an application may want to log. Runs on the endpoint’s thread; a panic in it is contained and ignored.

§Examples
use rpc_io::{Endpoint, Event, Router};

let router = Router::new().on_event(|log: &mut Vec<String>, event| {
    if let Event::UnknownNotification { method } = event {
        log.push(method.to_string());
    }
});
let (tx, _rx) = std::sync::mpsc::channel::<String>();
let mut endpoint = Endpoint::new(tx, router, Vec::new());
endpoint.handle(br#"{"jsonrpc":"2.0","method":"nobody/listens"}"#)?;
assert_eq!(endpoint.state(), &["nobody/listens"]);
Source

pub fn has_request(&self, method: &str) -> bool

Whether a request handler is registered for method.

§Examples
let router: rpc_io::Router<()> = rpc_io::Router::new().request("a", |_, _, _| Ok(()));
assert!(router.has_request("a"));
assert!(!router.has_notification("a"));
Source

pub fn has_notification(&self, method: &str) -> bool

Whether a notification handler is registered for method.

§Examples
let router: rpc_io::Router<()> = rpc_io::Router::new().notification("n", |_, _, _| {});
assert!(router.has_notification("n"));

Trait Implementations§

Source§

impl<S> Debug for Router<S>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<S> Default for Router<S>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<S> !RefUnwindSafe for Router<S>

§

impl<S> !Sync for Router<S>

§

impl<S> !UnwindSafe for Router<S>

§

impl<S> Freeze for Router<S>
where BTreeMap<Box<str>, RequestHandler<S>>: Freeze, BTreeMap<Box<str>, Box<dyn FnMut(&mut S, Params<'_>, &mut Context<'_>) + Send>>: Freeze, Option<Box<dyn FnMut(&mut S, &Event<'_>) + Send>>: Freeze,

§

impl<S> Send for Router<S>
where BTreeMap<Box<str>, RequestHandler<S>>: Send, BTreeMap<Box<str>, Box<dyn FnMut(&mut S, Params<'_>, &mut Context<'_>) + Send>>: Send, Option<Box<dyn FnMut(&mut S, &Event<'_>) + Send>>: Send,

§

impl<S> Unpin for Router<S>
where BTreeMap<Box<str>, RequestHandler<S>>: Unpin, BTreeMap<Box<str>, Box<dyn FnMut(&mut S, Params<'_>, &mut Context<'_>) + Send>>: Unpin, Option<Box<dyn FnMut(&mut S, &Event<'_>) + Send>>: Unpin,

§

impl<S> UnsafeUnpin for Router<S>
where BTreeMap<Box<str>, RequestHandler<S>>: UnsafeUnpin, BTreeMap<Box<str>, Box<dyn FnMut(&mut S, Params<'_>, &mut Context<'_>) + Send>>: UnsafeUnpin, Option<Box<dyn FnMut(&mut S, &Event<'_>) + Send>>: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.