redis_async/client/
builder.rs

1/*
2 * Copyright 2020-2024 Ben Ashford
3 *
4 * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 * http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 * <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 * option. This file may not be copied, modified, or distributed
8 * except according to those terms.
9 */
10
11use std::sync::Arc;
12use std::time::Duration;
13
14use crate::error;
15
16#[derive(Debug)]
17/// Connection builder
18pub struct ConnectionBuilder {
19    pub(crate) host: String,
20    pub(crate) port: u16,
21    pub(crate) username: Option<Arc<str>>,
22    pub(crate) password: Option<Arc<str>>,
23    #[cfg(feature = "tls")]
24    pub(crate) tls: bool,
25    pub(crate) socket_keepalive: Option<Duration>,
26    pub(crate) socket_timeout: Option<Duration>,
27}
28
29const DEFAULT_KEEPALIVE: Duration = Duration::from_secs(60);
30const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
31
32impl ConnectionBuilder {
33    pub fn new(host: impl Into<String>, port: u16) -> Result<Self, error::Error> {
34        Ok(Self {
35            host: host.into(),
36            port,
37            username: None,
38            password: None,
39            #[cfg(feature = "tls")]
40            tls: false,
41            socket_keepalive: Some(DEFAULT_KEEPALIVE),
42            socket_timeout: Some(DEFAULT_TIMEOUT),
43        })
44    }
45
46    /// Set the username used when connecting
47    pub fn password<V: Into<Arc<str>>>(&mut self, password: V) -> &mut Self {
48        self.password = Some(password.into());
49        self
50    }
51
52    /// Set the password used when connecting
53    pub fn username<V: Into<Arc<str>>>(&mut self, username: V) -> &mut Self {
54        self.username = Some(username.into());
55        self
56    }
57
58    #[cfg(feature = "tls")]
59    pub fn tls(&mut self) -> &mut Self {
60        self.tls = true;
61        self
62    }
63
64    /// Set the socket keepalive duration
65    pub fn socket_keepalive(&mut self, duration: Option<Duration>) -> &mut Self {
66        self.socket_keepalive = duration;
67        self
68    }
69
70    /// Set the socket timeout duration
71    pub fn socket_timeout(&mut self, duration: Option<Duration>) -> &mut Self {
72        self.socket_timeout = duration;
73        self
74    }
75}