Skip to main content

ntex_tls/
config.rs

1use ntex_service::cfg::{CfgContext, Configuration};
2use ntex_util::time::{Millis, Seconds};
3
4#[derive(Debug)]
5/// Tls service configuration
6pub struct TlsConfig {
7    pub(crate) handshake_timeout: Millis,
8    pub(crate) config: CfgContext,
9}
10
11impl Default for TlsConfig {
12    fn default() -> Self {
13        TlsConfig::new()
14    }
15}
16
17impl Configuration for TlsConfig {
18    const NAME: &str = "TLS Configuration";
19
20    fn ctx(&self) -> &CfgContext {
21        &self.config
22    }
23
24    fn set_ctx(&mut self, ctx: CfgContext) {
25        self.config = ctx;
26    }
27}
28
29impl TlsConfig {
30    #[must_use]
31    /// Create instance of `TlsConfig`
32    pub fn new() -> Self {
33        TlsConfig {
34            handshake_timeout: Millis(5_000),
35            config: CfgContext::default(),
36        }
37    }
38
39    #[inline]
40    /// Get tls handshake timeout.
41    pub fn handshake_timeout(&self) -> Millis {
42        self.handshake_timeout
43    }
44
45    #[must_use]
46    /// Set tls handshake timeout.
47    ///
48    /// Defines a timeout for connection tls handshake negotiation.
49    /// To disable timeout set value to 0.
50    ///
51    /// By default handshake timeout is set to 5 seconds.
52    pub fn set_handshake_timeout<T: Into<Seconds>>(mut self, timeout: T) -> Self {
53        self.handshake_timeout = timeout.into().into();
54        self
55    }
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61
62    #[test]
63    fn tls_config() {
64        let cfg = TlsConfig::default();
65        assert_eq!(cfg.handshake_timeout(), Millis(5_000));
66        let cfg = cfg.set_handshake_timeout(Seconds(1));
67        assert_eq!(cfg.handshake_timeout(), Millis(1_000));
68        assert_eq!(
69            cfg.set_handshake_timeout(Seconds::ZERO).handshake_timeout(),
70            Millis::ZERO
71        );
72    }
73}