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
pub mod connection;
pub mod connector;
pub mod key;
pub mod pool;

use std::rc::Rc;

use bytes::Bytes;
use http::{uri::Scheme, HeaderMap};
use monoio_http::common::{
    body::{Body, HttpBody},
    error::HttpError,
    request::Request,
    response::Response,
};

use self::{
    connector::{Connector, DefaultTcpConnector, DefaultTlsConnector},
    key::Key,
};
use crate::request::ClientRequest;

pub struct ClientInner<C, #[cfg(any(feature = "rustls", feature = "native-tls"))] CS> {
    cfg: ClientConfig,
    http_connector: C,
    #[cfg(any(feature = "rustls", feature = "native-tls"))]
    https_connector: CS,
}

pub struct Client<
    C = DefaultTcpConnector<Key>,
    #[cfg(any(feature = "rustls", feature = "native-tls"))] CS = DefaultTlsConnector<Key>,
> {
    #[cfg(any(feature = "rustls", feature = "native-tls"))]
    shared: Rc<ClientInner<C, CS>>,
    #[cfg(not(any(feature = "rustls", feature = "native-tls")))]
    shared: Rc<ClientInner<C>>,
}

#[derive(Default, Clone, PartialEq, Eq)]
pub enum Proto {
    #[default]
    Http1, // HTTP1_1 only client
    Http2, // HTTP2 only client
    Auto,  // Uses version header in request
}

// HTTP1 & HTTP2 Connection specific.
#[derive(Default, Clone)]
pub struct ConnectionConfig {
    pub proto: Proto,
    h2_builder: monoio_http::h2::client::Builder,
}

// Global config applicable to
// all connections maintained by client
#[derive(Default, Clone)]
pub struct ClientGlobalConfig {
    max_idle_connections: usize,
}

#[derive(Default, Clone)]
pub struct Builder {
    connection_config: ConnectionConfig,
    global_config: ClientGlobalConfig,
}

impl Builder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn http1_client(&mut self) -> &mut Self {
        self.connection_config.proto = Proto::Http1;
        self
    }

    pub fn http2_client(&mut self) -> &mut Self {
        self.connection_config.proto = Proto::Http2;
        self
    }

    pub fn http_auto(&mut self) -> &mut Self {
        self.connection_config.proto = Proto::Auto;
        self
    }

    pub fn max_idle_connections(&mut self, conns: usize) -> &mut Self {
        self.global_config.max_idle_connections = conns;
        self
    }

    pub fn http2_max_frame_size(&mut self, sz: u32) -> &mut Self {
        self.connection_config.h2_builder.max_frame_size(sz);
        self
    }

    pub fn http2_max_send_buf_size(&mut self, sz: usize) -> &mut Self {
        self.connection_config.h2_builder.max_send_buffer_size(sz);
        self
    }

    pub fn http2_max_concurrent_reset_streams(&mut self, max: usize) -> &mut Self {
        self.connection_config.h2_builder.max_send_buffer_size(max);
        self
    }

    pub fn http2_initial_stream_window_size(&mut self, size: u32) -> &mut Self {
        self.connection_config.h2_builder.initial_window_size(size);
        self
    }

    pub fn http2_initial_connection_window_size(&mut self, size: u32) -> &mut Self {
        self.connection_config
            .h2_builder
            .initial_connection_window_size(size);
        self
    }

    pub fn http2_max_concurrent_streams(&mut self, max: u32) -> &mut Self {
        self.connection_config
            .h2_builder
            .max_concurrent_streams(max);
        self
    }

    pub fn build_http1(self) -> Client {
        Client::new(self.global_config, self.connection_config)
    }

    pub fn build_http2(mut self) -> Client {
        self.http2_client();
        Client::new(self.global_config, self.connection_config)
    }

    pub fn build_auto(mut self) -> Client {
        self.http_auto();
        Client::new(self.global_config, self.connection_config)
    }
}

macro_rules! client_clone_impl {
    ( $( $x:item )* ) => {
        #[cfg(not(any(feature = "rustls", feature = "native-tls")))]
        impl<C> Clone for Client<C>
        {
            $($x)*
        }

        #[cfg(any(feature = "rustls", feature = "native-tls"))]
        impl<C, CS> Clone for Client<C, CS>
        {
            $($x)*
        }
    };
}

client_clone_impl! {
    fn clone(&self) -> Self {
        Self {
            shared: self.shared.clone(),
        }
    }
}

#[derive(Default, Clone)]
pub struct ClientConfig {
    default_headers: Rc<HeaderMap>,
}

impl Default for Client {
    fn default() -> Self {
        Builder::default().build_http1()
    }
}

impl Client {
    fn new(g_config: ClientGlobalConfig, c_config: ConnectionConfig) -> Self {
        let shared = Rc::new(ClientInner {
            cfg: ClientConfig::default(),
            http_connector: DefaultTcpConnector::new(g_config.clone(), c_config.clone()),
            #[cfg(any(feature = "rustls", feature = "native-tls"))]
            https_connector: DefaultTlsConnector::new(g_config, c_config),
        });
        Self { shared }
    }

    pub async fn send_request<B: Body<Data = Bytes, Error = HttpError> + 'static>(
        &self,
        req: Request<B>,
    ) -> crate::Result<Response<HttpBody>> {
        let mut key: Key = req.uri().try_into()?;
        key.set_version(req.version());

        match req.uri().scheme() {
            Some(s) if s == &Scheme::HTTP => {
                let conn = self.shared.http_connector.connect(key).await?;
                conn.send_request(req).await
            }
            #[cfg(any(feature = "rustls", feature = "native-tls"))]
            Some(s) if s == &Scheme::HTTPS => {
                let conn = self.shared.https_connector.connect(key).await?;
                conn.send_request(req).await
            }
            // Key creation should error first
            _ => unreachable!(),
        }
    }
}

macro_rules! http_method {
    ($fn: ident, $method: expr) => {
        pub fn $fn<U>(&self, uri: U) -> ClientRequest<C, CS>
        where
            http::Uri: TryFrom<U>,
            <http::Uri as TryFrom<U>>::Error: Into<http::Error>,
        {
            self.request($method, uri)
        }
    };
}

macro_rules! client_impl {
    ( $( $x:item )* ) => {
        #[cfg(not(any(feature = "rustls", feature = "native-tls")))]
        impl<C> Client<B, C> {
            $($x)*
        }

        #[cfg(any(feature = "rustls", feature = "native-tls"))]
        impl<C, CS> Client<C, CS> {
            $($x)*
        }
    };
}

client_impl! {
    http_method!(get, http::Method::GET);
    http_method!(post, http::Method::POST);
    http_method!(put, http::Method::PUT);
    http_method!(patch, http::Method::PATCH);
    http_method!(delete, http::Method::DELETE);
    http_method!(head, http::Method::HEAD);
}

#[cfg(not(any(feature = "rustls", feature = "native-tls")))]
impl<B: Body<Data = Bytes, Error = HttpError>, C> Client<B, C> {
    pub fn request<M, U>(&self, method: M, uri: U) -> ClientRequest<B, C>
    where
        http::Method: TryFrom<M>,
        <http::Method as TryFrom<M>>::Error: Into<http::Error>,
        http::Uri: TryFrom<U>,
        <http::Uri as TryFrom<U>>::Error: Into<http::Error>,
    {
        let mut req = ClientRequest::new(self.clone()).method(method).uri(uri);
        for (key, value) in self.shared.cfg.default_headers.iter() {
            req = req.header(key, value);
        }
        req
    }
}

#[cfg(any(feature = "rustls", feature = "native-tls"))]
impl<C, CS> Client<C, CS> {
    pub fn request<M, U>(&self, method: M, uri: U) -> ClientRequest<C, CS>
    where
        http::Method: TryFrom<M>,
        <http::Method as TryFrom<M>>::Error: Into<http::Error>,
        http::Uri: TryFrom<U>,
        <http::Uri as TryFrom<U>>::Error: Into<http::Error>,
    {
        let mut req = ClientRequest::<C, CS>::new(self.clone())
            .method(method)
            .uri(uri);
        for (key, value) in self.shared.cfg.default_headers.iter() {
            req = req.header(key, value);
        }
        req
    }
}