rpc_router/handler/handler.rs
1use crate::handler::{RpcHandlerWrapper, RpcHandlerWrapperTrait};
2use crate::{Resources, Result};
3use futures::Future;
4use serde_json::Value;
5
6/// The `Handler` trait that will be implemented by rpc handler functions.
7///
8/// Key points:
9/// - Rpc handler functions are asynchronous, thus returning a Future of Result<Value>.
10/// - The call format is normalized to two `impl FromResources` arguments (for now) and one optionals `impl IntoParams`, which represent the json-rpc's optional value.
11/// - `into_box` is a convenient method for converting a RpcHandler into a Boxed dyn RpcHandlerWrapperTrait,
12/// allowing for dynamic dispatch by the Router.
13/// - A `RpcHandler` will typically be implemented for static functions, as `FnOnce`,
14/// enabling them to be cloned with none or negligible performance impact,
15/// thus facilitating the use of RpcRoute dynamic dispatch.
16/// - `T` is the tuple of `impl FromResources` arguments.
17/// - `P` is the `impl IntoParams` argument.
18///
19pub trait Handler<T, P, R>: Clone
20where
21 T: Send + Sync + 'static,
22 P: Send + Sync + 'static,
23 R: Send + Sync + 'static,
24{
25 /// The type of future calling this handler returns.
26 type Future: Future<Output = Result<Value>> + Send + 'static;
27
28 /// Call the handler.
29 fn call(self, rpc_resources: Resources, params: Option<Value>) -> Self::Future;
30
31 /// Convert this RpcHandler into a Boxed dyn RpcHandlerWrapperTrait,
32 /// for dynamic dispatch by the Router.
33 fn into_dyn(self) -> Box<dyn RpcHandlerWrapperTrait>
34 where
35 Self: Sized + Send + Sync + 'static,
36 {
37 Box::new(RpcHandlerWrapper::new(self)) as Box<dyn RpcHandlerWrapperTrait>
38 }
39}