actix_http/
keep_alive.rs

1use std::time::Duration;
2
3/// Connection keep-alive config.
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub enum KeepAlive {
6    /// Keep-alive duration.
7    ///
8    /// `KeepAlive::Timeout(Duration::ZERO)` is mapped to `KeepAlive::Disabled`.
9    Timeout(Duration),
10
11    /// Rely on OS to shutdown TCP connection.
12    ///
13    /// Some defaults can be very long, check your OS documentation.
14    Os,
15
16    /// Keep-alive is disabled.
17    ///
18    /// Connections will be closed immediately.
19    Disabled,
20}
21
22impl KeepAlive {
23    pub(crate) fn enabled(&self) -> bool {
24        !matches!(self, Self::Disabled)
25    }
26
27    #[allow(unused)] // used with `http2` feature flag
28    pub(crate) fn duration(&self) -> Option<Duration> {
29        match self {
30            KeepAlive::Timeout(dur) => Some(*dur),
31            _ => None,
32        }
33    }
34
35    /// Map zero duration to disabled.
36    pub(crate) fn normalize(self) -> KeepAlive {
37        match self {
38            KeepAlive::Timeout(Duration::ZERO) => KeepAlive::Disabled,
39            ka => ka,
40        }
41    }
42}
43
44impl Default for KeepAlive {
45    fn default() -> Self {
46        Self::Timeout(Duration::from_secs(5))
47    }
48}
49
50impl From<Duration> for KeepAlive {
51    fn from(dur: Duration) -> Self {
52        KeepAlive::Timeout(dur).normalize()
53    }
54}
55
56impl From<Option<Duration>> for KeepAlive {
57    fn from(ka_dur: Option<Duration>) -> Self {
58        match ka_dur {
59            Some(dur) => KeepAlive::from(dur),
60            None => KeepAlive::Disabled,
61        }
62        .normalize()
63    }
64}
65
66#[cfg(test)]
67mod tests {
68    use super::*;
69
70    #[test]
71    fn from_impls() {
72        let test: KeepAlive = Duration::from_secs(1).into();
73        assert_eq!(test, KeepAlive::Timeout(Duration::from_secs(1)));
74
75        let test: KeepAlive = Duration::from_secs(0).into();
76        assert_eq!(test, KeepAlive::Disabled);
77
78        let test: KeepAlive = Some(Duration::from_secs(0)).into();
79        assert_eq!(test, KeepAlive::Disabled);
80
81        let test: KeepAlive = None.into();
82        assert_eq!(test, KeepAlive::Disabled);
83    }
84}