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
#![allow(warnings)]
use streaming::Message;
use tokio_service::Service;
use futures::{Future, Async, Poll, Stream, AsyncSink, Sink};
use futures::sync::mpsc;
use futures::sync::oneshot;
use std::{fmt, io};
use std::cell::RefCell;
pub struct ClientProxy<R, S, E> {
tx: RefCell<mpsc::UnboundedSender<io::Result<Envelope<R, S, E>>>>,
}
impl<R, S, E> Clone for ClientProxy<R, S, E> {
fn clone(&self) -> Self {
ClientProxy {
tx: RefCell::new(self.tx.borrow().clone()),
}
}
}
pub struct Response<T, E> {
inner: oneshot::Receiver<Result<T, E>>,
}
type Envelope<R, S, E> = (R, oneshot::Sender<Result<S, E>>);
pub type Pair<R, S, E> = (ClientProxy<R, S, E>, Receiver<R, S, E>);
pub type Receiver<R, S, E> = mpsc::UnboundedReceiver<io::Result<Envelope<R, S, E>>>;
pub fn pair<R, S, E>() -> Pair<R, S, E> {
let (tx, rx) = mpsc::unbounded();
let client = ClientProxy { tx: RefCell::new(tx) };
(client, rx)
}
impl<R, S, E: From<io::Error>> Service for ClientProxy<R, S, E> {
type Request = R;
type Response = S;
type Error = E;
type Future = Response<S, E>;
fn call(&self, request: R) -> Self::Future {
let (tx, rx) = oneshot::channel();
let _ = mpsc::UnboundedSender::send(&mut self.tx.borrow_mut(),
Ok((request, tx)));
Response { inner: rx }
}
}
impl<R, S, E> fmt::Debug for ClientProxy<R, S, E>
where R: fmt::Debug,
S: fmt::Debug,
E: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ClientProxy {{ ... }}")
}
}
impl<T, E> Future for Response<T, E>
where E: From<io::Error>,
{
type Item = T;
type Error = E;
fn poll(&mut self) -> Poll<T, E> {
match self.inner.poll() {
Ok(Async::Ready(Ok(v))) => Ok(Async::Ready(v)),
Ok(Async::Ready(Err(e))) => Err(e),
Ok(Async::NotReady) => Ok(Async::NotReady),
Err(_) => {
let e = io::Error::new(io::ErrorKind::BrokenPipe, "broken pipe");
Err(e.into())
}
}
}
}
impl<T, E> fmt::Debug for Response<T, E>
where T: fmt::Debug,
E: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Response {{ ... }}")
}
}