rs_jsonrpc_core/
calls.rs

1use std::fmt;
2use std::sync::Arc;
3use types::{Params, Value, Error};
4use futures::{Future, IntoFuture};
5use BoxFuture;
6
7/// Metadata trait
8pub trait Metadata: Default + Clone + Send + 'static {}
9impl Metadata for () {}
10
11/// Asynchronous Method
12pub trait RpcMethodSimple: Send + Sync + 'static {
13	/// Output future
14	type Out: Future<Item = Value, Error = Error> + Send;
15	/// Call method
16	fn call(&self, params: Params) -> Self::Out;
17}
18
19/// Asynchronous Method with Metadata
20pub trait RpcMethod<T: Metadata>: Send + Sync + 'static {
21	/// Call method
22	fn call(&self, params: Params, meta: T) -> BoxFuture<Value>;
23}
24
25/// Notification
26pub trait RpcNotificationSimple: Send + Sync + 'static {
27	/// Execute notification
28	fn execute(&self, params: Params);
29}
30
31/// Notification with Metadata
32pub trait RpcNotification<T: Metadata>: Send + Sync + 'static {
33	/// Execute notification
34	fn execute(&self, params: Params, meta: T);
35}
36
37/// Possible Remote Procedures with Metadata
38#[derive(Clone)]
39pub enum RemoteProcedure<T: Metadata> {
40	/// A method call
41	Method(Arc<RpcMethod<T>>),
42	/// A notification
43	Notification(Arc<RpcNotification<T>>),
44	/// An alias to other method,
45	Alias(String),
46}
47
48impl<T: Metadata> fmt::Debug for RemoteProcedure<T> {
49	fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
50		use self::RemoteProcedure::*;
51		match *self {
52			Method(..) => write!(fmt, "<method>"),
53			Notification(..) => write!(fmt, "<notification>"),
54			Alias(ref alias) => write!(fmt, "alias => {:?}", alias)
55		}
56	}
57}
58
59impl<F: Send + Sync + 'static, X: Send + 'static, I> RpcMethodSimple for F where
60	F: Fn(Params) -> I,
61	X: Future<Item = Value, Error = Error>,
62	I: IntoFuture<Item = Value, Error = Error, Future = X>,
63{
64	type Out = X;
65	fn call(&self, params: Params) -> Self::Out {
66		self(params).into_future()
67	}
68}
69
70impl<F: Send + Sync + 'static> RpcNotificationSimple for F where
71	F: Fn(Params),
72{
73	fn execute(&self, params: Params) {
74		self(params)
75	}
76}
77
78impl<F: Send + Sync + 'static, X: Send + 'static, T, I> RpcMethod<T> for F where
79	T: Metadata,
80	F: Fn(Params, T) -> I,
81	I: IntoFuture<Item = Value, Error = Error, Future = X>,
82	X: Future<Item = Value, Error = Error>,
83{
84	fn call(&self, params: Params, meta: T) -> BoxFuture<Value> {
85		Box::new(self(params, meta).into_future())
86	}
87}
88
89impl<F: Send + Sync + 'static, T> RpcNotification<T> for F where
90	T: Metadata,
91	F: Fn(Params, T),
92{
93	fn execute(&self, params: Params, meta: T) {
94		self(params, meta)
95	}
96}