Struct Router

Source
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:

§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>
where S: Send + Sync + Clone + 'static,

Source

pub fn new() -> Self

Create a new, empty router.

Source

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.

Source

pub fn fallback<H, T>(self, handler: H) -> Self
where H: Handler<T, S>, T: Send + 'static, S: Clone + Send + Sync + 'static,

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.

Source

pub fn fallback_service<T>(self, service: T) -> Self
where 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.

Source

pub fn route<H, T>( self, method: impl Into<Cow<'static, str>>, handler: H, ) -> Self
where H: Handler<T, S>, T: Send + 'static, S: Clone + Send + Sync + 'static,

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.

Source

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.

Source

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.

Source

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.

Source

pub fn call_batch_with_state( &self, ctx: HandlerCtx, inbound: InboundData, state: S, ) -> BatchFuture

Call a method on the router, without providing state.

Source

pub fn into_axum(self, path: &str) -> Router<S>

Available on crate feature 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.

Source

pub fn into_axum_with_handle(self, path: &str, handle: Handle) -> Router<S>

Available on crate feature 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<()>

Source

pub async fn serve_pubsub<C: Connect>( self, connect: C, ) -> Result<ServerShutdown, C::Error>

Available on crate feature pubsub only.

Serve the router over a connection. This method returns a ServerShutdown, which will shut down the server when dropped.

Source

pub fn to_axum_cfg(&self) -> AxumWsCfg

Available on crate features axum and pubsub only.

Create an AxumWsCfg from this router. This is a convenience method for AxumWsCfg::new(self.clone()).

Source

pub fn into_axum_with_ws(self, post_route: &str, ws_route: &str) -> Router<()>

Available on crate features 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.

Source

pub 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.

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.

Source

pub fn handle_request(&self, args: HandlerArgs) -> RouteFuture

Call a method on the router.

Source

pub fn handle_request_batch( &self, ctx: HandlerCtx, batch: InboundData, ) -> BatchFuture

Call a batch of methods on the router.

Trait Implementations§

Source§

impl<S> Clone for Router<S>

Source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
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>
where S: Send + Sync + Clone + 'static,

Source§

fn default() -> Self

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

impl From<Router<()>> for AxumWsCfg

Available on crate features axum and pubsub only.
Source§

fn from(router: Router<()>) -> Self

Converts to this type from the input type.
Source§

impl Service<HandlerArgs> for &Router<()>

Source§

type Response = Option<Box<RawValue>>

Responses given by the service.
Source§

type Error = Infallible

Errors produced by the service.
Source§

type Future = RouteFuture

The future response value.
Source§

fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Poll::Ready(Ok(())) when the service is able to process requests. Read more
Source§

fn call(&mut self, args: HandlerArgs) -> Self::Future

Process the request and return the response asynchronously. Read more
Source§

impl Service<HandlerArgs> for Router<()>

Source§

type Response = Option<Box<RawValue>>

Responses given by the service.
Source§

type Error = Infallible

Errors produced by the service.
Source§

type Future = RouteFuture

The future response value.
Source§

fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>>

Returns Poll::Ready(Ok(())) when the service is able to process requests. Read more
Source§

fn call(&mut self, args: HandlerArgs) -> Self::Future

Process the request and return the response asynchronously. Read more

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> 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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<S, R> ServiceExt<R> for S
where S: Service<R>,

Source§

fn into_make_service(self) -> IntoMakeService<S>

Convert this service into a MakeService, that is a Service whose response is another service. Read more
Source§

fn into_make_service_with_connect_info<C>( self, ) -> IntoMakeServiceWithConnectInfo<S, C>

Convert this service into a MakeService, that will store C’s associated ConnectInfo in a request extension such that ConnectInfo can extract it. Read more
Source§

fn handle_error<F, T>(self, f: F) -> HandleError<Self, F, T>

Convert this service into a HandleError, that will handle errors by converting them into responses. Read more
Source§

impl<T, Request> ServiceExt<Request> for T
where T: Service<Request> + ?Sized,

Source§

fn ready(&mut self) -> Ready<'_, Self, Request>
where Self: Sized,

Yields a mutable reference to the service when it is ready to accept a request.
Source§

fn ready_oneshot(self) -> ReadyOneshot<Self, Request>
where Self: Sized,

Yields the service when it is ready to accept a request.
Source§

fn oneshot(self, req: Request) -> Oneshot<Self, Request>
where Self: Sized,

Consume this Service, calling it with the provided request once it is ready.
Source§

fn call_all<S>(self, reqs: S) -> CallAll<Self, S>
where Self: Sized, S: Stream<Item = Request>,

Process all requests from the given Stream, and produce a Stream of their responses. Read more
Source§

fn and_then<F>(self, f: F) -> AndThen<Self, F>
where Self: Sized, F: Clone,

Executes a new future after this service’s future resolves. This does not alter the behaviour of the poll_ready method. Read more
Source§

fn map_response<F, Response>(self, f: F) -> MapResponse<Self, F>
where Self: Sized, F: FnOnce(Self::Response) -> Response + Clone,

Maps this service’s response value to a different value. This does not alter the behaviour of the poll_ready method. Read more
Source§

fn map_err<F, Error>(self, f: F) -> MapErr<Self, F>
where Self: Sized, F: FnOnce(Self::Error) -> Error + Clone,

Maps this service’s error value to a different value. This does not alter the behaviour of the poll_ready method. Read more
Source§

fn map_result<F, Response, Error>(self, f: F) -> MapResult<Self, F>
where Self: Sized, Error: From<Self::Error>, F: FnOnce(Result<Self::Response, Self::Error>) -> Result<Response, Error> + Clone,

Maps this service’s result type (Result<Self::Response, Self::Error>) to a different value, regardless of whether the future succeeds or fails. Read more
Source§

fn map_request<F, NewRequest>(self, f: F) -> MapRequest<Self, F>
where Self: Sized, F: FnMut(NewRequest) -> Request,

Composes a function in front of the service. Read more
Source§

fn then<F, Response, Error, Fut>(self, f: F) -> Then<Self, F>
where Self: Sized, Error: From<Self::Error>, F: FnOnce(Result<Self::Response, Self::Error>) -> Fut + Clone, Fut: Future<Output = Result<Response, Error>>,

Composes an asynchronous function after this service. Read more
Source§

fn map_future<F, Fut, Response, Error>(self, f: F) -> MapFuture<Self, F>
where Self: Sized, F: FnMut(Self::Future) -> Fut, Error: From<Self::Error>, Fut: Future<Output = Result<Response, Error>>,

Composes a function that transforms futures produced by the service. Read more
Source§

fn boxed(self) -> BoxService<Request, Self::Response, Self::Error>
where Self: Sized + Send + 'static, Self::Future: Send + 'static,

Convert the service into a Service + Send trait object. Read more
Source§

fn boxed_clone(self) -> BoxCloneService<Request, Self::Response, Self::Error>
where Self: Sized + Clone + Send + 'static, Self::Future: Send + 'static,

Convert the service into a Service + Clone + Send trait object. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> TryClone for T
where T: Clone,

Source§

fn try_clone(&self) -> Result<T, Error>

Clones self, possibly returning an error.
Source§

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

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,