Skip to main content

ntex_net/connect/
message.rs

1use std::collections::{VecDeque, vec_deque};
2use std::{fmt, iter::FusedIterator, net::SocketAddr};
3
4use ntex_bytes::ByteString;
5use ntex_util::future::Either;
6
7/// Address information required by [`Connect`].
8pub trait Address: Unpin + 'static {
9    /// Returns the host name.
10    fn host(&self) -> &str;
11
12    /// Returns an explicitly configured port, if available.
13    fn port(&self) -> Option<u16>;
14
15    /// Returns a pre-resolved socket address, if available.
16    ///
17    /// [`Connect::new()`] uses it as the request's initial pre-resolved
18    /// address; afterwards the request's own addresses are authoritative.
19    fn addr(&self) -> Option<SocketAddr> {
20        None
21    }
22}
23
24impl Address for String {
25    fn host(&self) -> &str {
26        self
27    }
28
29    fn port(&self) -> Option<u16> {
30        None
31    }
32}
33
34impl Address for ByteString {
35    fn host(&self) -> &str {
36        self
37    }
38
39    fn port(&self) -> Option<u16> {
40        None
41    }
42}
43
44impl Address for &'static str {
45    fn host(&self) -> &str {
46        self
47    }
48
49    fn port(&self) -> Option<u16> {
50        None
51    }
52}
53
54impl Address for SocketAddr {
55    fn host(&self) -> &'static str {
56        ""
57    }
58
59    fn port(&self) -> Option<u16> {
60        None
61    }
62
63    fn addr(&self) -> Option<SocketAddr> {
64        Some(*self)
65    }
66}
67
68/// Request to resolve and connect to a remote address.
69///
70/// A request owns one list of pre-resolved addresses. It starts with
71/// [`Address::addr()`] of the original value, if any, and is replaced by
72/// [`set_addr()`](Self::set_addr) or [`set_addrs()`](Self::set_addrs), emptied by
73/// [`clear_addrs()`](Self::clear_addrs) or [`take_addrs()`](Self::take_addrs), and
74/// filled by the resolver when empty. The connector connects to exactly the
75/// addresses reported by [`addrs()`](Self::addrs).
76#[derive(Eq, PartialEq, Debug, Hash)]
77pub struct Connect<T> {
78    pub(super) req: T,
79    pub(super) port: u16,
80    pub(super) addr: Option<Either<SocketAddr, VecDeque<SocketAddr>>>,
81}
82
83impl<T: Address> Connect<T> {
84    /// Creates a connection request and derives a port from the host when present.
85    ///
86    /// A pre-resolved [`Address::addr()`] becomes the request's initial
87    /// address, and provides the port if the host has none.
88    #[must_use]
89    pub fn new(req: T) -> Connect<T> {
90        let (_, port) = parse(req.host());
91        let addr = req.addr();
92        Connect {
93            port: port.or(addr.map(|a| a.port())).unwrap_or(0),
94            addr: addr.map(Either::Left),
95            req,
96        }
97    }
98
99    /// Creates a request with a pre-resolved socket address.
100    ///
101    /// The address replaces any [`Address::addr()`] of `req`, and the connector
102    /// skips DNS resolution for this request.
103    #[must_use]
104    pub fn with(req: T, addr: SocketAddr) -> Connect<T> {
105        Connect {
106            req,
107            port: 0,
108            addr: Some(Either::Left(addr)),
109        }
110    }
111
112    /// Sets the port used when [`Address::port()`] does not provide one.
113    ///
114    /// This replaces the port parsed from a `host:port` host by
115    /// [`new()`](Self::new), which is zero if the host has none.
116    #[must_use]
117    pub fn set_port(mut self, port: u16) -> Self {
118        self.port = port;
119        self
120    }
121
122    /// Replaces the pre-resolved addresses with `addr`.
123    ///
124    /// `None` keeps the current addresses, use
125    /// [`clear_addrs()`](Self::clear_addrs) to remove them.
126    #[must_use]
127    pub fn set_addr(mut self, addr: Option<SocketAddr>) -> Self {
128        if let Some(addr) = addr {
129            self.addr = Some(Either::Left(addr));
130        }
131        self
132    }
133
134    /// Replaces the pre-resolved addresses with `addrs`.
135    ///
136    /// An empty iterator removes all addresses, like
137    /// [`clear_addrs()`](Self::clear_addrs).
138    #[must_use]
139    pub fn set_addrs<I>(mut self, addrs: I) -> Self
140    where
141        I: IntoIterator<Item = SocketAddr>,
142    {
143        let mut addrs = VecDeque::from_iter(addrs);
144        self.addr = if addrs.len() < 2 {
145            addrs.pop_front().map(Either::Left)
146        } else {
147            Some(Either::Right(addrs))
148        };
149        self
150    }
151
152    /// Removes all pre-resolved addresses, including the initial
153    /// [`Address::addr()`].
154    ///
155    /// The connector then resolves [`host()`](Self::host) instead.
156    #[must_use]
157    pub fn clear_addrs(mut self) -> Self {
158        self.addr = None;
159        self
160    }
161
162    /// Returns the request host name.
163    pub fn host(&self) -> &str {
164        self.req.host()
165    }
166
167    /// Returns the port from [`Address::port()`], or the one parsed from the
168    /// host or set by [`set_port()`](Self::set_port).
169    pub fn port(&self) -> u16 {
170        self.req.port().unwrap_or(self.port)
171    }
172
173    /// Iterates over the request's pre-resolved addresses.
174    pub fn addrs(&self) -> ConnectAddrsIter<'_> {
175        let inner = match self.addr {
176            None => Either::Left(None),
177            Some(Either::Left(addr)) => Either::Left(Some(addr)),
178            Some(Either::Right(ref addrs)) => Either::Right(addrs.iter()),
179        };
180        ConnectAddrsIter { inner }
181    }
182
183    /// Removes and returns the request's pre-resolved addresses.
184    ///
185    /// The request has no addresses afterwards, so a second call returns an
186    /// empty iterator.
187    pub fn take_addrs(&mut self) -> ConnectTakeAddrsIter {
188        let inner = match self.addr.take() {
189            None => Either::Left(None),
190            Some(Either::Left(addr)) => Either::Left(Some(addr)),
191            Some(Either::Right(addrs)) => Either::Right(addrs.into_iter()),
192        };
193        ConnectTakeAddrsIter { inner }
194    }
195
196    /// Returns the original address value.
197    pub fn get_ref(&self) -> &T {
198        &self.req
199    }
200
201    /// Maps the original address value while preserving port and resolved addresses.
202    ///
203    /// [`Address::addr()`] of the new value is not used.
204    pub fn map_addr<F, R>(self, f: F) -> Connect<R>
205    where
206        F: FnOnce(T) -> R,
207    {
208        let req = f(self.req);
209
210        Connect {
211            req,
212            port: self.port,
213            addr: self.addr,
214        }
215    }
216}
217
218impl<T: Clone> Clone for Connect<T> {
219    fn clone(&self) -> Self {
220        Connect {
221            req: self.req.clone(),
222            port: self.port,
223            addr: self.addr.clone(),
224        }
225    }
226}
227
228impl<T: Address> From<T> for Connect<T> {
229    fn from(addr: T) -> Self {
230        Connect::new(addr)
231    }
232}
233
234impl<T: Address> fmt::Display for Connect<T> {
235    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
236        let (host, _) = parse(self.host());
237        if host.contains(':') {
238            write!(f, "[{host}]:{}", self.port())
239        } else {
240            write!(f, "{host}:{}", self.port())
241        }
242    }
243}
244
245/// Iterator over addresses in a [`Connect`] request.
246#[derive(Clone)]
247pub struct ConnectAddrsIter<'a> {
248    inner: Either<Option<SocketAddr>, vec_deque::Iter<'a, SocketAddr>>,
249}
250
251impl Iterator for ConnectAddrsIter<'_> {
252    type Item = SocketAddr;
253
254    fn next(&mut self) -> Option<Self::Item> {
255        match self.inner {
256            Either::Left(ref mut opt) => opt.take(),
257            Either::Right(ref mut iter) => iter.next().copied(),
258        }
259    }
260
261    fn size_hint(&self) -> (usize, Option<usize>) {
262        match self.inner {
263            Either::Left(Some(_)) => (1, Some(1)),
264            Either::Left(None) => (0, Some(0)),
265            Either::Right(ref iter) => iter.size_hint(),
266        }
267    }
268}
269
270impl fmt::Debug for ConnectAddrsIter<'_> {
271    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
272        f.debug_list().entries(self.clone()).finish()
273    }
274}
275
276impl ExactSizeIterator for ConnectAddrsIter<'_> {}
277
278impl FusedIterator for ConnectAddrsIter<'_> {}
279
280/// Owning iterator over addresses removed from a [`Connect`] request.
281#[derive(Debug)]
282pub struct ConnectTakeAddrsIter {
283    inner: Either<Option<SocketAddr>, vec_deque::IntoIter<SocketAddr>>,
284}
285
286impl Iterator for ConnectTakeAddrsIter {
287    type Item = SocketAddr;
288
289    fn next(&mut self) -> Option<Self::Item> {
290        match self.inner {
291            Either::Left(ref mut opt) => opt.take(),
292            Either::Right(ref mut iter) => iter.next(),
293        }
294    }
295
296    fn size_hint(&self) -> (usize, Option<usize>) {
297        match self.inner {
298            Either::Left(Some(_)) => (1, Some(1)),
299            Either::Left(None) => (0, Some(0)),
300            Either::Right(ref iter) => iter.size_hint(),
301        }
302    }
303}
304
305impl ExactSizeIterator for ConnectTakeAddrsIter {}
306
307impl FusedIterator for ConnectTakeAddrsIter {}
308
309/// Splits `host`, `host:port`, `[v6]`, `[v6]:port` or bare `v6` into host and port.
310///
311/// Brackets are stripped from IPv6 hosts.
312pub(super) fn parse(host: &str) -> (&str, Option<u16>) {
313    let (name, port) = if let Some(rest) = host.strip_prefix('[') {
314        match rest.split_once(']') {
315            Some((ip, tail)) => (ip, tail.strip_prefix(':')),
316            None => (host, None),
317        }
318    } else {
319        match host.split_once(':') {
320            Some((name, port)) if !port.contains(':') => (name, Some(port)),
321            _ => (host, None),
322        }
323    };
324    (name, port.and_then(|p| p.parse::<u16>().ok()))
325}
326
327#[cfg(test)]
328mod tests {
329    use super::*;
330
331    /// STATEMENT: String types used as addresses report themselves as the host and have no
332    /// port.
333    ///
334    /// HOW:
335    /// - Query host and port of a `&str`, a `String` and a `ByteString`.
336    /// - Expect the string as host and no port for each.
337    #[test]
338    fn address() {
339        assert_eq!("test".host(), "test");
340        assert_eq!("test".port(), None);
341
342        let s = "test".to_string();
343        assert_eq!(s.host(), "test");
344        assert_eq!(s.port(), None);
345
346        let s = ByteString::from("test");
347        assert_eq!(s.host(), "test");
348        assert_eq!(s.port(), None);
349    }
350
351    /// STATEMENT: Host parsing splits an optional port from host names, IPv4 addresses and
352    /// bracketed IPv6 addresses.
353    ///
354    /// HOW:
355    /// - Parse names and IPv4 addresses with and without a port; expect an invalid port to be
356    ///   dropped.
357    /// - Parse IPv6 addresses with brackets, without brackets, and with an unclosed bracket;
358    ///   expect a port only after `]:`.
359    /// - Expect `Connect` to take a port from `[::1]:8080` and from `set_port`.
360    #[test]
361    fn parse_host() {
362        assert_eq!(parse("example.com"), ("example.com", None));
363        assert_eq!(parse("example.com:443"), ("example.com", Some(443)));
364        assert_eq!(parse("example.com:bad"), ("example.com", None));
365        assert_eq!(parse("127.0.0.1:8080"), ("127.0.0.1", Some(8080)));
366        assert_eq!(parse("[::1]"), ("::1", None));
367        assert_eq!(parse("[::1]:443"), ("::1", Some(443)));
368        assert_eq!(parse("[::1]443"), ("::1", None));
369        assert_eq!(parse("::1"), ("::1", None));
370        assert_eq!(parse("2001:db8::1"), ("2001:db8::1", None));
371        assert_eq!(parse("[::1"), ("[::1", None));
372        assert_eq!(parse(""), ("", None));
373
374        assert_eq!(Connect::new("[::1]:8080").port(), 8080);
375        assert_eq!(Connect::new("::1").set_port(80).port(), 80);
376    }
377
378    /// STATEMENT: `Connect` displays as `host:port`, with IPv6 hosts in brackets.
379    ///
380    /// HOW:
381    /// - Format requests for a name with a parsed port and with `set_port`.
382    /// - Format IPv6 requests, including one with a zone id; expect bracketed hosts.
383    #[test]
384    fn display() {
385        assert_eq!(
386            Connect::new("example.com:443").to_string(),
387            "example.com:443"
388        );
389        assert_eq!(
390            Connect::new("example.com").set_port(80).to_string(),
391            "example.com:80"
392        );
393        assert_eq!(Connect::new("[::1]:8080").to_string(), "[::1]:8080");
394        assert_eq!(Connect::new("::1").set_port(80).to_string(), "[::1]:80");
395        assert_eq!(
396            Connect::new("fe80::1%3").set_port(80).to_string(),
397            "[fe80::1%3]:80"
398        );
399    }
400
401    /// STATEMENT: `Connect` keeps its host, port and resolved addresses, and `take_addrs`
402    /// moves the addresses out.
403    ///
404    /// HOW:
405    /// - Create a request from a host name; expect port 0 until `set_port`, and no addresses.
406    /// - Map the address to a `host:port` string; expect the port parsed from it.
407    /// - Set one and then two addresses; expect `addrs` and `take_addrs` to return them, and
408    ///   none after `take_addrs`.
409    /// - Create a request from a socket address; expect an empty host, its port and the
410    ///   address.
411    #[test]
412    #[allow(clippy::similar_names)]
413    fn connect() {
414        let mut connect = Connect::new("www.rust-lang.org");
415        assert_eq!(connect.host(), "www.rust-lang.org");
416        assert_eq!(connect.port(), 0);
417        assert_eq!(*connect.get_ref(), "www.rust-lang.org");
418        connect = connect.set_port(80);
419        assert_eq!(connect.port(), 80);
420        let addrs = connect.addrs().clone();
421        assert_eq!(format!("{addrs:?}"), "[]");
422        assert!(connect.addrs().next().is_none());
423
424        let c = connect.clone().map_addr(|_| "www.rust-lang.org:80");
425        assert_eq!(c.host(), "www.rust-lang.org:80");
426        assert_eq!(c.port(), 80);
427        let addrs = c.addrs().clone();
428        assert_eq!(format!("{addrs:?}"), "[]");
429        assert!(c.addrs().next().is_none());
430
431        let addr: SocketAddr = "127.0.0.1:8080".parse().unwrap();
432        connect = connect.set_addrs(vec![addr]);
433        let addrs = connect.addrs().clone();
434        assert_eq!(format!("{addrs:?}"), "[127.0.0.1:8080]");
435        let addrs: Vec<_> = connect.take_addrs().collect();
436        assert_eq!(addrs.len(), 1);
437        assert!(addrs.contains(&addr));
438
439        let addr2: SocketAddr = "127.0.0.1:8081".parse().unwrap();
440        connect = connect.set_addrs(vec![addr, addr2]);
441        let addrs: Vec<_> = connect.addrs().collect();
442        assert_eq!(addrs.len(), 2);
443        assert!(addrs.contains(&addr));
444        assert!(addrs.contains(&addr2));
445
446        let addrs: Vec<_> = connect.take_addrs().collect();
447        assert_eq!(addrs.len(), 2);
448        assert!(addrs.contains(&addr));
449        assert!(addrs.contains(&addr2));
450        assert!(connect.addrs().next().is_none());
451
452        connect = connect.set_addrs(vec![addr]);
453        assert_eq!(format!("{connect}"), "www.rust-lang.org:80");
454
455        let addr: SocketAddr = "127.0.0.1:8080".parse().unwrap();
456        let mut connect = Connect::new(addr);
457        assert_eq!(connect.host(), "");
458        assert_eq!(connect.port(), 8080);
459        let addrs: Vec<_> = connect.addrs().collect();
460        assert_eq!(addrs.len(), 1);
461        assert!(addrs.contains(&addr));
462        let addrs: Vec<_> = connect.take_addrs().collect();
463        assert_eq!(addrs.len(), 1);
464        assert!(addrs.contains(&addr));
465    }
466
467    /// STATEMENT: `Connect::with`, `set_addr` and `take_addrs` keep the address count, and
468    /// `set_addr(None)` keeps the current addresses.
469    ///
470    /// HOW:
471    /// - Create a request with a host and an address; expect port 0 and that address.
472    /// - Set no address on requests with none and with one address; expect them unchanged.
473    /// - Take addresses; expect the iterator length to drop as it advances and nothing left.
474    /// - Expect a partly consumed iterator's `Debug` to show the remaining address.
475    #[test]
476    fn connect_with_addr() {
477        let addr: SocketAddr = "127.0.0.1:8080".parse().unwrap();
478        let connect = Connect::with("example.com", addr);
479        assert_eq!(connect.port(), 0);
480        assert_eq!(connect.addrs().len(), 1);
481        assert_eq!(connect.addrs().next(), Some(addr));
482
483        let connect: Connect<&str> = "example.com:80".into();
484        assert_eq!(connect.port(), 80);
485        assert_eq!(connect.addrs().len(), 0);
486
487        // `None` keeps the current addresses
488        let connect = connect.set_addr(None);
489        assert_eq!(connect.addrs().len(), 0);
490        let mut connect = connect.set_addr(Some(addr)).set_addr(None);
491        assert_eq!(connect.addrs().collect::<Vec<_>>(), vec![addr]);
492
493        let mut it = connect.take_addrs();
494        assert_eq!(it.len(), 1);
495        assert_eq!(it.next(), Some(addr));
496        assert_eq!(it.len(), 0);
497        assert_eq!(connect.take_addrs().len(), 0);
498
499        let mut connect = Connect::new(addr);
500        assert_eq!(connect.addrs().len(), 1);
501        assert_eq!(connect.take_addrs().len(), 1);
502
503        let addr2: SocketAddr = "127.0.0.1:8081".parse().unwrap();
504        let mut connect = Connect::new("example.com").set_addrs([addr, addr2]);
505        assert_eq!(connect.addrs().len(), 2);
506        let mut it = connect.take_addrs();
507        assert_eq!(it.len(), 2);
508        it.next();
509        assert_eq!(it.len(), 1);
510        assert!(format!("{it:?}").contains("8081"));
511    }
512
513    /// STATEMENT: A request owns one address list that every accessor agrees on.
514    ///
515    /// HOW:
516    /// - Start from a `SocketAddr`-backed request and check its intrinsic address
517    ///   and port seed `addrs()`, and that `set_addr` and `set_addrs` override it.
518    /// - Take the addresses twice and check the second `take_addrs()` is empty.
519    /// - Clear with `clear_addrs()` and with an empty `set_addrs`, check
520    ///   `set_addr(None)` keeps addresses, and repeat for a hostname-backed request.
521    /// - Check `map_addr` keeps the list rather than using the new intrinsic address.
522    #[test]
523    #[allow(clippy::similar_names)]
524    fn address_ownership() {
525        let a: SocketAddr = "127.0.0.1:8080".parse().unwrap();
526        let b: SocketAddr = "127.0.0.1:8081".parse().unwrap();
527        let c: SocketAddr = "127.0.0.1:8082".parse().unwrap();
528
529        let connect = Connect::new(a);
530        assert_eq!(connect.port(), 8080);
531        assert_eq!(connect.addrs().collect::<Vec<_>>(), vec![a]);
532        let connect = connect.set_addr(Some(b));
533        assert_eq!(connect.addrs().collect::<Vec<_>>(), vec![b]);
534        let mut connect = connect.set_addrs([b, c]);
535        assert_eq!(connect.addrs().collect::<Vec<_>>(), vec![b, c]);
536        assert_eq!(connect.take_addrs().collect::<Vec<_>>(), vec![b, c]);
537        assert_eq!(connect.addrs().len(), 0);
538
539        let mut connect = Connect::new(a);
540        assert_eq!(connect.take_addrs().collect::<Vec<_>>(), vec![a]);
541        assert_eq!(connect.take_addrs().len(), 0);
542        assert_eq!(connect.addrs().len(), 0);
543        assert_eq!(Connect::new(a).clear_addrs().addrs().len(), 0);
544        assert_eq!(Connect::new(a).set_addrs([]).addrs().len(), 0);
545        assert_eq!(Connect::new(a).set_addr(None).addrs().len(), 1);
546        assert_eq!(Connect::with(b, a).addrs().collect::<Vec<_>>(), vec![a]);
547
548        for connect in [
549            Connect::new("example.com").set_addr(Some(a)),
550            Connect::new("example.com").set_addrs([a, b]),
551        ] {
552            let mut taken = connect.clone();
553            assert!(taken.take_addrs().len() > 0);
554            assert_eq!(taken.take_addrs().len(), 0);
555            assert_eq!(connect.clone().clear_addrs().addrs().len(), 0);
556            assert_eq!(connect.clone().set_addrs([]).addrs().len(), 0);
557            assert_eq!(connect.clone().set_addr(None), connect);
558        }
559
560        let connect = Connect::new("example.com").map_addr(|_| a);
561        assert_eq!(connect.addrs().len(), 0);
562        let connect = Connect::new(a).clear_addrs().map_addr(|_| b);
563        assert_eq!(connect.addrs().len(), 0);
564    }
565}