rama_http/layer/dns/dns_resolve/
service.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
use super::DnsResolveMode;
use crate::{HeaderName, Request};
use rama_core::{error::OpaqueError, Context, Service};
use rama_utils::macros::define_inner_service_accessors;
use std::fmt;

/// Service to support configuring the DNS resolve mode.
///
/// By default DNS resolving is expected to only be done
/// if it is needed (e.g. because we need to know the IP).
/// Configuring this to be used as eager (when requested) is
/// a way to have requested the intent
/// to reoslve DNS even if it is not needed.
///
/// See `Dns` (`rama_core`) and [`DnsResolveMode`] for more information.
pub struct DnsResolveModeService<S> {
    inner: S,
    header_name: HeaderName,
}

impl<S> DnsResolveModeService<S> {
    /// Create a new instance of the [`DnsResolveModeService`].
    pub const fn new(inner: S, header_name: HeaderName) -> Self {
        Self { inner, header_name }
    }

    define_inner_service_accessors!();
}

impl<S: fmt::Debug> fmt::Debug for DnsResolveModeService<S> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DnsResolveModeService")
            .field("inner", &self.inner)
            .finish()
    }
}

impl<S: Clone> Clone for DnsResolveModeService<S> {
    fn clone(&self) -> Self {
        DnsResolveModeService {
            inner: self.inner.clone(),
            header_name: self.header_name.clone(),
        }
    }
}

impl<State, Body, S> Service<State, Request<Body>> for DnsResolveModeService<S>
where
    State: Clone + Send + Sync + 'static,
    Body: Send + Sync + 'static,
    S: Service<
        State,
        Request<Body>,
        Error: Into<rama_core::error::BoxError> + Send + Sync + 'static,
    >,
{
    type Response = S::Response;
    type Error = OpaqueError;

    async fn serve(
        &self,
        mut ctx: Context<State>,
        request: Request<Body>,
    ) -> Result<Self::Response, Self::Error> {
        if let Some(header_value) = request.headers().get(&self.header_name) {
            let dns_resolve_mode: DnsResolveMode = header_value.try_into()?;
            ctx.insert(dns_resolve_mode);
        }

        self.inner
            .serve(ctx, request)
            .await
            .map_err(|err| OpaqueError::from_boxed(err.into()))
    }
}