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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
use std::collections::VecDeque;
use std::mem;
use std::net::SocketAddr;
use futures::{future, Async, AsyncSink, Future, Poll, Sink, Stream, sync::{mpsc, oneshot}};
use tokio_executor::{DefaultExecutor, Executor};
use error;
use resp;
use super::connect::{connect, RespConnection};
type PairedConnectionBox = Box<Future<Item = PairedConnection, Error = error::Error> + Send>;
enum SendStatus {
Ok,
End,
Full(resp::RespValue, bool),
}
impl SendStatus {
fn full(msg: resp::RespValue) -> Self {
SendStatus::Full(msg, false)
}
}
enum FlushStatus {
Ok,
Required,
}
enum ReceiveStatus {
ReadyFinished,
ReadyMore,
NotReady,
}
struct PairedConnectionInner {
connection: RespConnection,
out_rx: mpsc::UnboundedReceiver<(resp::RespValue, oneshot::Sender<resp::RespValue>)>,
waiting: VecDeque<oneshot::Sender<resp::RespValue>>,
send_status: SendStatus,
flush_status: FlushStatus,
}
impl PairedConnectionInner {
fn new(
con: RespConnection,
out_rx: mpsc::UnboundedReceiver<(resp::RespValue, oneshot::Sender<resp::RespValue>)>,
) -> Self {
PairedConnectionInner {
connection: con,
out_rx: out_rx,
waiting: VecDeque::new(),
send_status: SendStatus::Ok,
flush_status: FlushStatus::Ok,
}
}
fn impl_start_send(&mut self, msg: resp::RespValue) -> Result<bool, ()> {
match self.connection
.start_send(msg)
.map_err(|e| error!("Error sending message to connection: {}", e))?
{
AsyncSink::Ready => {
self.send_status = SendStatus::Ok;
self.flush_status = FlushStatus::Required;
Ok(true)
}
AsyncSink::NotReady(msg) => {
self.send_status = SendStatus::full(msg);
self.flush_status = FlushStatus::Required;
Ok(false)
}
}
}
fn poll_start_send(&mut self) -> Result<bool, ()> {
let message = match self.send_status {
SendStatus::End | SendStatus::Full(_, false) => return Ok(false),
SendStatus::Full(ref mut msg_rf, true) => unsafe {
mem::replace(msg_rf, mem::uninitialized())
},
SendStatus::Ok => match self.out_rx
.poll()
.map_err(|_| error!("Error polling for messages to send"))?
{
Async::Ready(Some((msg, tx))) => {
self.waiting.push_back(tx);
msg
}
Async::Ready(None) => {
self.send_status = SendStatus::End;
return Ok(false);
}
Async::NotReady => return Ok(false),
},
};
self.impl_start_send(message)
}
fn poll_complete(&mut self) -> Result<(), ()> {
match self.flush_status {
FlushStatus::Ok => (),
FlushStatus::Required => {
match self.connection
.poll_complete()
.map_err(|e| error!("Error polling for completeness: {}", e))?
{
Async::Ready(()) => self.flush_status = FlushStatus::Ok,
Async::NotReady => (),
}
if let SendStatus::Full(_, ref mut post) = self.send_status {
if *post == false {
*post = true;
}
}
}
}
Ok(())
}
fn receive(&mut self) -> Result<ReceiveStatus, ()> {
match self.connection
.poll()
.map_err(|e| error!("Error polling to receive messages: {}", e))?
{
Async::Ready(None) => Ok(ReceiveStatus::ReadyFinished),
Async::Ready(Some(msg)) => {
let tx = self.waiting
.pop_front()
.expect(&format!("Received unexpected message: {:?}", msg));
let _ = tx.send(msg);
if let SendStatus::End = self.send_status {
if self.waiting.is_empty() {
return Ok(ReceiveStatus::ReadyFinished);
}
}
Ok(ReceiveStatus::ReadyMore)
}
Async::NotReady => Ok(ReceiveStatus::NotReady),
}
}
}
impl Future for PairedConnectionInner {
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
let mut sending = true;
while sending {
sending = self.poll_start_send()?;
}
self.poll_complete()?;
let mut receiving = true;
while receiving {
receiving = match self.receive()? {
ReceiveStatus::NotReady => false,
ReceiveStatus::ReadyMore => true,
ReceiveStatus::ReadyFinished => return Ok(Async::Ready(())),
}
}
Ok(Async::NotReady)
}
}
#[derive(Clone)]
pub struct PairedConnection {
out_tx: mpsc::UnboundedSender<(resp::RespValue, oneshot::Sender<resp::RespValue>)>,
}
pub fn paired_connect(addr: &SocketAddr) -> PairedConnectionBox {
let pc_f = connect(addr).map_err(|e| e.into()).map(|connection| {
let (out_tx, out_rx) = mpsc::unbounded();
let paired_connection_inner = Box::new(PairedConnectionInner::new(connection, out_rx));
let mut executor = DefaultExecutor::current();
executor
.spawn(paired_connection_inner)
.expect("Cannot spawn paired connection");
PairedConnection { out_tx }
});
Box::new(pc_f)
}
pub type SendBox<T> = Box<Future<Item = T, Error = error::Error> + Send>;
#[macro_export]
macro_rules! faf {
($e: expr) => {{
use $crate::client::paired::SendBox;
use $crate::resp;
let _: SendBox<resp::RespValue> = $e;
}};
}
impl PairedConnection {
pub fn send<T: resp::FromResp + Send + 'static>(&self, msg: resp::RespValue) -> SendBox<T> {
match &msg {
&resp::RespValue::Array(_) => (),
_ => {
return Box::new(future::err(error::internal(
"Command must be a RespValue::Array",
)))
}
}
let (tx, rx) = oneshot::channel();
self.out_tx
.unbounded_send((msg, tx))
.expect("Cannot send message!");
let future = rx.then(|v| match v {
Ok(v) => future::result(T::from_resp(v)),
Err(e) => future::err(e.into()),
});
Box::new(future)
}
}