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
use core::time::Duration;

use std::{io, net::SocketAddr};

use socket2::{SockRef, TcpKeepalive};

use tracing::warn;
use xitca_io::net::{Stream as ServerStream, TcpStream};
use xitca_service::{ready::ReadyService, Service};

#[cfg(unix)]
use xitca_io::net::UnixStream;

/// A middleware for socket options config of `TcpStream` and `UnixStream`.
#[derive(Clone, Debug)]
pub struct SocketConfig {
    ka: Option<TcpKeepalive>,
    nodelay: bool,
}

impl Default for SocketConfig {
    fn default() -> Self {
        Self::new()
    }
}

impl SocketConfig {
    pub const fn new() -> Self {
        Self {
            ka: None,
            nodelay: false,
        }
    }

    /// For more information about this option, see [`set_nodelay`].
    ///
    /// [`set_nodelay`]: socket2::Socket::set_nodelay
    pub fn set_nodelay(mut self, value: bool) -> Self {
        self.nodelay = value;
        self
    }

    /// For more information about this option, see [`with_time`].
    ///
    /// [`with_time`]: TcpKeepalive::with_time
    pub fn keep_alive_with_time(mut self, time: Duration) -> Self {
        self.ka = Some(self.ka.unwrap_or_else(TcpKeepalive::new).with_time(time));
        self
    }

    /// For more information about this option, see [`with_interval`].
    ///
    /// [`with_interval`]: TcpKeepalive::with_interval
    pub fn keep_alive_with_interval(mut self, time: Duration) -> Self {
        self.ka = Some(self.ka.unwrap_or_else(TcpKeepalive::new).with_interval(time));
        self
    }

    #[cfg(not(windows))]
    /// For more information about this option, see [`with_retries`].
    ///
    /// [`with_retries`]: TcpKeepalive::with_retries
    pub fn keep_alive_with_retries(mut self, retries: u32) -> Self {
        self.ka = Some(self.ka.unwrap_or_else(TcpKeepalive::new).with_retries(retries));
        self
    }
}

impl<S, E> Service<Result<S, E>> for SocketConfig {
    type Response = SocketConfigService<S>;
    type Error = E;

    async fn call(&self, res: Result<S, E>) -> Result<Self::Response, Self::Error> {
        res.map(|service| SocketConfigService {
            config: self.clone(),
            service,
        })
    }
}

impl<S> ReadyService for SocketConfigService<S>
where
    S: ReadyService,
{
    type Ready = S::Ready;

    #[inline]
    async fn ready(&self) -> Self::Ready {
        self.service.ready().await
    }
}

impl<S> Service<(TcpStream, SocketAddr)> for SocketConfigService<S>
where
    S: Service<(TcpStream, SocketAddr)>,
{
    type Response = S::Response;
    type Error = S::Error;

    async fn call(&self, (stream, addr): (TcpStream, SocketAddr)) -> Result<Self::Response, Self::Error> {
        self.try_apply_config(&stream);
        self.service.call((stream, addr)).await
    }
}

#[cfg(unix)]
impl<S> Service<(UnixStream, SocketAddr)> for SocketConfigService<S>
where
    S: Service<(UnixStream, SocketAddr)>,
{
    type Response = S::Response;
    type Error = S::Error;

    async fn call(&self, (stream, addr): (UnixStream, SocketAddr)) -> Result<Self::Response, Self::Error> {
        self.try_apply_config(&stream);
        self.service.call((stream, addr)).await
    }
}

impl<S> Service<ServerStream> for SocketConfigService<S>
where
    S: Service<ServerStream>,
{
    type Response = S::Response;
    type Error = S::Error;

    #[inline]
    async fn call(&self, stream: ServerStream) -> Result<Self::Response, Self::Error> {
        #[cfg_attr(windows, allow(irrefutable_let_patterns))]
        if let ServerStream::Tcp(ref tcp, _) = stream {
            self.try_apply_config(tcp)
        };

        #[cfg(unix)]
        if let ServerStream::Unix(ref unix, _) = stream {
            self.try_apply_config(unix)
        };

        self.service.call(stream).await
    }
}

pub struct SocketConfigService<S> {
    config: SocketConfig,
    service: S,
}

impl<S> SocketConfigService<S> {
    fn apply_config<'s>(&self, stream: impl Into<SockRef<'s>>) -> io::Result<()> {
        let stream_ref = stream.into();

        stream_ref.set_nodelay(self.config.nodelay)?;

        if let Some(ka) = self.config.ka.as_ref() {
            stream_ref.set_tcp_keepalive(ka)?;
        }

        Ok(())
    }

    fn try_apply_config<'s>(&self, stream: impl Into<SockRef<'s>>) {
        if let Err(e) = self.apply_config(stream) {
            warn!(target: "SocketConfig", "Failed to apply configuration to SocketConfig. {:?}", e);
        };
    }
}