volo-http 0.5.5

HTTP framework implementation of volo.
Documentation
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
//! [`Layer`]s for inserting header to requests.
//!
//! - [`Header`] inserts any [`HeaderName`] and [`HeaderValue`]
//! - [`Host`] inserts the given `Host` or a `Host` generated by the target hostname or target
//!   address with its scheme and port.
//! - [`UserAgent`] inserts the given `User-Agent` or a `User-Agent` generated by the current
//!   package information.

use std::{error::Error, future::Future};

use http::header::{self, HeaderName, HeaderValue};
use motore::{layer::Layer, service::Service};

use crate::{
    client::{Target, target::RemoteHost, utils::is_default_port},
    context::ClientContext,
    error::client::{Result, builder_error},
    request::Request,
};

/// [`Layer`] for inserting a header to requests.
#[derive(Clone, Debug)]
pub struct Header {
    key: HeaderName,
    val: HeaderValue,
}

impl Header {
    /// Create a new [`Header`] layer for inserting a header to requests.
    ///
    /// This function takes [`HeaderName`] and [`HeaderValue`], users should create it by
    /// themselves.
    ///
    /// For using string types directly, see [`Header::try_new`].
    pub fn new(key: HeaderName, val: HeaderValue) -> Self {
        Self { key, val }
    }

    /// Create a new [`Header`] layer for inserting a header to requests.
    ///
    /// This function takes any types that can be converted into [`HeaderName`] or [`HeaderValue`].
    /// If the values are invalid [`HeaderName`] or [`HeaderValue`], an [`ClientError`] with
    /// [`ErrorKind::Builder`] will be returned.
    ///
    /// [`ClientError`]: crate::error::client::ClientError
    /// [`ErrorKind::Builder`]: crate::error::client::ErrorKind::Builder
    pub fn try_new<K, V>(key: K, val: V) -> Result<Self>
    where
        K: TryInto<HeaderName>,
        K::Error: Error + Send + Sync + 'static,
        V: TryInto<HeaderValue>,
        V::Error: Error + Send + Sync + 'static,
    {
        let key = key.try_into().map_err(builder_error)?;
        let val = val.try_into().map_err(builder_error)?;

        Ok(Self::new(key, val))
    }
}

impl<S> Layer<S> for Header {
    type Service = HeaderService<S>;

    fn layer(self, inner: S) -> Self::Service {
        HeaderService {
            inner,
            key: self.key,
            val: self.val,
        }
    }
}

/// [`Service`] generated by [`Header`].
///
/// See [`Header`], [`Header::new`] and [`Header::try_new`] for more details.
pub struct HeaderService<S> {
    inner: S,
    key: HeaderName,
    val: HeaderValue,
}

impl<Cx, B, S> Service<Cx, Request<B>> for HeaderService<S>
where
    S: Service<Cx, Request<B>>,
{
    type Response = S::Response;
    type Error = S::Error;

    fn call(
        &self,
        cx: &mut Cx,
        mut req: Request<B>,
    ) -> impl Future<Output = Result<Self::Response, Self::Error>> + Send {
        req.headers_mut().insert(self.key.clone(), self.val.clone());
        self.inner.call(cx, req)
    }
}

/// [`Layer`] for inserting `Host` into the request header.
#[derive(Clone, Debug, Default)]
pub enum Host {
    /// Do not insert `Host` into the request headers.
    None,
    /// If there is no `Host` in request headers, the layer will generate it through target
    /// address.
    #[default]
    Auto,
    /// Forcely use the given value as `Host` in request headers, it will override the previous
    /// one.
    Force(HeaderValue),
    /// If there is no `Host` in request headers, the `Host` will be set to the given value.
    Fallback(HeaderValue),
}

impl<S> Layer<S> for Host {
    type Service = HostService<S>;

    fn layer(self, inner: S) -> Self::Service {
        HostService {
            inner,
            config: self,
        }
    }
}

/// [`Service`] generated by [`Host`].
///
/// See [`Host`] for more details.
pub struct HostService<S> {
    inner: S,
    config: Host,
}

#[cfg(target_family = "unix")]
const UDS_HOST: HeaderValue = HeaderValue::from_static("unix-domain-socket");

pub(super) fn gen_host(target: &Target) -> Option<HeaderValue> {
    let rt = match target {
        Target::None => return None,
        Target::Remote(rt) => rt,
        #[cfg(target_family = "unix")]
        Target::Local(_) => return Some(UDS_HOST.clone()),
    };
    let default_port = is_default_port(&rt.scheme, rt.port);
    match &rt.host {
        RemoteHost::Ip(ip) => {
            let s = if default_port {
                if ip.is_ipv4() {
                    format!("{ip}")
                } else {
                    format!("[{ip}]")
                }
            } else {
                let port = rt.port;
                if ip.is_ipv4() {
                    format!("{ip}:{port}")
                } else {
                    format!("[{ip}]:{port}")
                }
            };
            HeaderValue::from_str(&s).ok()
        }
        RemoteHost::Name(name) => {
            let port = rt.port;
            if default_port {
                HeaderValue::from_str(name).ok()
            } else {
                HeaderValue::from_str(&format!("{name}:{port}")).ok()
            }
        }
    }
}

impl<B, S> Service<ClientContext, Request<B>> for HostService<S>
where
    S: Service<ClientContext, Request<B>>,
{
    type Response = S::Response;
    type Error = S::Error;

    fn call(
        &self,
        cx: &mut ClientContext,
        mut req: Request<B>,
    ) -> impl Future<Output = Result<Self::Response, Self::Error>> + Send {
        match &self.config {
            Host::None => {}
            Host::Auto => {
                if !req.headers().contains_key(header::HOST) {
                    if let Some(val) = gen_host(cx.target()) {
                        req.headers_mut().insert(header::HOST, val);
                    }
                }
            }
            Host::Force(val) => {
                req.headers_mut().insert(header::HOST, val.clone());
            }
            Host::Fallback(val) => {
                if !req.headers().contains_key(header::HOST) {
                    req.headers_mut().insert(header::HOST, val.clone());
                }
            }
        }

        self.inner.call(cx, req)
    }
}

const PKG_NAME_WITH_VER: &str = concat!(env!("CARGO_PKG_NAME"), '/', env!("CARGO_PKG_VERSION"));

/// [`Layer`] for inserting `User-Agent` into the request header.
///
/// See [`UserAgent::new`] for more details.
pub struct UserAgent {
    val: HeaderValue,
}

impl UserAgent {
    /// Create a new [`UserAgent`] layer that inserts `User-Agent` into the request header.
    ///
    /// Note that the layer only inserts it if there is no `User-Agent`
    pub fn new(val: HeaderValue) -> Self {
        Self { val }
    }

    /// Create a new [`UserAgent`] layer with the package name and package version as its default
    /// value.
    ///
    /// Note that the layer only inserts it if there is no `User-Agent`
    pub fn auto() -> Self {
        Self {
            val: HeaderValue::from_static(PKG_NAME_WITH_VER),
        }
    }
}

impl<S> Layer<S> for UserAgent {
    type Service = UserAgentService<S>;

    fn layer(self, inner: S) -> Self::Service {
        UserAgentService {
            inner,
            val: self.val,
        }
    }
}

/// [`Service`] generated by [`UserAgent`].
///
/// See [`UserAgent`] and [`UserAgent::new`] for more details.
pub struct UserAgentService<S> {
    inner: S,
    val: HeaderValue,
}

impl<Cx, B, S> Service<Cx, Request<B>> for UserAgentService<S>
where
    S: Service<Cx, Request<B>>,
{
    type Response = S::Response;
    type Error = S::Error;

    fn call(
        &self,
        cx: &mut Cx,
        mut req: Request<B>,
    ) -> impl Future<Output = Result<Self::Response, Self::Error>> + Send {
        if !req.headers().contains_key(header::USER_AGENT) {
            req.headers_mut()
                .insert(header::USER_AGENT, self.val.clone());
        }
        self.inner.call(cx, req)
    }
}

#[cfg(test)]
mod layer_header_tests {
    use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};

    use faststr::FastStr;
    use http::uri::Scheme;

    use crate::client::{
        Target,
        layer::header::gen_host,
        target::{RemoteHost, RemoteTarget},
    };

    const IPV4: IpAddr = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1));
    const IPV6: IpAddr = IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));

    const fn host_target(scheme: Scheme, host: &'static str, port: u16) -> Target {
        Target::Remote(RemoteTarget {
            scheme,
            host: RemoteHost::Name(FastStr::from_static_str(host)),
            port,
        })
    }

    const fn ip_target(scheme: Scheme, ip: IpAddr, port: u16) -> Target {
        Target::Remote(RemoteTarget {
            scheme,
            host: RemoteHost::Ip(ip),
            port,
        })
    }

    #[test]
    fn gen_host_test() {
        // no host, no addr
        assert_eq!(gen_host(&Target::None), None);

        // host with default port
        assert_eq!(
            gen_host(&host_target(Scheme::HTTP, "github.com", 80)).unwrap(),
            "github.com",
        );
        // host with non-default port
        assert_eq!(
            gen_host(&host_target(Scheme::HTTP, "github.com", 8000)).unwrap(),
            "github.com:8000",
        );
        assert_eq!(
            gen_host(&host_target(Scheme::HTTP, "github.com", 443)).unwrap(),
            "github.com:443",
        );

        // ipv4 addr with default port
        assert_eq!(
            gen_host(&ip_target(Scheme::HTTP, IPV4, 80)).unwrap(),
            "127.0.0.1",
        );
        // ipv4 addr with non-default port
        assert_eq!(
            gen_host(&ip_target(Scheme::HTTP, IPV4, 8000)).unwrap(),
            "127.0.0.1:8000",
        );
        assert_eq!(
            gen_host(&ip_target(Scheme::HTTP, IPV4, 443)).unwrap(),
            "127.0.0.1:443",
        );

        // ipv6 addr with default port
        assert_eq!(
            gen_host(&ip_target(Scheme::HTTP, IPV6, 80)).unwrap(),
            "[::1]",
        );
        // ipv6 addr with non-default port
        assert_eq!(
            gen_host(&ip_target(Scheme::HTTP, IPV6, 8000)).unwrap(),
            "[::1]:8000",
        );
        assert_eq!(
            gen_host(&ip_target(Scheme::HTTP, IPV6, 443)).unwrap(),
            "[::1]:443",
        );
    }

    #[cfg(feature = "__tls")]
    #[test]
    fn gen_host_with_tls_test() {
        // host with default port
        assert_eq!(
            gen_host(&host_target(Scheme::HTTPS, "github.com", 443)).unwrap(),
            "github.com",
        );
        // host with non-default port
        assert_eq!(
            gen_host(&host_target(Scheme::HTTPS, "github.com", 4430)).unwrap(),
            "github.com:4430"
        );
        assert_eq!(
            gen_host(&host_target(Scheme::HTTPS, "github.com", 80)).unwrap(),
            "github.com:80"
        );

        // ipv4 addr with default port
        assert_eq!(
            gen_host(&ip_target(Scheme::HTTPS, IPV4, 443)).unwrap(),
            "127.0.0.1"
        );
        // ipv4 addr with non-default port
        assert_eq!(
            gen_host(&ip_target(Scheme::HTTPS, IPV4, 4430)).unwrap(),
            "127.0.0.1:4430"
        );
        assert_eq!(
            gen_host(&ip_target(Scheme::HTTPS, IPV4, 80)).unwrap(),
            "127.0.0.1:80"
        );

        // ipv6 addr with default port
        assert_eq!(
            gen_host(&ip_target(Scheme::HTTPS, IPV6, 443)).unwrap(),
            "[::1]"
        );
        // ipv6 addr with non-default port
        assert_eq!(
            gen_host(&ip_target(Scheme::HTTPS, IPV6, 4430)).unwrap(),
            "[::1]:4430"
        );
        assert_eq!(
            gen_host(&ip_target(Scheme::HTTPS, IPV6, 80)).unwrap(),
            "[::1]:80"
        );
    }
}