1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
use actix_wamp::{Error, RpcCallRequest, RpcCallResponse, RpcEndpoint, ToArgs};
pub use futures::future::{self, Future};
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::borrow::Cow;

pub mod wamp {
    pub use actix_wamp::{Error, RpcCallRequest, RpcCallResponse, RpcEndpoint, ToArgs};
    pub use futures::Future;
}

pub struct Invoker<'a, Inner: RpcEndpoint + ?Sized>(&'a Inner);

pub trait AsInvoker: RpcEndpoint {
    fn as_invoker<'a>(&'a self) -> Invoker<'a, Self>;
}

impl<Inner: RpcEndpoint> AsInvoker for Inner {
    fn as_invoker<'a>(&'a self) -> Invoker<'a, Self> {
        Invoker(self)
    }
}

impl<'a, Inner: RpcEndpoint + ?Sized> Invoker<'a, Inner> {
    pub fn rpc_call<'args, Args: ToArgs + 'args, Ret: DeserializeOwned + 'static>(
        &self,
        uri: &'static str,
        args: &Args,
    ) -> impl Future<Item = Ret, Error = Error> + 'static {
        let request = match RpcCallRequest::with_args(uri, args) {
            Ok(resuest) => resuest,
            Err(e) => return future::Either::B(future::err(e)),
        };
        future::Either::A(self.0.rpc_call(request).and_then(
            move |RpcCallResponse { args, .. }| {
                if args.len() != 1 {
                    Err(Error::protocol_err(
                        "invalid rpc response, only 1 args expected",
                    ))
                } else {
                    Ok(serde_json::from_value(args[0].clone()).map_err(move |e| {
                        log::error!("on {} unable to parse: {:?}: {}", uri, args, e);
                        e
                    })?)
                }
            },
        ))
    }

    pub fn rpc_va_call<T: Serialize, Ret: DeserializeOwned + 'static>(
        &self,
        uri: impl Into<Cow<'static, str>>,
        va_args: &Vec<T>,
    ) -> impl Future<Item = Ret, Error = Error> + 'static {
        let uri = uri.into().to_owned();
        let request = match RpcCallRequest::with_va_args(uri.clone(), va_args) {
            Ok(resuest) => resuest,
            Err(e) => return future::Either::B(future::err(e)),
        };
        future::Either::A(self.0.rpc_call(request).and_then(
            move |RpcCallResponse { args, .. }| {
                if args.len() != 1 {
                    Err(Error::protocol_err(
                        "invalid rpc response, only 1 args expected",
                    ))
                } else {
                    Ok(serde_json::from_value(args[0].clone()).map_err(move |e| {
                        log::error!("on {} unable to parse: {:?}: {}", uri, args, e);
                        e
                    })?)
                }
            },
        ))
    }
}

#[macro_export]
macro_rules! rpc_interface {
    {
        trait $interface_name:ident {
            $(
                $(#[doc = $doc:expr])*
                #[id = $rpc_uri:expr]
                fn $it:tt $args:tt -> Result<$ret:ty>;
            )*
        }

        $(
            converter $converter_name:ident $converter_method:ident;
        )?
    }

     => {
        pub struct $interface_name<'a, Inner: $crate::rpc::wamp::RpcEndpoint + ?Sized>($crate::rpc::Invoker<'a, Inner>);

        impl<'a, Inner: $crate::rpc::wamp::RpcEndpoint + ?Sized + 'static> $interface_name<'a, Inner> {
            $(

                impl_async_rpc_item! {
                    $(#[doc = $doc])*
                    #[id = $rpc_uri]
                    fn $it $args -> Result<$ret, Error>;
                }

            )*
        }

        $(
            pub trait $converter_name : $crate::rpc::wamp::RpcEndpoint {
                fn $converter_method<'a>(&'a self ) -> $interface_name<'a, Self>;
            }

            impl<Endpoint: $crate::rpc::wamp::RpcEndpoint> $converter_name for Endpoint {
                fn $converter_method<'a>(&'a self) -> $interface_name<'a, Endpoint> {
                    $interface_name(self.as_invoker())
                }
            }
        )?

     };
}

#[macro_export]
#[doc(hidden)]
macro_rules! impl_async_rpc_item {
    {
                $(#[doc = $doc:expr])*
                #[id = $rpc_uri:expr]
                fn $name:ident(&self) -> Result<$ret:ty, Error>;

    } => {
                $(#[doc = $doc])*
                #[doc = "RPC uri="]
                #[doc = $rpc_uri]
                pub fn $name<'b>(&'b self) -> impl $crate::rpc::wamp::Future<Item=$ret, Error=$crate::rpc::wamp::Error> + 'static {
                    self.0.rpc_call($rpc_uri, &())
                }
    };

    {
                $(#[doc = $doc:expr])*
                #[id = $rpc_uri:expr]
                fn $name:ident(&self $(, $arg_id:ident : $t:ty)* $(, #[kwarg] $kw_arg_id:ident : $kw_t:ty)*) -> Result<$ret:ty, Error>;

    }=> {
                $(#[doc = $doc])*
                #[doc = "RPC uri="]
                #[doc = $rpc_uri]
                #[allow(unused)]
                pub fn $name(&self $(, $arg_id : $t)* $(, $kw_arg_id : $kw_t)*) -> impl $crate::rpc::wamp::Future<Item=$ret, Error=$crate::rpc::wamp::Error> {
                    self.0.rpc_call($rpc_uri, &($($arg_id,)*))
                }
    };


    {
                $(#[doc = $doc:expr])*
                #[id = $rpc_uri:expr]
                fn $name:ident(&self $(, #[kwarg] $kw_arg_id:ident : $kw_t:ty)+) -> Result<$ret:ty, Error>;

    } => {
                $(#[doc = $doc])*
                #[doc = "RPC uri="]
                #[doc = $rpc_uri]
                pub fn $name<'b>(&'b self $(, $kw_arg_id : $kw_t)+) -> impl $crate::rpc::wamp::Future<Item=$ret, Error=$crate::rpc::wamp::Error> + 'static {
                    self.0.rpc_call($rpc_uri, &())
                }
    };
}

#[cfg(test)]
#[allow(dead_code)]
mod test {

    use super::*;

    rpc_interface! {
    trait Test {

        /// Test function example
        #[id = "test"]
        fn test(&self, a : u8) -> Result<()>;

        #[id = "rpc.test.x2"]
        fn test2(&self) -> Result<Vec<String>>;
    }
    }

    pub trait AsTest: RpcEndpoint {
        fn as_test<'a>(&'a self) -> Test<'a, Self>;
    }

    impl<Endpoint: RpcEndpoint> AsTest for Endpoint {
        fn as_test<'a>(&'a self) -> Test<'a, Endpoint> {
            Test(self.as_invoker())
        }
    }

    struct RpcMock;

    impl RpcEndpoint for RpcMock {
        type Response = future::FutureResult<RpcCallResponse, Error>;

        fn rpc_call(&self, request: RpcCallRequest) -> Self::Response {
            eprintln!("request={:?}", request);
            future::ok(RpcCallResponse::default())
        }
    }

    #[test]
    fn test_compile() {
        let rpc = RpcMock;
        let t = rpc.as_test();

        let _ = t.test(10);
    }
}