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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
use crate::metrics_utils::describe_metrics;
use crate::{Manager, Pool};
use std::marker::PhantomData;
use std::time::Duration;

const DEFAULT_MAX_IDLE_CONNS: u64 = 2;
const DEFAULT_MAX_OPEN_CONNS: u64 = 10;
const DEFAULT_BAD_CONN_RETRIES: u32 = 2;

pub(crate) struct Config {
    pub max_open: u64,
    pub max_idle: u64,
    pub max_lifetime: Option<Duration>,
    pub max_idle_lifetime: Option<Duration>,
    pub clean_rate: Duration,
    pub max_bad_conn_retries: u32,
    pub get_timeout: Option<Duration>,
    pub health_check_interval: Option<Duration>,
    pub health_check: bool,
}

impl Config {
    pub fn split(self) -> (ShareConfig, InternalConfig) {
        let share = ShareConfig {
            clean_rate: self.clean_rate,
            max_bad_conn_retries: self.max_bad_conn_retries,
            get_timeout: self.get_timeout,
            health_check: self.health_check,
            health_check_interval: self.health_check_interval,
        };

        let internal = InternalConfig {
            max_open: self.max_open,
            max_idle: self.max_idle,
            max_lifetime: self.max_lifetime,
            max_idle_lifetime: self.max_idle_lifetime,
        };

        (share, internal)
    }
}

pub(crate) struct ShareConfig {
    pub clean_rate: Duration,
    pub max_bad_conn_retries: u32,
    pub get_timeout: Option<Duration>,
    pub health_check: bool,
    pub health_check_interval: Option<Duration>,
}

#[derive(Clone)]
pub(crate) struct InternalConfig {
    pub max_open: u64,
    pub max_idle: u64,
    pub max_lifetime: Option<Duration>,
    pub max_idle_lifetime: Option<Duration>,
}

/// A builder for a connection pool.
pub struct Builder<M> {
    max_open: u64,
    max_idle: Option<u64>,
    max_lifetime: Option<Duration>,
    max_idle_lifetime: Option<Duration>,
    clean_rate: Duration,
    max_bad_conn_retries: u32,
    get_timeout: Option<Duration>,
    health_check_interval: Option<Duration>,
    health_check: bool,
    _keep: PhantomData<M>,
}

impl<M> Default for Builder<M> {
    fn default() -> Self {
        Self {
            max_open: DEFAULT_MAX_OPEN_CONNS,
            max_idle: None,
            max_lifetime: None,
            max_idle_lifetime: None,
            clean_rate: Duration::from_secs(1),
            max_bad_conn_retries: DEFAULT_BAD_CONN_RETRIES,
            get_timeout: Some(Duration::from_secs(30)),
            _keep: PhantomData,
            health_check: true,
            health_check_interval: None,
        }
    }
}

impl<M: Manager> Builder<M> {
    /// Constructs a new `Builder`.
    ///
    /// Parameters are initialized with their default values.
    pub fn new() -> Self {
        Default::default()
    }

    /// Sets the maximum number of connections managed by the pool.
    ///
    /// - 0 means unlimited.
    /// - Defaults to 10.
    pub fn max_open(mut self, max_open: u64) -> Self {
        self.max_open = max_open;
        self
    }

    /// Sets the maximum idle connection count maintained by the pool.
    ///
    /// The pool will maintain at most this many idle connections
    /// at all times, while respecting the value of `max_open`.
    ///
    /// - 0 means unlimited (limited only by `max_open`).
    /// - Defaults to 2.
    pub fn max_idle(mut self, max_idle: u64) -> Self {
        self.max_idle = Some(max_idle);
        self
    }

    /// If true, the health of a connection will be verified via a call to
    /// `Manager::check` before it is checked out of the pool.
    ///
    /// - Defaults to true.
    pub fn test_on_check_out(mut self, health_check: bool) -> Builder<M> {
        self.health_check = health_check;
        self
    }

    /// Sets the maximum lifetime of connections in the pool.
    ///
    /// Expired connections may be closed lazily before reuse.
    ///
    /// - `None` means reuse forever.
    /// - Defaults to `None`.
    ///
    /// # Panics
    ///
    /// Panics if `max_lifetime` is the zero `Duration`.
    pub fn max_lifetime(mut self, max_lifetime: Option<Duration>) -> Self {
        assert_ne!(
            max_lifetime,
            Some(Duration::from_secs(0)),
            "max_lifetime must be positive"
        );
        self.max_lifetime = max_lifetime;
        self
    }

    /// Sets the maximum lifetime of connection to be idle in the pool,
    /// resetting the timer when connection is used.
    ///
    /// Expired connections may be closed lazily before reuse.
    ///
    /// - `None` means reuse forever.
    /// - Defaults to `None`.
    ///
    /// # Panics
    ///
    /// Panics if `max_idle_lifetime` is the zero `Duration`.
    pub fn max_idle_lifetime(mut self, max_idle_lifetime: Option<Duration>) -> Self {
        assert_ne!(
            max_idle_lifetime,
            Some(Duration::from_secs(0)),
            "max_idle_lifetime must be positive"
        );
        self.max_idle_lifetime = max_idle_lifetime;
        self
    }

    /// Sets the get timeout used by the pool.
    ///
    /// Calls to `Pool::get` will wait this long for a connection to become
    /// available before returning an error.
    ///
    /// - `None` means never timeout.
    /// - Defaults to 30 seconds.
    ///
    /// # Panics
    ///
    /// Panics if `connection_timeout` is the zero duration
    pub fn get_timeout(mut self, get_timeout: Option<Duration>) -> Self {
        assert_ne!(
            get_timeout,
            Some(Duration::from_secs(0)),
            "get_timeout must be positive"
        );

        self.get_timeout = get_timeout;
        self
    }

    /// Sets the interval how often a connection will be checked when returning
    /// an existing connection from the pool. If set to `None`, a connection is
    /// checked every time when returning from the pool. Must be used together
    /// with [`test_on_check_out`] set to `true`, otherwise does nothing.
    ///
    /// - `None` means a connection is checked every time when returning from the
    ///   pool.
    /// - Defaults to `None`.
    ///
    /// # Panics
    ///
    /// Panics if `connection_timeout` is the zero duration
    ///
    /// [`test_on_check_out`]: #method.test_on_check_out
    pub fn health_check_interval(mut self, health_check_interval: Option<Duration>) -> Self {
        assert_ne!(
            health_check_interval,
            Some(Duration::from_secs(0)),
            "health_check_interval must be positive"
        );

        self.health_check_interval = health_check_interval;
        self
    }
    // used by tests
    #[doc(hidden)]
    #[allow(dead_code)]
    pub fn clean_rate(mut self, clean_rate: Duration) -> Builder<M> {
        assert!(
            clean_rate > Duration::from_secs(0),
            "connection_timeout must be positive"
        );

        if clean_rate > Duration::from_secs(1) {
            self.clean_rate = clean_rate;
        }

        self
    }

    /// Consumes the builder, returning a new, initialized pool.
    pub fn build(self, manager: M) -> Pool<M> {
        describe_metrics();
        let mut max_idle = self.max_idle.unwrap_or(DEFAULT_MAX_IDLE_CONNS);
        if self.max_open > 0 && max_idle > self.max_open {
            max_idle = self.max_open
        };

        let config = Config {
            max_open: self.max_open,
            max_idle,
            max_lifetime: self.max_lifetime,
            max_idle_lifetime: self.max_idle_lifetime,
            get_timeout: self.get_timeout,
            clean_rate: self.clean_rate,
            max_bad_conn_retries: self.max_bad_conn_retries,
            health_check: self.health_check,
            health_check_interval: self.health_check_interval,
        };

        Pool::new_inner(manager, config)
    }
}