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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
#![deny(missing_docs)]
extern crate crossbeam_queue;
extern crate futures;
extern crate tokio;
#[macro_use]
extern crate failure;
#[macro_use]
extern crate log;
#[macro_use]
extern crate async_trait;
mod conn;
mod error;
mod inner;
mod manage_connection;
mod queue;
use futures::channel::oneshot;
use futures::future::{self};
use futures::prelude::*;
use futures::stream;
use std::fmt;
use std::sync::Arc;
use std::time::Duration;
use tokio::time;
use crate::error::InternalError;
pub use conn::Conn;
pub use error::Error;
pub use manage_connection::ManageConnection;
use inner::ConnectionPool;
use queue::{Live, Queue};
pub struct Pool<C: ManageConnection + Send> {
conn_pool: Arc<ConnectionPool<C>>,
}
impl<C: ManageConnection + Send + fmt::Debug> fmt::Debug for Pool<C> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Pool")
.field("conn_pool", &self.conn_pool)
.finish()
}
}
#[derive(Debug)]
pub struct Config {
pub min_size: usize,
pub max_size: usize,
}
impl Default for Config {
fn default() -> Self {
Config {
max_size: 10,
min_size: 1,
}
}
}
impl<C> Clone for Pool<C>
where
C: ManageConnection,
{
fn clone(&self) -> Pool<C> {
Pool {
conn_pool: self.conn_pool.clone(),
}
}
}
impl<C: ManageConnection + Send> Pool<C> {
pub async fn new(manager: C, config: Config) -> Result<Pool<C>, Error<C::Error>> {
assert!(
config.max_size >= config.min_size,
"max_size of pool must be greater than or equal to the min_size"
);
let conns: stream::FuturesUnordered<_> = std::iter::repeat(&manager)
.take(config.min_size)
.map(|c| c.connect())
.collect();
let conns = conns
.try_fold(Queue::new(), |conns, conn| {
conns.new_conn(Live::new(conn));
future::ok(conns)
})
.await?;
let conn_pool = Arc::new(ConnectionPool::new(conns, manager, config));
Ok(Pool { conn_pool })
}
pub async fn connection(&self) -> Result<Conn<C>, Error<C::Error>> {
{
if let Some(conn) = self.conn_pool.conns.get() {
debug!("connection: connection already in pool and ready to go");
return Ok(Conn {
conn: Some(conn),
pool: Some(self.clone()),
});
} else {
debug!("connection: try spawn connection");
if let Some(conn) = self.try_spawn_connection().await {
let conn = conn?;
let this = self.clone();
debug!("connection: spawned connection");
return Ok(Conn {
conn: Some(conn),
pool: Some(this),
});
}
}
}
let (tx, rx) = oneshot::channel();
debug!("connection: pushing to notify of connection");
self.conn_pool.notify_of_connection(tx);
let this = self.clone();
debug!("connection: waiting for connection");
let conn = rx.await.map_err(|_| {
Error::Internal(InternalError::Other(
"Connection channel was closed unexpectedly".into(),
))
})?;
debug!("connection: got connection after waiting");
Ok(Conn {
conn: Some(conn),
pool: Some(this),
})
}
pub(crate) async fn try_spawn_connection(
&self,
) -> Option<Result<Live<C::Connection>, Error<C::Error>>> {
if self
.conn_pool
.conns
.safe_increment(self.conn_pool.max_size())
.is_some()
{
debug!("try_spawn_connection: starting connection");
let result = match self.conn_pool.connect().await {
Ok(conn) => Ok(Live::new(conn)),
Err(err) => {
self.conn_pool.conns.decrement();
Err(err)
}
};
Some(result)
} else {
None
}
}
pub fn put_back(&self, mut conn: Live<C::Connection>) {
debug!("put_back: start put back");
let broken = self.conn_pool.has_broken(&mut conn);
if broken {
self.conn_pool.conns.decrement();
debug!(
"connection count is now: {:?}",
self.conn_pool.conns.total()
);
self.spawn_new_future_loop();
return;
}
let mut conn = conn;
while let Some(waiting) = self.conn_pool.try_waiting() {
debug!("put_back: got a waiting connection, sending");
conn = match waiting.send(conn) {
Ok(_) => return,
Err(conn) => {
debug!("put_back: unable to send connection");
conn
}
};
}
debug!("put_back: no waiting connection, storing");
self.conn_pool.conns.store(conn);
}
fn spawn_new_future_loop(&self) {
let this1 = self.clone();
tokio::spawn(async move {
loop {
let this = this1.clone();
let res = this.conn_pool.connect().await;
match res {
Ok(conn) => {
debug!("creating new connection from spawn loop");
this.conn_pool.conns.increment();
this.put_back(Live::new(conn));
break;
}
Err(err) => {
error!(
"unable to establish new connection, trying again: {:?}",
err
);
time::delay_for(Duration::from_secs(1)).await;
}
}
}
});
}
pub fn total_conns(&self) -> usize {
self.conn_pool.conns.total()
}
pub fn idle_conns(&self) -> usize {
self.conn_pool.conns.idle()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::{atomic::*, Arc};
use std::time::Duration;
use tokio::time::timeout;
#[derive(Debug)]
pub struct DummyManager {}
#[derive(Debug, Fail)]
#[fail(display = "DummyError")]
pub struct DummyError;
impl DummyManager {
pub fn new() -> Self {
Self {}
}
}
#[async_trait]
impl ManageConnection for DummyManager {
type Connection = ();
type Error = DummyError;
async fn connect(&self) -> Result<Self::Connection, Error<Self::Error>> {
Ok(())
}
async fn is_valid(&self, _conn: &mut Self::Connection) -> Result<(), Error<Self::Error>> {
unimplemented!()
}
fn has_broken(&self, _conn: &mut Self::Connection) -> bool {
false
}
fn timed_out(&self) -> Error<Self::Error> {
unimplemented!()
}
}
#[tokio::test]
async fn simple_pool_creation_and_connection() {
let mngr = DummyManager::new();
let config: Config = Default::default();
let pool = Pool::new(mngr, config).await.unwrap();
let conn = pool.connection().await.unwrap();
assert!(conn.conn.is_some(), "connection is not correct type");
}
#[tokio::test]
async fn it_returns_a_non_resolved_future_when_over_pool_limit() {
let mngr = DummyManager::new();
let config: Config = Config {
max_size: 1,
min_size: 1,
};
let pool = Pool::new(mngr, config).await.unwrap();
::std::mem::forget(pool.connection().await.unwrap());
let result = tokio::time::timeout(Duration::from_millis(10), pool.connection()).await;
assert!(result.is_err(), "didn't timeout");
}
#[tokio::test]
async fn it_allocates_new_connections_up_to_max_size() {
let mngr = DummyManager::new();
let config: Config = Config {
max_size: 2,
min_size: 1,
};
let pool = Pool::new(mngr, config).await.unwrap();
let connection = pool.connection().await.unwrap();
::std::mem::forget(connection);
let f1 = async {
let conn = tokio::time::timeout(Duration::from_millis(10), pool.connection())
.await
.expect("second connection timed out");
::std::mem::forget(conn);
};
let f2 = async {
let result = tokio::time::timeout(Duration::from_millis(10), pool.connection()).await;
assert!(result.is_err(), "third didn't timeout");
};
futures::join!(f1, f2);
}
#[tokio::test]
async fn test_can_be_accessed_by_mutliple_futures_concurrently() {
let mngr = DummyManager::new();
let config = Config {
min_size: 2,
max_size: 2,
};
let pool = Arc::new(Pool::new(mngr, config).await.unwrap());
let count = Arc::new(AtomicUsize::new(0));
futures::join!(
loop_run(Arc::clone(&count), Arc::clone(&pool)),
loop_run(Arc::clone(&count), Arc::clone(&pool))
);
assert_eq!(pool.total_conns(), 2);
assert_eq!(pool.idle_conns(), 2);
}
async fn loop_run(count: Arc<AtomicUsize>, pool: Arc<Pool<DummyManager>>) {
tokio::spawn(async move {
loop {
timeout(Duration::from_secs(5), pool.connection())
.await
.expect("connection timed out")
.expect("error getting connection");
let old_count = count.fetch_add(1, Ordering::SeqCst);
if old_count + 1 >= 100 {
break;
}
}
})
.await
.unwrap();
}
}