pub struct Router<S> { /* private fields */ }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>
impl<S> Router<S>
Sourcepub fn new() -> Self
pub fn new() -> Self
A router with no handlers.
§Examples
let router: rpc_io::Router<()> = rpc_io::Router::new();
assert!(!router.has_request("anything"));Sourcepub fn request<F, J>(self, method: &str, handler: F) -> Self
pub fn request<F, J>(self, method: &str, handler: F) -> Self
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"}"#));Sourcepub fn deferred<F>(self, method: &str, handler: F) -> Self
pub fn deferred<F>(self, method: &str, handler: F) -> Self
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"));Sourcepub fn notification<F>(self, method: &str, handler: F) -> Self
pub fn notification<F>(self, method: &str, handler: F) -> Self
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 answeredSourcepub fn on_event<F>(self, hook: F) -> Self
pub fn on_event<F>(self, hook: F) -> Self
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"]);Sourcepub fn has_request(&self, method: &str) -> bool
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"));Sourcepub fn has_notification(&self, method: &str) -> bool
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"));