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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
use buf::SendBuf;
use {flush, Body, RecvBody};

use tower::MakeService;
use tower_service::Service;

use futures::future::{Either, Executor, Join, MapErr};
use futures::{Async, Future, Poll, Stream};
use h2;
use h2::server::{Connection as Accept, Handshake, SendResponse};
use http::{Request, Response};
use tokio_io::{AsyncRead, AsyncWrite};

use std::marker::PhantomData;
use std::{error, fmt, mem};

/// Attaches service implementations to h2 connections.
pub struct Server<S, E, B>
where
    S: MakeService<(), Request<RecvBody>>,
    B: Body,
{
    new_service: S,
    builder: h2::server::Builder,
    executor: E,
    _p: PhantomData<B>,
}

/// Drives connection-level I/O .
pub struct Connection<T, S, E, B, F>
where
    T: AsyncRead + AsyncWrite,
    S: MakeService<(), Request<RecvBody>>,
    B: Body,
{
    state: State<T, S, B>,
    executor: E,
    modify: F,
}

/// Modify a received request
pub trait Modify {
    /// Modify a request before calling the service.
    fn modify(&mut self, request: &mut Request<()>);
}

enum State<T, S, B>
where
    T: AsyncRead + AsyncWrite,
    S: MakeService<(), Request<RecvBody>>,
    B: Body,
{
    /// Establish the HTTP/2.0 connection and get a service to process inbound
    /// requests.
    Init(Init<T, SendBuf<B::Data>, S::Future, S::MakeError>),

    /// Both the HTTP/2.0 connection and the service are ready.
    Ready {
        connection: Accept<T, SendBuf<B::Data>>,
        service: S::Service,
    },

    /// The service has closed, so poll until connection is closed.
    GoAway {
        connection: Accept<T, SendBuf<B::Data>>,
        error: Error<S>,
    },

    /// Everything is closed up.
    Done,
}

type Init<T, B, S, E> = Join<MapErr<Handshake<T, B>, MapErrA<E>>, MapErr<S, MapErrB<E>>>;

type MapErrA<E> = fn(h2::Error) -> Either<h2::Error, E>;
type MapErrB<E> = fn(E) -> Either<h2::Error, E>;

/// Task used to process requests
pub struct Background<T, B>
where
    B: Body,
{
    state: BackgroundState<T, B>,
}

enum BackgroundState<T, B>
where
    B: Body,
{
    Respond {
        respond: SendResponse<SendBuf<B::Data>>,
        response: T,
    },
    Flush(flush::Flush<B>),
}

/// Error produced by a `Connection`.
pub enum Error<S>
where
    S: MakeService<(), Request<RecvBody>>,
{
    /// Error produced during the HTTP/2.0 handshake.
    Handshake(h2::Error),

    /// Error produced by the HTTP/2.0 stream
    Protocol(h2::Error),

    /// Error produced when obtaining the service
    NewService(S::MakeError),

    /// Error produced by the service
    Service(S::Error),

    /// Error produced when attempting to spawn a task
    Execute,
}

enum PollMain {
    Again,
    Done,
}

// ===== impl Server =====

impl<S, E, B> Server<S, E, B>
where
    S: MakeService<(), Request<RecvBody>, Response = Response<B>>,
    S::Error: Into<Box<dyn std::error::Error>>,
    B: Body + 'static,
    B::Error: Into<Box<dyn std::error::Error>>,
    E: Clone + Executor<Background<<S::Service as Service<Request<RecvBody>>>::Future, B>>,
{
    pub fn new(new_service: S, builder: h2::server::Builder, executor: E) -> Self {
        Server {
            new_service,
            executor,
            builder,
            _p: PhantomData,
        }
    }
}

impl<S, E, B> Server<S, E, B>
where
    S: MakeService<(), Request<RecvBody>, Response = Response<B>>,
    B: Body,
    B::Data: 'static,
    B::Error: Into<Box<dyn std::error::Error>>,
    E: Clone,
{
    /// Produces a future that is satisfied once the h2 connection has been initialized.
    pub fn serve<T>(&mut self, io: T) -> Connection<T, S, E, B, ()>
    where
        T: AsyncRead + AsyncWrite,
    {
        self.serve_modified(io, ())
    }

    pub fn serve_modified<T, F>(&mut self, io: T, modify: F) -> Connection<T, S, E, B, F>
    where
        T: AsyncRead + AsyncWrite,
        F: Modify,
    {
        // Clone a handle to the executor so that it can be moved into the
        // connection handle
        let executor = self.executor.clone();

        let service = self
            .new_service
            .make_service(())
            .map_err(Either::B as MapErrB<S::MakeError>);

        // TODO we should specify initial settings here!
        let handshake = self
            .builder
            .handshake(io)
            .map_err(Either::A as MapErrA<S::MakeError>);

        Connection {
            state: State::Init(handshake.join(service)),
            executor,
            modify,
        }
    }
}

// B doesn't need to be Clone, it's just a marker type.
impl<S, E, B> Clone for Server<S, E, B>
where
    S: MakeService<(), Request<RecvBody>> + Clone,
    E: Clone,
    B: Body,
{
    fn clone(&self) -> Self {
        Server {
            new_service: self.new_service.clone(),
            executor: self.executor.clone(),
            builder: self.builder.clone(),
            _p: PhantomData,
        }
    }
}

// ===== impl Connection =====

impl<T, S, E, B, F> Future for Connection<T, S, E, B, F>
where
    T: AsyncRead + AsyncWrite,
    S: MakeService<(), Request<RecvBody>, Response = Response<B>>,
    S::Error: Into<Box<dyn std::error::Error>>,
    E: Executor<Background<<S::Service as Service<Request<RecvBody>>>::Future, B>>,
    B: Body + 'static,
    B::Error: Into<Box<dyn std::error::Error>>,
    F: Modify,
{
    type Item = ();
    type Error = Error<S>;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        // Code is in poll2 to make sure any Err returned
        // transitions state to State::Done.
        self.poll2().map_err(|e| {
            self.state = State::Done;
            e
        })
    }
}

impl<T, S, E, B, F> Connection<T, S, E, B, F>
where
    T: AsyncRead + AsyncWrite,
    S: MakeService<(), Request<RecvBody>, Response = Response<B>>,
    S::Error: Into<Box<dyn std::error::Error>>,
    E: Executor<Background<<S::Service as Service<Request<RecvBody>>>::Future, B>>,
    B: Body + 'static,
    B::Error: Into<Box<dyn std::error::Error>>,
    F: Modify,
{
    /// Start an HTTP2 graceful shutdown.
    ///
    /// The `Connection` must continue to be polled until shutdown completes.
    pub fn graceful_shutdown(&mut self) {
        match self.state {
            State::Init(_) => {
                // Never connected, just switch to Done...
            }
            State::Ready {
                ref mut connection, ..
            } => {
                connection.graceful_shutdown();
                return;
            }
            State::GoAway { .. } => return,
            State::Done => return,
        }

        self.state = State::Done;
    }

    fn poll2(&mut self) -> Poll<(), Error<S>> {
        loop {
            match self.state {
                State::Init(..) => try_ready!(self.poll_init()),
                State::Ready { .. } => match try_ready!(self.poll_main()) {
                    PollMain::Again => continue,
                    PollMain::Done => {
                        self.state = State::Done;
                        return Ok(().into());
                    }
                },
                State::GoAway { .. } => try_ready!(self.poll_goaway()),
                State::Done => return Ok(().into()),
            }
        }
    }

    fn poll_init(&mut self) -> Poll<(), Error<S>> {
        use self::State::*;

        let (connection, service) = match self.state {
            Init(ref mut join) => try_ready!(join.poll().map_err(Error::from_init)),
            _ => unreachable!(),
        };

        self.state = Ready {
            connection,
            service,
        };

        Ok(().into())
    }

    fn poll_main(&mut self) -> Poll<PollMain, Error<S>> {
        let error = match self.state {
            State::Ready {
                ref mut connection,
                ref mut service,
            } => loop {
                // Make sure the service is ready
                match service.poll_ready() {
                    Ok(Async::Ready(())) => (),
                    Ok(Async::NotReady) => {
                        // Just because the service isn't ready doesn't mean
                        // we do nothing. We must keep polling the connection
                        // regardless. However, since we don't want to accept
                        // a request, we `poll_close` instead of `poll`.
                        let next = connection.poll_close().map_err(Error::Protocol);

                        // If not ready, we'll get polled again.
                        try_ready!(next);

                        // If poll_close was ready, that means the connection
                        // is closed. All done!
                        return Ok(PollMain::Done.into());
                    }
                    Err(err) => {
                        trace!("service closed");
                        // service is closed, transition to goaway state
                        break Error::Service(err);
                    }
                }

                let next = connection.poll().map_err(Error::Protocol);

                let (request, respond) = match try_ready!(next) {
                    Some(next) => next,
                    None => return Ok(PollMain::Done.into()),
                };

                let (parts, body) = request.into_parts();

                // This is really unfortunate, but the `http` currently lacks the
                // APIs to do this better :(
                let mut request = Request::from_parts(parts, ());
                self.modify.modify(&mut request);

                let (parts, _) = request.into_parts();
                let request = Request::from_parts(parts, RecvBody::new(body));

                // Dispatch the request to the service
                let response = service.call(request);

                // Spawn a new task to process the response future
                if let Err(_) = self.executor.execute(Background::new(respond, response)) {
                    break Error::Execute;
                }
            },
            _ => unreachable!(),
        };

        // We only break out of the loop on an error, which means we
        // should transition to GOAWAY.
        match mem::replace(&mut self.state, State::Done) {
            State::Ready { mut connection, .. } => {
                connection.graceful_shutdown();

                self.state = State::GoAway { connection, error };

                Ok(Async::Ready(PollMain::Again))
            }
            _ => unreachable!(),
        }
    }

    fn poll_goaway(&mut self) -> Poll<(), Error<S>> {
        match self.state {
            State::GoAway {
                ref mut connection, ..
            } => {
                try_ready!(connection.poll_close().map_err(Error::Protocol));
            }
            _ => unreachable!(),
        }

        // Once here, the connection has finished successfully. Time to just
        // return the service error.
        match mem::replace(&mut self.state, State::Done) {
            State::GoAway { error, .. } => {
                trace!("goaway completed");
                Err(error)
            }
            _ => unreachable!(),
        }
    }
}

// ===== impl Modify =====

impl<T> Modify for T
where
    T: FnMut(&mut Request<()>),
{
    fn modify(&mut self, request: &mut Request<()>) {
        (*self)(request);
    }
}

impl Modify for () {
    fn modify(&mut self, _: &mut Request<()>) {}
}

// ===== impl Background =====

impl<T, B> Background<T, B>
where
    T: Future,
    B: Body,
{
    fn new(respond: SendResponse<SendBuf<B::Data>>, response: T) -> Self {
        Background {
            state: BackgroundState::Respond { respond, response },
        }
    }
}

impl<T, B> Future for Background<T, B>
where
    T: Future<Item = Response<B>>,
    T::Error: Into<Box<dyn std::error::Error>>,
    B: Body,
    B::Error: Into<Box<dyn std::error::Error>>,
{
    type Item = ();
    type Error = ();

    fn poll(&mut self) -> Poll<(), ()> {
        use self::BackgroundState::*;

        loop {
            let flush = match self.state {
                Respond {
                    ref mut respond,
                    ref mut response,
                } => {
                    use flush::Flush;

                    // Check if the client has reset this stream...
                    match respond.poll_reset() {
                        Ok(Async::Ready(reason)) => {
                            debug!("stream received RST_FRAME: {:?}", reason);
                            return Ok(().into());
                        }
                        Ok(Async::NotReady) => {
                            // The client hasn't reset this stream yet, so keep
                            // trying to process the response future. This will
                            // have registered this task in case the client
                            // DOES reset at a later point.
                        }
                        Err(err) => {
                            debug!("stream poll_reset received error: {}", err);
                            return Err(());
                        }
                    }

                    let response = try_ready!(response.poll().map_err(|err| {
                        let err = err.into();
                        debug!("user service error: {}", err);
                        let reason = ::error::reason_from_dyn_error(&*err);
                        respond.send_reset(reason);
                    }));

                    let (parts, body) = response.into_parts();

                    // Check if the response is immediately an end-of-stream.
                    let eos = body.is_end_stream();

                    // Try sending the response.
                    let response = Response::from_parts(parts, ());
                    match respond.send_response(response, eos) {
                        Ok(stream) => {
                            if eos {
                                // Nothing more to do
                                return Ok(().into());
                            }

                            // Transition to flushing the body
                            Flush::new(body, stream)
                        }
                        Err(err) => {
                            warn!("error sending response: {:?}", err);
                            return Ok(().into());
                        }
                    }
                }
                Flush(ref mut flush) => return flush.poll(),
            };

            self.state = Flush(flush);
        }
    }
}

// ===== impl Error =====

impl<S> Error<S>
where
    S: MakeService<(), Request<RecvBody>>,
{
    fn from_init(err: Either<h2::Error, S::MakeError>) -> Self {
        match err {
            Either::A(err) => Error::Handshake(err),
            Either::B(err) => Error::NewService(err),
        }
    }
}

impl<S> fmt::Debug for Error<S>
where
    S: MakeService<(), Request<RecvBody>>,
    S::MakeError: fmt::Debug,
    S::Error: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Error::Handshake(ref why) => f.debug_tuple("Handshake").field(why).finish(),
            Error::Protocol(ref why) => f.debug_tuple("Protocol").field(why).finish(),
            Error::NewService(ref why) => f.debug_tuple("NewService").field(why).finish(),
            Error::Service(ref why) => f.debug_tuple("Service").field(why).finish(),
            Error::Execute => f.debug_tuple("Execute").finish(),
        }
    }
}

impl<S> fmt::Display for Error<S>
where
    S: MakeService<(), Request<RecvBody>>,
    S::MakeError: fmt::Display,
    S::Error: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Error::Handshake(ref why) => {
                write!(f, "Error occurred during HTTP/2.0 handshake: {}", why)
            }
            Error::Protocol(ref why) => write!(f, "Error produced by HTTP/2.0 stream: {}", why),
            Error::NewService(ref why) => {
                write!(f, "Error occurred while obtaining service: {}", why)
            }
            Error::Service(ref why) => write!(f, "Error returned by service: {}", why),
            Error::Execute => write!(f, "Error occurred while attempting to spawn a task"),
        }
    }
}

impl<S> error::Error for Error<S>
where
    S: MakeService<(), Request<RecvBody>>,
    S::MakeError: error::Error,
    S::Error: error::Error,
{
    fn cause(&self) -> Option<&error::Error> {
        match *self {
            Error::Handshake(ref why) => Some(why),
            Error::Protocol(ref why) => Some(why),
            Error::NewService(ref why) => Some(why),
            Error::Service(ref why) => Some(why),
            Error::Execute => None,
        }
    }

    fn description(&self) -> &str {
        match *self {
            Error::Handshake(_) => "error occurred during HTTP/2.0 handshake",
            Error::Protocol(_) => "error produced by HTTP/2.0 stream",
            Error::NewService(_) => "error occured while obtaining service",
            Error::Service(_) => "error returned by service",
            Error::Execute => "error occurred while attempting to spawn a task",
        }
    }
}