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
use bytes::Bytes;
use futures::{Async, Future, Poll};
use codec::MethodCodec;
use channel::{Channel, ChannelFuture};
use load_balancer::CallInfo;
use message::{RpcRequestMeta, RpcResponseMeta};
use service::MethodError;
type ResponsePackage = (RpcResponseMeta, Bytes);
#[allow(missing_debug_implementations)]
#[derive(Clone)]
pub struct RpcWrapper<'a, C: Clone> {
codec: C,
channel: &'a Channel,
}
impl<'a, C: Clone> RpcWrapper<'a, C> {
pub fn new(codec: C, channel: &'a Channel) -> Self {
RpcWrapper { codec, channel }
}
}
impl<'a, C> RpcWrapper<'a, C>
where
C: MethodCodec + Clone,
{
pub fn call(&'a self, bundle: (C::Response, String, String)) -> StubFuture<C> {
let (req, service_name, method_name) = bundle;
let channel_fut = match self.codec.encode(req) {
Ok(body) => {
let mut meta = RpcRequestMeta::new();
meta.set_service_name(service_name);
meta.set_method_name(method_name);
Some(self.channel.call((meta, body)))
}
Err(_) => None,
};
StubFuture::new(channel_fut, self.codec.clone())
}
}
fn errno_to_result(result: ResponsePackage) -> Result<Bytes, MethodError> {
let (meta, body) = result;
let error_code = meta.get_error_code();
if error_code == 0 {
Ok(body)
} else {
error!("Server mark rpc to failed");
Err(MethodError::UnknownError)
}
}
#[derive(Debug)]
pub struct StubFuture<C> {
start_usec: u64,
inner: Option<ChannelFuture>,
codec: C,
}
impl<C> StubFuture<C> {
pub fn new(inner: Option<ChannelFuture>, codec: C) -> Self {
StubFuture {
start_usec: 0,
inner,
codec,
}
}
}
impl<C> Future for StubFuture<C>
where
C: MethodCodec,
{
type Item = (C::Request, RpcInfo);
type Error = MethodError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
if let Some(ref mut channel) = self.inner {
match channel.poll() {
Ok(Async::Ready((resp, fb_handle))) => {
let body = errno_to_result(resp)?;
let resp = self.codec
.decode(body)
.map_err(|_| MethodError::CodecError)?;
let fb = CallInfo::new(self.start_usec, None);
let info = RpcInfo;
fb_handle.call(fb);
Ok(Async::Ready((resp, info)))
}
Ok(Async::NotReady) => Ok(Async::NotReady),
Err(_) => Err(MethodError::UnknownError),
}
} else {
Err(MethodError::CodecError)
}
}
}
#[derive(Clone, Debug)]
pub struct RpcInfo;