Skip to main content

ntex_net/connect/
service.rs

1use std::{collections::VecDeque, io, marker, net::SocketAddr};
2
3use ntex_error::Error;
4use ntex_io::{Io, IoConfig, types};
5use ntex_service::{Ctx, Service, cfg::SharedCfg};
6use ntex_util::{future::Either, time::timeout_checked};
7
8use super::{Address, Connect, ConnectError, resolve};
9
10#[derive(Debug)]
11/// DNS-aware TCP stream connector.
12pub struct Connector<A> {
13    _t: marker::PhantomData<A>,
14}
15
16impl<A> Connector<A> {
17    #[inline]
18    /// Creates a connector.
19    pub fn new() -> Self {
20        Connector {
21            _t: marker::PhantomData,
22        }
23    }
24}
25
26impl<A> Default for Connector<A> {
27    fn default() -> Self {
28        Connector::new()
29    }
30}
31
32impl<A> Clone for Connector<A> {
33    fn clone(&self) -> Self {
34        Connector {
35            _t: marker::PhantomData,
36        }
37    }
38}
39
40impl<A: Address> Connector<A> {
41    /// Resolves and connects to a remote host.
42    pub async fn connect<U>(&self, message: U, cfg: &SharedCfg) -> Result<Io, Error<ConnectError>>
43    where
44        Connect<A>: From<U>,
45    {
46        let timeout = cfg.get::<IoConfig>().connect_timeout();
47        timeout_checked(timeout, async {
48            // resolve first
49            let msg = resolve::lookup(message.into(), cfg.tag()).await?;
50
51            let port = msg.port();
52            let Connect { req, addr, .. } = msg;
53
54            if let Some(addr) = addr {
55                connect(req, port, addr, cfg).await
56            } else {
57                Err(Error::from(ConnectError::Unresolved))
58            }
59        })
60        .await
61        .map_err(|()| {
62            Error::from(ConnectError::Io(io::Error::new(
63                io::ErrorKind::TimedOut,
64                "Connect timeout",
65            )))
66        })
67        .and_then(|item| item)
68        .map_err(|e| e.with_service(cfg.service()))
69    }
70}
71
72impl<A: Address> Service<SharedCfg, Connect<A>> for Connector<A> {
73    type Res = Io;
74    type Error = Error<ConnectError>;
75
76    async fn call(
77        &self,
78        req: Connect<A>,
79        ctx: Ctx<'_, Self, SharedCfg>,
80    ) -> Result<Io, Self::Error> {
81        self.connect(req, ctx.st()).await
82    }
83}
84
85/// Tcp stream connector
86async fn connect<A: Address>(
87    req: A,
88    port: u16,
89    addr: Either<SocketAddr, VecDeque<SocketAddr>>,
90    cfg: &SharedCfg,
91) -> Result<Io, Error<ConnectError>> {
92    log::trace!(
93        "{}: TCP connector - connecting to {:?} addr:{addr:?} port:{port}",
94        cfg.tag(),
95        req.host(),
96    );
97
98    let io = match addr {
99        Either::Left(addr) => crate::tcp_connect(addr, cfg.clone())
100            .await
101            .map_err(ConnectError::from)?,
102        Either::Right(mut addrs) => loop {
103            let addr = addrs.pop_front().unwrap();
104
105            match crate::tcp_connect(addr, cfg.clone()).await {
106                Ok(io) => break io,
107                Err(err) => {
108                    log::trace!(
109                        "{}: TCP connector - failed to connect to {:?} port: {port} err: {err:?}",
110                        cfg.tag(),
111                        req.host(),
112                    );
113                    if addrs.is_empty() {
114                        return Err(ConnectError::from(err).into());
115                    }
116                }
117            }
118        },
119    };
120
121    log::trace!(
122        "{}: TCP connector - successfully connected to {:?} - {:?}",
123        cfg.tag(),
124        req.host(),
125        io.query::<types::PeerAddr>().get()
126    );
127    Ok(io)
128}