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
use super::{Background, Connection, Handshake, HandshakeError};
use Body;

use tower::MakeConnection;
use tower_service::Service;

use futures::future::Executor;
use futures::{Future, Poll};
use h2;

use std::error::Error;
use std::fmt;
use std::marker::PhantomData;

/// Establishes an H2 client connection.
///
/// Has a builder-like API for configuring client connections.  Currently this only allows
/// the configuration of TLS transport on new services created by this factory.
pub struct Connect<A, C, E, S> {
    /// Establish new session layer values (usually TCP sockets w/ TLS).
    inner: C,

    /// HTTP/2.0 client configuration
    builder: h2::client::Builder,

    /// Used to spawn connection management tasks and tasks to flush send
    /// body streams.
    executor: E,

    /// The HTTP request body type.
    _p: PhantomData<(A, S)>,
}

/// Completes with a Connection when the H2 connection has been initialized.
pub struct ConnectFuture<A, C, E, S>
where
    C: MakeConnection<A>,
    S: Body,
{
    /// Connect state. Starts in "Connect", which attempts to obtain the `io`
    /// handle from the `tokio_connect::Connect` instance. Then, with the
    /// handle, performs the HTTP/2.0 handshake.
    state: State<A, C, E, S>,

    /// The executor that the `Connection` will use to spawn request body stream
    /// flushing tasks
    executor: Option<E>,

    /// HTTP/2.0 client configuration
    builder: h2::client::Builder,
}

/// Represents the state of a `ConnectFuture`
enum State<A, C, E, S>
where
    C: MakeConnection<A>,
    S: Body,
{
    Connect(C::Future),
    Handshake(Handshake<C::Connection, E, S>),
}

/// Error produced when establishing an H2 client connection.
#[derive(Debug)]
pub enum ConnectError<T> {
    /// An error occurred when attempting to establish the underlying session
    /// layer.
    Connect(T),

    /// An error occurred while performing the HTTP/2.0 handshake.
    Handshake(HandshakeError),
}

// ===== impl Connect =====

impl<A, C, E, S> Connect<A, C, E, S>
where
    C: MakeConnection<A>,
    E: Executor<Background<C::Connection, S>> + Clone,
    S: Body,
    S::Data: 'static,
    S::Error: Into<Box<dyn std::error::Error>>,
{
    /// Create a new `Connect`.
    ///
    /// The `connect` argument is used to obtain new session layer instances
    /// (`AsyncRead` + `AsyncWrite`). For each new client service returned, a
    /// task will be spawned onto `executor` that will be used to manage the H2
    /// connection.
    pub fn new(inner: C, builder: h2::client::Builder, executor: E) -> Self {
        Connect {
            inner,
            executor,
            builder,
            _p: PhantomData,
        }
    }
}

impl<A, C, E, S> Service<A> for Connect<A, C, E, S>
where
    C: MakeConnection<A> + 'static,
    E: Executor<Background<C::Connection, S>> + Clone,
    S: Body + 'static,
    S::Error: Into<Box<dyn std::error::Error>>,
{
    type Response = Connection<C::Connection, E, S>;
    type Error = ConnectError<C::Error>;
    type Future = ConnectFuture<A, C, E, S>;

    fn poll_ready(&mut self) -> Poll<(), Self::Error> {
        self.inner.poll_ready().map_err(ConnectError::Connect)
    }

    /// Obtains a Connection on a single plaintext h2 connection to a remote.
    fn call(&mut self, target: A) -> Self::Future {
        let state = State::Connect(self.inner.make_connection(target));
        let builder = self.builder.clone();

        ConnectFuture {
            state,
            builder,
            executor: Some(self.executor.clone()),
        }
    }
}

// ===== impl ConnectFuture =====

impl<A, C, E, S> Future for ConnectFuture<A, C, E, S>
where
    C: MakeConnection<A>,
    E: Executor<Background<C::Connection, S>> + Clone,
    S: Body,
    S::Data: 'static,
    S::Error: Into<Box<dyn std::error::Error>>,
{
    type Item = Connection<C::Connection, E, S>;
    type Error = ConnectError<C::Error>;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        loop {
            let io = match self.state {
                State::Connect(ref mut fut) => {
                    let res = fut.poll().map_err(ConnectError::Connect);

                    try_ready!(res)
                }
                State::Handshake(ref mut fut) => {
                    return fut.poll().map_err(ConnectError::Handshake);
                }
            };

            let executor = self.executor.take().expect("double poll");
            let handshake = Handshake::new(io, executor, &self.builder);

            self.state = State::Handshake(handshake);
        }
    }
}

// ===== impl ConnectError =====

impl<T> fmt::Display for ConnectError<T>
where
    T: Error,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            ConnectError::Connect(ref why) => write!(
                f,
                "Error attempting to establish underlying session layer: {}",
                why
            ),
            ConnectError::Handshake(ref why) => {
                write!(f, "Error while performing HTTP/2.0 handshake: {}", why,)
            }
        }
    }
}

impl<T> Error for ConnectError<T>
where
    T: Error,
{
    fn description(&self) -> &str {
        match *self {
            ConnectError::Connect(_) => "error attempting to establish underlying session layer",
            ConnectError::Handshake(_) => "error performing HTTP/2.0 handshake",
        }
    }

    fn cause(&self) -> Option<&Error> {
        match *self {
            ConnectError::Connect(ref why) => Some(why),
            ConnectError::Handshake(ref why) => Some(why),
        }
    }
}