pub struct Router<S> { /* private fields */ }
Expand description
A JSON-RPC router. This is the top-level type for handling JSON-RPC
requests. It is heavily inspired by the axum::Router
type.
A router manages a collection of “methods” that can be called by clients. Each method is associated with a handler that processes the request and returns a response. The router is responsible for routing requests to the appropriate handler.
Methods can be added to the router using the Router::route
family of
methods:
Router::route
: Add a method with aHandler
. TheHandler
will be invoked with the request parameters and provided state.
§Basic Example
Routers are constructed via builder-style methods. The following example
demonstrates how to create a router with two methods, double
and add
.
The double
method doubles the provided number, and the add
method adds
the provided number to some state, and returns the sum.
use ajj::Router;
// Provide methods called "double" and "add" to the router.
let router = Router::<u64>::new()
// This route requires state to be provided.
.route("add", |params: u64, state: u64| async move {
Ok::<_, ()>(params + state)
})
.with_state::<()>(3u64)
// when double is called, the provided number is doubled.
// see the Handler docs for more information on the hint type
.route("double", |params: u64| async move {
Ok::<_, ()>(params * 2)
});
§Note
The state S
is “missing” state. It is state that must be added to the
router (and therefore to the methods) before it can be used. To add state,
use the Router::with_state
method. See that method for more
information.
Analagous to axum::Router
.
Implementations§
Source§impl<S> Router<S>
impl<S> Router<S>
Sourcepub fn with_state<S2>(self, state: S) -> Router<S2>
pub fn with_state<S2>(self, state: S) -> Router<S2>
Add state to the router, readying methods that require that state.
Note that the type parameter S2
is NOT the state you are adding to the
router. It is additional state that must be added AFTER the state S
.
Sourcepub fn fallback<H, T>(self, handler: H) -> Self
pub fn fallback<H, T>(self, handler: H) -> Self
Add a fallback Handler
to the router. This handler will be called
when no method names match the request.
§Notes
The S
type parameter is “missing” state. It is state that must be
added to the router (and therefore to the methods) before it can be
used. To add state, use the Router::with_state
method. See that
method for more information.
If unset, a default fallback route will be used that returns the error
generated by ResponsePayload::method_not_found
.
Sourcepub fn fallback_service<T>(self, service: T) -> Selfwhere
T: Service<HandlerArgs, Response = Option<Box<RawValue>>, Error = Infallible, Future: Send + 'static> + Clone + Send + Sync + 'static,
pub fn fallback_service<T>(self, service: T) -> Selfwhere
T: Service<HandlerArgs, Response = Option<Box<RawValue>>, Error = Infallible, Future: Send + 'static> + Clone + Send + Sync + 'static,
Add a fallback Service
handler. This handler will be called when no
method names match the request.
§Note
If unset, a default fallback route will be used that returns the error
generated by ResponsePayload::method_not_found
.
Sourcepub fn route<H, T>(
self,
method: impl Into<Cow<'static, str>>,
handler: H,
) -> Self
pub fn route<H, T>( self, method: impl Into<Cow<'static, str>>, handler: H, ) -> Self
Add a method with a Handler
to the router.
§Note
The S
type parameter is “missing” state. It is state that must be
added to the router (and therefore to the methods) before it can be
used. To add state, use the Router::with_state
method. See that
method for more information.
§Panics
Panics if the method name already exists in the router.
Sourcepub fn nest(self, prefix: impl Into<Cow<'static, str>>, other: Self) -> Self
pub fn nest(self, prefix: impl Into<Cow<'static, str>>, other: Self) -> Self
Nest a router under a prefix. This is useful for grouping related methods together, or for namespacing logical groups of methods.
The prefix is trimmed of any trailing underscores, and a single underscore is added between the prefix and the method name.
I.e. the following are equivalent and will all produce the foo_
prefix for the methods in other
:
router.nest("foo", other)
router.nest("foo_", other)
router.nest("foo__", other)
§Panics
Panics if collision occurs between the prefixed methods from other
and
the methods in self
. E.g. if the prefix is foo
, self
has a
method foo_bar
, and other
has a method bar
.
Sourcepub fn merge(self, other: Self) -> Self
pub fn merge(self, other: Self) -> Self
Merge two routers together. This enrolls all methods from other
into
self
.
§Panics
Panics if a method name collision occurs between the two routers. I.e.
if any method from other
has the same name as a method in self
.
Sourcepub fn call_with_state(&self, args: HandlerArgs, state: S) -> RouteFuture ⓘ
pub fn call_with_state(&self, args: HandlerArgs, state: S) -> RouteFuture ⓘ
Call a method on the router, by providing the necessary state.
This is a convenience method, primarily for testing. Use in production code is discouraged. Routers should not be left in incomplete states.
Sourcepub fn call_batch_with_state(
&self,
ctx: HandlerCtx,
inbound: InboundData,
state: S,
) -> BatchFuture ⓘ
pub fn call_batch_with_state( &self, ctx: HandlerCtx, inbound: InboundData, state: S, ) -> BatchFuture ⓘ
Call a method on the router, without providing state.
Sourcepub fn into_axum(self, path: &str) -> Router<S>
Available on crate feature axum
only.
pub fn into_axum(self, path: &str) -> Router<S>
axum
only.Nest this router into a new Axum router, with the specified path and the currently-running
Users needing specific control over the runtime should use
Router::into_axum_with_handle
instead.
Sourcepub fn into_axum_with_handle(self, path: &str, handle: Handle) -> Router<S>
Available on crate feature axum
only.
pub fn into_axum_with_handle(self, path: &str, handle: Handle) -> Router<S>
axum
only.Nest this router into a new Axum router, with the specified path and using the specified runtime handle.
This method allows users to specify a runtime handle for the router to use. This runtime is accessible to all handlers invoked by the router.
Tasks spawned by the router will be spawned on the provided runtime,
and automatically cancelled when the returned axum::Router
is
dropped.
Source§impl Router<()>
impl Router<()>
Sourcepub async fn serve_pubsub<C: Connect>(
self,
connect: C,
) -> Result<ServerShutdown, C::Error>
Available on crate feature pubsub
only.
pub async fn serve_pubsub<C: Connect>( self, connect: C, ) -> Result<ServerShutdown, C::Error>
pubsub
only.Serve the router over a connection. This method returns a
ServerShutdown
, which will shut down the server when dropped.
Sourcepub fn to_axum_cfg(&self) -> AxumWsCfg
Available on crate features axum
and pubsub
only.
pub fn to_axum_cfg(&self) -> AxumWsCfg
axum
and pubsub
only.Create an AxumWsCfg
from this router. This is a convenience method
for AxumWsCfg::new(self.clone())
.
Sourcepub fn into_axum_with_ws(self, post_route: &str, ws_route: &str) -> Router<()>
Available on crate features axum
and pubsub
only.
pub fn into_axum_with_ws(self, post_route: &str, ws_route: &str) -> Router<()>
axum
and pubsub
only.Create an axum::Router
from this router, serving this router via
HTTP POST
requests at post_route
and via WebSocket at ws_route
.
Sourcepub fn into_axum_with_ws_and_handle(
self,
post_route: &str,
ws_route: &str,
handle: Handle,
) -> Router<()>
Available on crate features axum
and pubsub
only.
pub fn into_axum_with_ws_and_handle( self, post_route: &str, ws_route: &str, handle: Handle, ) -> Router<()>
axum
and pubsub
only.Create an axum::Router
from this router, serving this router via
HTTP POST
requests at post_route
and via WebSocket at ws_route
.
This convenience method allows users to specify a runtime handle for the
router to use. See Router::into_axum_with_handle
for more
information.
Sourcepub fn handle_request(&self, args: HandlerArgs) -> RouteFuture ⓘ
pub fn handle_request(&self, args: HandlerArgs) -> RouteFuture ⓘ
Call a method on the router.
Sourcepub fn handle_request_batch(
&self,
ctx: HandlerCtx,
batch: InboundData,
) -> BatchFuture ⓘ
pub fn handle_request_batch( &self, ctx: HandlerCtx, batch: InboundData, ) -> BatchFuture ⓘ
Call a batch of methods on the router.
Trait Implementations§
Source§impl Service<HandlerArgs> for &Router<()>
impl Service<HandlerArgs> for &Router<()>
Source§impl Service<HandlerArgs> for Router<()>
impl Service<HandlerArgs> for Router<()>
Auto Trait Implementations§
impl<S> Freeze for Router<S>
impl<S> !RefUnwindSafe for Router<S>
impl<S> Send for Router<S>
impl<S> Sync for Router<S>
impl<S> Unpin for Router<S>
impl<S> !UnwindSafe for Router<S>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<S, R> ServiceExt<R> for Swhere
S: Service<R>,
impl<S, R> ServiceExt<R> for Swhere
S: Service<R>,
Source§fn into_make_service(self) -> IntoMakeService<S>
fn into_make_service(self) -> IntoMakeService<S>
MakeService
, that is a Service
whose
response is another service. Read moreSource§fn into_make_service_with_connect_info<C>(
self,
) -> IntoMakeServiceWithConnectInfo<S, C>
fn into_make_service_with_connect_info<C>( self, ) -> IntoMakeServiceWithConnectInfo<S, C>
MakeService
, that will store C
’s
associated ConnectInfo
in a request extension such that ConnectInfo
can extract it. Read moreSource§fn handle_error<F, T>(self, f: F) -> HandleError<Self, F, T>
fn handle_error<F, T>(self, f: F) -> HandleError<Self, F, T>
HandleError
, that will handle errors
by converting them into responses. Read moreSource§impl<T, Request> ServiceExt<Request> for T
impl<T, Request> ServiceExt<Request> for T
Source§fn ready(&mut self) -> Ready<'_, Self, Request>where
Self: Sized,
fn ready(&mut self) -> Ready<'_, Self, Request>where
Self: Sized,
Source§fn ready_oneshot(self) -> ReadyOneshot<Self, Request>where
Self: Sized,
fn ready_oneshot(self) -> ReadyOneshot<Self, Request>where
Self: Sized,
Source§fn oneshot(self, req: Request) -> Oneshot<Self, Request>where
Self: Sized,
fn oneshot(self, req: Request) -> Oneshot<Self, Request>where
Self: Sized,
Service
, calling it with the provided request once it is ready.Source§fn and_then<F>(self, f: F) -> AndThen<Self, F>
fn and_then<F>(self, f: F) -> AndThen<Self, F>
poll_ready
method. Read moreSource§fn map_response<F, Response>(self, f: F) -> MapResponse<Self, F>
fn map_response<F, Response>(self, f: F) -> MapResponse<Self, F>
poll_ready
method. Read moreSource§fn map_err<F, Error>(self, f: F) -> MapErr<Self, F>
fn map_err<F, Error>(self, f: F) -> MapErr<Self, F>
poll_ready
method. Read moreSource§fn map_result<F, Response, Error>(self, f: F) -> MapResult<Self, F>
fn map_result<F, Response, Error>(self, f: F) -> MapResult<Self, F>
Result<Self::Response, Self::Error>
)
to a different value, regardless of whether the future succeeds or
fails. Read more