-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathclient.rs
421 lines (378 loc) · 13.7 KB
/
client.rs
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
use crate::NewTransport;
use futures::future;
use futures::sync::oneshot;
use futures::{Async, AsyncSink, Future, Poll, Sink, Stream};
use std::collections::VecDeque;
use std::marker::PhantomData;
use std::{error, fmt};
use tokio_executor::DefaultExecutor;
use tower_buffer::{Buffer, DirectServiceRef};
use tower_direct_service::DirectService;
use tower_service::Service;
/// This type provides an implementation of a Tower
/// [`Service`](https://docs.rs/tokio-service/0.1/tokio_service/trait.Service.html) on top of a
/// request-at-a-time protocol transport. In particular, it wraps a transport that implements
/// `Sink<SinkItem = Request>` and `Stream<Item = Response>` with the necessary bookkeeping to
/// adhere to Tower's convenient `fn(Request) -> Future<Response>` API.
pub struct Client<T, E>
where
T: Sink + Stream,
{
requests: VecDeque<T::SinkItem>,
responses: VecDeque<oneshot::Sender<T::Item>>,
transport: T,
max_in_flight: Option<usize>,
in_flight: usize,
finish: bool,
#[allow(unused)]
error: PhantomData<E>,
}
/// A factory that makes new [`Client`] instances by creating new transports and wrapping them in
/// fresh `Client`s.
pub struct Maker<NT, Request> {
t_maker: NT,
_req: PhantomData<Request>,
in_flight: Option<usize>,
}
impl<NT, Request> Maker<NT, Request> {
/// Make a new `Client` factory that uses the given transport factory.
pub fn new(t: NT) -> Self {
Maker {
t_maker: t,
_req: PhantomData,
in_flight: None,
}
}
/// Limit each new `Client` instance to `in_flight` pending requests.
pub fn with_limit(mut self, in_flight: usize) -> Self {
self.in_flight = Some(in_flight);
self
}
}
/// A `Future` that will resolve into a `Buffer<Client<T::Transport>>`.
pub struct NewSpawnedClientFuture<NT, Request>
where
NT: NewTransport<Request>,
{
maker: Option<NT::TransportFut>,
in_flight: Option<usize>,
}
/// A failure to spawn a new `Client`.
#[derive(Debug)]
pub enum SpawnError<E> {
/// The executor failed to spawn the `tower_buffer::Worker`.
SpawnFailed,
/// A new `Transport` could not be produced.
Inner(E),
}
impl<NT, Request> Future for NewSpawnedClientFuture<NT, Request>
where
NT: NewTransport<Request>,
NT::Transport: 'static + Send,
<NT::Transport as Sink>::SinkItem: 'static + Send,
<NT::Transport as Stream>::Item: 'static + Send,
<NT::Transport as Sink>::SinkError: 'static + Send,
<NT::Transport as Stream>::Error: 'static + Send,
{
type Item = Buffer<DirectServiceRef<Client<NT::Transport, Error<NT::Transport>>>, Request>;
type Error = SpawnError<NT::InitError>;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match self.maker.take() {
None => unreachable!("poll called after future resolved"),
Some(mut fut) => match fut.poll().map_err(SpawnError::Inner)? {
Async::Ready(t) => {
let c = if let Some(f) = self.in_flight {
Client::with_limit(t, f)
} else {
Client::new(t)
};
Ok(Async::Ready(
Buffer::new_direct(c, 0, &DefaultExecutor::current())
.map_err(|_| SpawnError::SpawnFailed)?,
))
}
Async::NotReady => {
self.maker = Some(fut);
Ok(Async::NotReady)
}
},
}
}
}
impl<NT, Request> Service<()> for Maker<NT, Request>
where
NT: NewTransport<Request>,
NT::Transport: 'static + Send,
Request: 'static + Send,
<NT::Transport as Stream>::Item: 'static + Send,
<NT::Transport as Sink>::SinkError: 'static + Send,
<NT::Transport as Stream>::Error: 'static + Send,
{
type Error = SpawnError<NT::InitError>;
type Response = Buffer<DirectServiceRef<Client<NT::Transport, Error<NT::Transport>>>, Request>;
type Future = NewSpawnedClientFuture<NT, Request>;
fn call(&mut self, _: ()) -> Self::Future {
NewSpawnedClientFuture {
maker: Some(self.t_maker.new_transport()),
in_flight: self.in_flight.clone(),
}
}
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
}
/// An error that occurred while servicing a request.
pub enum Error<T>
where
T: Sink + Stream,
{
/// The underlying transport failed to send a request.
BrokenTransportSend(T::SinkError),
/// The underlying transport failed while attempting to receive a response.
///
/// If `None`, the transport closed without error while there were pending requests.
BrokenTransportRecv(Option<T::Error>),
/// Attempted to issue a `call` when no more requests can be in flight.
///
/// See [`tower_service::Service::poll_ready`] and [`Client::with_limit`].
TransportFull,
/// Attempted to issue a `call`, but the underlying transport has been closed.
ClientDropped,
}
impl<T> fmt::Display for Error<T>
where
T: Sink + Stream,
T::SinkError: fmt::Display,
T::Error: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::BrokenTransportSend(ref se) => fmt::Display::fmt(se, f),
Error::BrokenTransportRecv(Some(ref se)) => fmt::Display::fmt(se, f),
Error::BrokenTransportRecv(None) => f.pad("transport closed with in-flight requests"),
Error::TransportFull => f.pad("no more in-flight requests allowed"),
Error::ClientDropped => f.pad("Client was dropped"),
}
}
}
impl<T> fmt::Debug for Error<T>
where
T: Sink + Stream,
T::SinkError: fmt::Debug,
T::Error: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::BrokenTransportSend(ref se) => write!(f, "BrokenTransportSend({:?})", se),
Error::BrokenTransportRecv(Some(ref se)) => write!(f, "BrokenTransportRecv({:?})", se),
Error::BrokenTransportRecv(None) => f.pad("BrokenTransportRecv"),
Error::TransportFull => f.pad("TransportFull"),
Error::ClientDropped => f.pad("ClientDropped"),
}
}
}
impl<T> error::Error for Error<T>
where
T: Sink + Stream,
T::SinkError: error::Error,
T::Error: error::Error,
{
fn cause(&self) -> Option<&error::Error> {
match *self {
Error::BrokenTransportSend(ref se) => Some(se),
Error::BrokenTransportRecv(Some(ref se)) => Some(se),
_ => None,
}
}
fn description(&self) -> &str {
match *self {
Error::BrokenTransportSend(ref se) => se.description(),
Error::BrokenTransportRecv(Some(ref se)) => se.description(),
Error::BrokenTransportRecv(None) => "transport closed with in-flight requests",
Error::TransportFull => "no more in-flight requests allowed",
Error::ClientDropped => "Client was dropped",
}
}
}
impl<T> Error<T>
where
T: Sink + Stream,
{
fn from_sink_error(e: T::SinkError) -> Self {
Error::BrokenTransportSend(e)
}
fn from_stream_error(e: T::Error) -> Self {
Error::BrokenTransportRecv(Some(e))
}
}
impl<T, E> Client<T, E>
where
T: Sink + Stream,
E: From<Error<T>>,
{
/// Construct a new [`Client`] over the given `transport` with no limit on the number of
/// in-flight requests.
pub fn new(transport: T) -> Self {
Client {
requests: VecDeque::default(),
responses: VecDeque::default(),
transport,
max_in_flight: None,
in_flight: 0,
error: PhantomData::<E>,
finish: false,
}
}
/// Construct a new [`Client`] over the given `transport` with a maxmimum limit on the number
/// of in-flight requests.
///
/// Note that setting the limit to 1 implies that for each `Request`, the `Response` must be
/// received before another request is sent on the same transport.
pub fn with_limit(transport: T, max_in_flight: usize) -> Self {
Client {
requests: VecDeque::with_capacity(max_in_flight),
responses: VecDeque::with_capacity(max_in_flight),
transport,
max_in_flight: Some(max_in_flight),
in_flight: 0,
error: PhantomData::<E>,
finish: false,
}
}
}
impl<T, E> DirectService<T::SinkItem> for Client<T, E>
where
T: Sink + Stream,
E: From<Error<T>>,
E: 'static + Send,
T::SinkItem: 'static + Send,
T::Item: 'static + Send,
{
type Response = T::Item;
type Error = E;
// TODO: get rid of Box + Send bound here by using existential types
type Future = Box<Future<Item = Self::Response, Error = Self::Error> + Send>;
fn poll_ready(&mut self) -> Result<Async<()>, Self::Error> {
if let Some(mif) = self.max_in_flight {
if self.in_flight + self.requests.len() >= mif {
// not enough request slots -- need to handle some outstanding
self.poll_service()?;
if self.in_flight + self.requests.len() >= mif {
// that didn't help -- wait to be awoken again
return Ok(Async::NotReady);
}
}
}
return Ok(Async::Ready(()));
}
fn poll_service(&mut self) -> Result<Async<()>, Self::Error> {
loop {
// send more requests if we have them
while let Some(req) = self.requests.pop_front() {
if let AsyncSink::NotReady(req) = self
.transport
.start_send(req)
.map_err(Error::from_sink_error)?
{
self.requests.push_front(req);
break;
} else {
self.in_flight += 1;
}
}
if self.in_flight != 0 {
// flush out any stuff we've sent in the past
// don't return on NotReady since we have to check for responses too
if self.finish && self.requests.is_empty() {
// we're closing up shop!
//
// note that the check for requests.is_empty() is necessary, because
// Sink::close() requires that we never call start_send ever again!
//
// close() implies poll_complete()
//
// FIXME: if close returns Ready, are we allowed to call close again?
self.transport.close().map_err(Error::from_sink_error)?;
} else {
self.transport
.poll_complete()
.map_err(Error::from_sink_error)?;
}
}
// and start looking for replies.
//
// note that we *could* have this just be a loop, but we don't want to poll the stream
// if we know there's nothing for it to produce.
while self.in_flight != 0 {
match try_ready!(self.transport.poll().map_err(Error::from_stream_error)) {
Some(r) => {
// ignore send failures
// the client may just no longer care about the response
let sender = self
.responses
.pop_front()
.expect("got a request with no sender?");
let _ = sender.send(r);
self.in_flight -= 1;
}
None => {
// the transport terminated while we were waiting for a response!
// TODO: it'd be nice if we could return the transport here..
return Err(E::from(Error::BrokenTransportRecv(None)));
}
}
}
if self.requests.is_empty() && self.in_flight == 0 {
if self.finish {
// we're completely done once close() finishes!
try_ready!(self.transport.close().map_err(Error::from_sink_error));
}
return Ok(Async::Ready(()));
}
}
}
fn poll_close(&mut self) -> Result<Async<()>, Self::Error> {
self.finish = true;
self.poll_service()
}
fn call(&mut self, req: T::SinkItem) -> Self::Future {
if let Some(mif) = self.max_in_flight {
if self.in_flight + self.requests.len() >= mif {
return Box::new(future::err(E::from(Error::TransportFull)));
}
}
assert!(!self.finish, "invoked call() after poll_close()");
let (tx, rx) = oneshot::channel();
self.requests.push_back(req);
self.responses.push_back(tx);
Box::new(rx.map_err(|_| E::from(Error::ClientDropped)))
}
}
// ===== impl SpawnError =====
impl<T> fmt::Display for SpawnError<T>
where
T: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
SpawnError::SpawnFailed => write!(f, "error spawning multiplex client"),
SpawnError::Inner(ref te) => {
write!(f, "error making new multiplex transport: {:?}", te)
}
}
}
}
impl<T> error::Error for SpawnError<T>
where
T: error::Error,
{
fn cause(&self) -> Option<&error::Error> {
match *self {
SpawnError::SpawnFailed => None,
SpawnError::Inner(ref te) => Some(te),
}
}
fn description(&self) -> &str {
"error creating new multiplex client"
}
}