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
use crate::SmolTransport;
use async_net::TcpStream;
use std::{
    future::Future,
    io::{Error, ErrorKind, Result},
};
use trillium_server_common::{
    async_trait,
    url::{Host, Url},
    Connector, Transport,
};

/**
configuration for the tcp Connector
*/
#[derive(Default, Debug, Clone, Copy)]
pub struct ClientConfig {
    /// disable [nagle's algorithm](https://en.wikipedia.org/wiki/Nagle%27s_algorithm)
    pub nodelay: Option<bool>,

    /// set a time to live for the tcp protocol
    pub ttl: Option<u32>,
}

impl ClientConfig {
    /// constructs a default ClientConfig
    pub const fn new() -> Self {
        Self {
            nodelay: None,
            ttl: None,
        }
    }

    /// chainable setter to set default nodelay
    pub const fn with_nodelay(mut self, nodelay: bool) -> Self {
        self.nodelay = Some(nodelay);
        self
    }

    /// chainable setter for ip ttl
    pub const fn with_ttl(mut self, ttl: u32) -> Self {
        self.ttl = Some(ttl);
        self
    }
}

#[async_trait]
impl Connector for ClientConfig {
    type Transport = SmolTransport<TcpStream>;

    async fn connect(&self, url: &Url) -> Result<Self::Transport> {
        if url.scheme() != "http" {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                format!("unknown scheme {}", url.scheme()),
            ));
        }

        let port = url
            .port_or_known_default()
            // this should be ok because we already checked that the scheme is http, which has a default port
            .ok_or_else(|| Error::new(ErrorKind::InvalidInput, format!("{url} missing port")))?;

        let host = url
            .host()
            .ok_or_else(|| Error::new(ErrorKind::InvalidInput, format!("{url} missing host")))?;

        let mut tcp = match host {
            Host::Domain(domain) => Self::Transport::connect((domain, port)).await?,
            Host::Ipv4(ip) => Self::Transport::connect((ip, port)).await?,
            Host::Ipv6(ip) => Self::Transport::connect((ip, port)).await?,
        };

        if let Some(nodelay) = self.nodelay {
            tcp.set_nodelay(nodelay)?;
        }

        if let Some(ttl) = self.ttl {
            tcp.set_ip_ttl(ttl)?;
        }

        Ok(tcp)
    }

    fn spawn<Fut: Future<Output = ()> + Send + 'static>(&self, fut: Fut) {
        async_global_executor::spawn(fut).detach();
    }
}