redis_async/client/
builder.rs

1/*
2 * Copyright 2020-2025 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, reconnect::ReconnectOptions};
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    pub(crate) reconnect_options: ReconnectOptions,
24    #[cfg(feature = "tls")]
25    pub(crate) tls: bool,
26    pub(crate) socket_keepalive: Option<Duration>,
27    pub(crate) socket_timeout: Option<Duration>,
28}
29
30const DEFAULT_KEEPALIVE: Duration = Duration::from_secs(60);
31const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
32
33impl ConnectionBuilder {
34    pub fn new(host: impl Into<String>, port: u16) -> Result<Self, error::Error> {
35        Ok(Self {
36            host: host.into(),
37            port,
38            username: None,
39            password: None,
40            reconnect_options: ReconnectOptions::default(),
41            #[cfg(feature = "tls")]
42            tls: false,
43            socket_keepalive: Some(DEFAULT_KEEPALIVE),
44            socket_timeout: Some(DEFAULT_TIMEOUT),
45        })
46    }
47
48    /// Set the username used when connecting
49    pub fn password<V: Into<Arc<str>>>(&mut self, password: V) -> &mut Self {
50        self.password = Some(password.into());
51        self
52    }
53
54    /// Set the password used when connecting
55    pub fn username<V: Into<Arc<str>>>(&mut self, username: V) -> &mut Self {
56        self.username = Some(username.into());
57        self
58    }
59
60    #[cfg(feature = "tls")]
61    pub fn tls(&mut self) -> &mut Self {
62        self.tls = true;
63        self
64    }
65
66    /// Set the socket keepalive duration
67    pub fn socket_keepalive(&mut self, duration: Option<Duration>) -> &mut Self {
68        self.socket_keepalive = duration;
69        self
70    }
71
72    /// Set the socket timeout duration
73    pub fn socket_timeout(&mut self, duration: Option<Duration>) -> &mut Self {
74        self.socket_timeout = duration;
75        self
76    }
77
78    /// Set the reconnect timeout
79    pub fn reconnect_timeout(&mut self, duration: Duration) -> &mut Self {
80        self.reconnect_options.connection_timeout = duration;
81        self
82    }
83
84    /// Set the number of reconnection attempts
85    pub fn reconnect_attempts(&mut self, attempts: u64) -> &mut Self {
86        self.reconnect_options.max_connection_attempts = attempts;
87        self
88    }
89}