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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
use futures_util::FutureExt;
use tokio::sync::mpsc;
use std::{
collections::VecDeque,
convert::TryFrom,
pin::Pin,
str::FromStr,
sync::{atomic, Arc, Mutex},
task::{Context, Poll, Waker},
time::{Duration, Instant},
};
use crate::{
conn::{pool::futures::*, Conn},
error::*,
opts::{Opts, PoolOpts},
queryable::transaction::{Transaction, TxOpts, TxStatus},
};
mod recycler;
pub mod futures;
mod ttl_check_inerval;
#[derive(Debug)]
struct IdlingConn {
since: Instant,
conn: Conn,
}
impl IdlingConn {
fn elapsed(&self) -> Duration {
self.since.elapsed()
}
}
impl From<Conn> for IdlingConn {
fn from(conn: Conn) -> Self {
Self {
since: Instant::now(),
conn,
}
}
}
#[derive(Debug)]
struct Exchange {
waiting: VecDeque<Waker>,
available: VecDeque<IdlingConn>,
exist: usize,
recycler: Option<(mpsc::UnboundedReceiver<Option<Conn>>, PoolOpts)>,
}
impl Exchange {
fn spawn_futures_if_needed(&mut self, inner: &Arc<Inner>) {
use recycler::Recycler;
use ttl_check_inerval::TtlCheckInterval;
if let Some((dropped, pool_opts)) = self.recycler.take() {
tokio::spawn(Recycler::new(pool_opts.clone(), inner.clone(), dropped));
if pool_opts.inactive_connection_ttl() > Duration::from_secs(0) {
tokio::spawn(TtlCheckInterval::new(pool_opts, inner.clone()));
}
}
}
}
#[derive(Debug)]
pub struct Inner {
close: atomic::AtomicBool,
closed: atomic::AtomicBool,
exchange: Mutex<Exchange>,
}
#[derive(Debug, Clone)]
pub struct Pool {
opts: Opts,
inner: Arc<Inner>,
drop: mpsc::UnboundedSender<Option<Conn>>,
}
impl Pool {
pub fn new<O>(opts: O) -> Pool
where
Opts: TryFrom<O>,
<Opts as TryFrom<O>>::Error: std::error::Error,
{
let opts = Opts::try_from(opts).unwrap();
let pool_opts = opts.pool_opts().clone();
let (tx, rx) = mpsc::unbounded_channel();
Pool {
opts,
inner: Arc::new(Inner {
close: false.into(),
closed: false.into(),
exchange: Mutex::new(Exchange {
available: VecDeque::with_capacity(pool_opts.constraints().max()),
waiting: VecDeque::new(),
exist: 0,
recycler: Some((rx, pool_opts)),
}),
}),
drop: tx,
}
}
pub fn from_url<T: AsRef<str>>(url: T) -> Result<Pool> {
let opts = Opts::from_str(url.as_ref())?;
Ok(Pool::new(opts))
}
pub fn get_conn(&self) -> GetConn {
GetConn::new(self)
}
pub async fn start_transaction(&self, options: TxOpts) -> Result<Transaction<'static>> {
let conn = self.get_conn().await?;
Transaction::new(conn, options).await
}
pub fn disconnect(self) -> DisconnectPool {
let was_closed = self.inner.close.swap(true, atomic::Ordering::AcqRel);
if !was_closed {
let _ = self.drop.send(None).is_ok();
}
DisconnectPool::new(self)
}
fn return_conn(&mut self, conn: Conn) {
if conn.inner.stream.is_some()
&& !conn.inner.disconnected
&& !conn.expired()
&& conn.inner.tx_status == TxStatus::None
&& !conn.has_pending_result()
&& !self.inner.close.load(atomic::Ordering::Acquire)
{
let mut exchange = self.inner.exchange.lock().unwrap();
if exchange.available.len() < self.opts.pool_opts().active_bound() {
exchange.available.push_back(conn.into());
if let Some(w) = exchange.waiting.pop_front() {
w.wake();
}
return;
}
}
self.send_to_recycler(conn);
}
fn send_to_recycler(&self, conn: Conn) {
if let Err(conn) = self.drop.send(Some(conn)) {
let conn = conn.0.unwrap();
if !self.inner.closed.load(atomic::Ordering::SeqCst) {
assert!(conn.inner.pool.is_none());
drop(conn);
} else {
unreachable!("Recycler exited while connections still exist");
}
}
}
fn cancel_connection(&self) {
let mut exchange = self.inner.exchange.lock().unwrap();
exchange.exist -= 1;
if let Some(w) = exchange.waiting.pop_front() {
w.wake();
}
}
fn poll_new_conn(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<GetConn>> {
self.poll_new_conn_inner(cx)
}
fn poll_new_conn_inner(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<GetConn>> {
let mut exchange = self.inner.exchange.lock().unwrap();
if self.inner.close.load(atomic::Ordering::Acquire) {
return Err(Error::Driver(DriverError::PoolDisconnected)).into();
}
exchange.spawn_futures_if_needed(&self.inner);
while let Some(IdlingConn { mut conn, .. }) = exchange.available.pop_back() {
if !conn.expired() {
return Poll::Ready(Ok(GetConn {
pool: Some(self.clone()),
inner: GetConnInner::Checking(
async move {
conn.stream_mut()?.check().await?;
Ok(conn)
}
.boxed(),
),
}));
} else {
self.send_to_recycler(conn);
}
}
if exchange.exist < self.opts.pool_opts().constraints().max() {
exchange.exist += 1;
return Poll::Ready(Ok(GetConn {
pool: Some(self.clone()),
inner: GetConnInner::Connecting(Conn::new(self.opts.clone()).boxed()),
}));
}
exchange.waiting.push_back(cx.waker().clone());
Poll::Pending
}
}
impl Drop for Conn {
fn drop(&mut self) {
if std::thread::panicking() {
return;
}
if let Some(mut pool) = self.inner.pool.take() {
pool.return_conn(self.take());
} else if self.inner.stream.is_some() && !self.inner.disconnected {
crate::conn::disconnect(self.take());
}
}
}
#[cfg(test)]
mod test {
use futures_util::{
future::{join_all, select, select_all, try_join_all},
try_join, FutureExt,
};
use mysql_common::row::Row;
use tokio::time::sleep;
use std::time::Duration;
use crate::{
conn::pool::Pool, opts::PoolOpts, prelude::*, test_misc::get_opts, PoolConstraints, TxOpts,
};
macro_rules! conn_ex_field {
($conn:expr, $field:tt) => {
ex_field!($conn.inner.pool.as_ref().unwrap(), $field)
};
}
macro_rules! ex_field {
($pool:expr, $field:tt) => {
$pool.inner.exchange.lock().unwrap().$field
};
}
#[test]
fn should_not_hang() -> super::Result<()> {
pub struct Database {
pool: Pool,
}
impl Database {
pub async fn disconnect(self) -> super::Result<()> {
self.pool.disconnect().await?;
Ok(())
}
}
let runtime = tokio::runtime::Runtime::new().unwrap();
let database = Database {
pool: Pool::new(get_opts()),
};
runtime.block_on(database.disconnect())
}
#[tokio::test]
async fn should_track_conn_if_disconnected_outside_of_a_pool() -> super::Result<()> {
let pool = Pool::new(get_opts());
let conn = pool.get_conn().await?;
conn.disconnect().await?;
pool.disconnect().await?;
Ok(())
}
#[tokio::test]
async fn should_connect() -> super::Result<()> {
let pool = Pool::new(get_opts());
pool.get_conn().await?.ping().await?;
pool.disconnect().await?;
Ok(())
}
#[tokio::test]
async fn should_reconnect() -> super::Result<()> {
let mut master = crate::Conn::new(get_opts()).await?;
async fn test(master: &mut crate::Conn, opts: crate::OptsBuilder) -> super::Result<()> {
const NUM_CONNS: usize = 5;
let pool = Pool::new(opts);
let connections = (0..NUM_CONNS).map(|_| {
async {
let mut conn = pool.get_conn().await?;
conn.ping().await?;
crate::Result::Ok(conn)
}
.boxed()
});
let ids = try_join_all(connections)
.await?
.into_iter()
.map(|conn| conn.id())
.collect::<Vec<_>>();
pool.get_conn().await?;
for id in ids {
master.query_drop(&format!("KILL {}", id)).await?;
}
assert_eq!(ex_field!(pool, available).len(), NUM_CONNS);
sleep(Duration::from_millis(500)).await;
let _conn = pool.get_conn().await?;
assert_eq!(ex_field!(pool, available).len(), 0);
drop(_conn);
pool.disconnect().await
}
println!("Check socket/pipe..");
test(&mut master, get_opts()).await?;
println!("Check tcp..");
test(&mut master, get_opts().prefer_socket(false)).await?;
master.disconnect().await
}
#[tokio::test]
#[ignore]
async fn can_handle_the_pressure() {
let pool = Pool::new(get_opts());
for _ in 0..10i32 {
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
for i in 0..10_000 {
let pool = pool.clone();
let tx = tx.clone();
tokio::spawn(async move {
let _ = pool.get_conn().await.unwrap();
tx.send(i).unwrap();
});
}
drop(tx);
while let Some(_) = rx.recv().await {}
}
drop(pool);
}
#[tokio::test]
async fn should_start_transaction() -> super::Result<()> {
let constraints = PoolConstraints::new(1, 1).unwrap();
let opts = get_opts().pool_opts(PoolOpts::default().with_constraints(constraints));
let pool = Pool::new(opts);
"CREATE TEMPORARY TABLE tmp(id int)".ignore(&pool).await?;
let mut tx = pool.start_transaction(TxOpts::default()).await?;
tx.exec_batch("INSERT INTO tmp (id) VALUES (?)", vec![(1_u8,), (2_u8,)])
.await?;
tx.exec_drop("SELECT * FROM tmp", ()).await?;
drop(tx);
let row_opt = pool
.get_conn()
.await?
.query_first("SELECT COUNT(*) FROM tmp")
.await?;
assert_eq!(row_opt, Some((0u8,)));
pool.get_conn().await?.query_drop("DROP TABLE tmp").await?;
pool.disconnect().await?;
Ok(())
}
#[tokio::test]
async fn should_check_inactive_connection_ttl() -> super::Result<()> {
const POOL_MIN: usize = 5;
const POOL_MAX: usize = 10;
const INACTIVE_CONNECTION_TTL: Duration = Duration::from_millis(500);
const TTL_CHECK_INTERVAL: Duration = Duration::from_secs(1);
let constraints = PoolConstraints::new(POOL_MIN, POOL_MAX).unwrap();
let pool_opts = PoolOpts::default()
.with_constraints(constraints)
.with_inactive_connection_ttl(INACTIVE_CONNECTION_TTL)
.with_ttl_check_interval(TTL_CHECK_INTERVAL);
let pool = Pool::new(get_opts().pool_opts(pool_opts));
let pool_clone = pool.clone();
let conns = (0..POOL_MAX).map(|_| pool.get_conn()).collect::<Vec<_>>();
let conns = try_join_all(conns).await?;
assert_eq!(ex_field!(pool_clone, exist), POOL_MAX);
drop(conns);
sleep(Duration::from_millis(100)).await;
assert_eq!(ex_field!(pool_clone, available).len(), POOL_MAX);
sleep(TTL_CHECK_INTERVAL).await;
sleep(Duration::from_millis(500)).await;
assert_eq!(ex_field!(pool_clone, available).len(), POOL_MIN);
Ok(())
}
#[tokio::test]
async fn aa_should_hold_bounds2() -> super::Result<()> {
use std::cmp::min;
const POOL_MIN: usize = 5;
const POOL_MAX: usize = 10;
let constraints = PoolConstraints::new(POOL_MIN, POOL_MAX).unwrap();
let pool_opts = PoolOpts::default().with_constraints(constraints);
let pool = Pool::new(get_opts().pool_opts(pool_opts));
let pool_clone = pool.clone();
let conns = (0..POOL_MAX).map(|_| pool.get_conn()).collect::<Vec<_>>();
let mut conns = try_join_all(conns).await?;
assert_eq!(ex_field!(pool_clone, exist), POOL_MAX);
while !conns.is_empty() {
let _ = conns.pop();
sleep(Duration::from_millis(50)).await;
let dropped = POOL_MAX - conns.len();
let idle = min(dropped, POOL_MIN);
let expected = conns.len() + idle;
let have = ex_field!(pool_clone, exist);
assert_eq!(have, expected);
}
pool.disconnect().await?;
Ok(())
}
#[tokio::test]
async fn should_hold_bounds1() -> super::Result<()> {
let constraints = PoolConstraints::new(1, 2).unwrap();
let opts = get_opts().pool_opts(PoolOpts::default().with_constraints(constraints));
let pool = Pool::new(opts);
let pool_clone = pool.clone();
let (conn1, conn2) = try_join!(pool.get_conn(), pool.get_conn()).unwrap();
assert_eq!(conn_ex_field!(conn1, exist), 2);
assert_eq!(conn_ex_field!(conn1, available).len(), 0);
drop(conn1);
drop(conn2);
let conn1 = pool_clone.get_conn().await?;
assert_eq!(conn_ex_field!(conn1, available).len(), 0);
drop(conn1);
assert!(ex_field!(pool, available).len() <= 1);
pool.disconnect().await?;
Ok(())
}
#[tokio::test]
async fn should_hold_bounds_on_error() -> super::Result<()> {
let pool = Pool::new("mysql://255.255.255.255");
assert!(try_join!(pool.get_conn(), pool.get_conn()).is_err());
assert_eq!(ex_field!(pool, exist), 0);
Ok(())
}
#[tokio::test]
async fn zz_should_check_wait_timeout_on_get_conn() -> super::Result<()> {
let pool = Pool::new(get_opts());
let mut conn = pool.get_conn().await?;
let wait_timeout_orig: Option<usize> = conn.query_first("SELECT @@wait_timeout").await?;
conn.query_drop("SET GLOBAL wait_timeout = 3").await?;
conn.disconnect().await?;
let mut conn = pool.get_conn().await?;
let wait_timeout: Option<usize> = conn.query_first("SELECT @@wait_timeout").await?;
let id1: Option<usize> = conn.query_first("SELECT CONNECTION_ID()").await?;
drop(conn);
assert_eq!(wait_timeout, Some(3));
assert_eq!(ex_field!(pool, exist), 1);
sleep(Duration::from_secs(6)).await;
let mut conn = pool.get_conn().await?;
let id2: Option<usize> = conn.query_first("SELECT CONNECTION_ID()").await?;
assert_eq!(ex_field!(pool, exist), 1);
assert_ne!(id1, id2);
conn.exec_drop("SET GLOBAL wait_timeout = ?", (wait_timeout_orig,))
.await?;
drop(conn);
pool.disconnect().await?;
Ok(())
}
#[tokio::test]
async fn droptest() -> super::Result<()> {
let pool = Pool::new(get_opts());
let conns = try_join_all((0..10).map(|_| pool.get_conn()))
.await
.unwrap();
drop(conns);
drop(pool);
let pool = Pool::new(get_opts());
let conns = try_join_all((0..10).map(|_| pool.get_conn()))
.await
.unwrap();
drop(pool);
drop(conns);
Ok(())
}
#[test]
fn drop_impl_for_conn_should_not_panic_within_unwind() {
use tokio::runtime;
const PANIC_MESSAGE: &str = "ORIGINAL_PANIC";
let result = std::panic::catch_unwind(|| {
runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(async {
let pool = Pool::new(get_opts());
let _conn = pool.get_conn().await.unwrap();
std::panic::panic_any(PANIC_MESSAGE);
});
});
assert_eq!(
*result.unwrap_err().downcast::<&str>().unwrap(),
"ORIGINAL_PANIC",
);
}
#[test]
fn should_not_panic_on_unclean_shutdown() {
for _ in 0..10 {
let rt = tokio::runtime::Runtime::new().unwrap();
let (tx, rx) = tokio::sync::oneshot::channel();
rt.block_on(async move {
let pool = Pool::new(get_opts());
let mut c = pool.get_conn().await.unwrap();
tokio::spawn(async move {
let _ = rx.await;
let _ = c.query_drop("SELECT 1").await;
});
});
drop(rt);
let _ = tx.send(());
}
}
#[test]
fn should_perform_clean_shutdown() {
for _ in 0..10 {
let rt = tokio::runtime::Runtime::new().unwrap();
let (tx, rx) = tokio::sync::oneshot::channel();
let jh = rt.spawn(async move {
let pool = Pool::new(get_opts());
let mut c = pool.get_conn().await.unwrap();
tokio::spawn(async move {
let _ = rx.await;
let _ = c.query_drop("SELECT 1").await;
});
let _ = pool.disconnect().await;
});
let _ = tx.send(());
rt.block_on(jh).unwrap();
}
}
#[tokio::test]
async fn issue_126_should_cleanup_errors_in_multiresult_sets() -> super::Result<()> {
let pool_constraints = PoolConstraints::new(0, 1).unwrap();
let pool_opts = PoolOpts::default().with_constraints(pool_constraints);
let pool = Pool::new(get_opts().pool_opts(pool_opts));
for _ in 0u8..100 {
pool.get_conn()
.await?
.query_iter("DO '42'; BLABLA;")
.await?;
}
Ok(())
}
#[tokio::test]
async fn should_ignore_non_fatal_errors_while_returning_to_a_pool() -> super::Result<()> {
let pool_constraints = PoolConstraints::new(1, 1).unwrap();
let pool_opts = PoolOpts::default().with_constraints(pool_constraints);
let pool = Pool::new(get_opts().pool_opts(pool_opts));
let id = pool.get_conn().await?.id();
for _ in 0u8..10 {
let mut conn = pool.get_conn().await?;
conn.query_iter("DO '42'; BLABLA;").await?;
assert_eq!(id, conn.id());
}
Ok(())
}
#[tokio::test]
async fn should_work_if_pooled_connection_operation_is_cancelled() -> super::Result<()> {
let pool = Pool::new(get_opts());
join_all((0..10).map(|_| pool.get_conn())).await;
async fn op(pool: &Pool) {
let _: Option<Row> = pool
.get_conn()
.await
.unwrap()
.exec_first("SELECT ?, ?", (42, "foo"))
.await
.unwrap();
}
let mut max_delay = 0_u128;
for _ in 0..10_usize {
let start = std::time::Instant::now();
op(&pool).await;
max_delay = std::cmp::max(max_delay, start.elapsed().as_micros());
}
for _ in 0_usize..128 {
let fut = select_all((0_usize..5).map(|_| op(&pool).boxed()));
let delay_micros = rand::random::<u128>() % max_delay;
select(
sleep(Duration::from_micros(delay_micros as u64)).boxed(),
fut,
)
.await;
sleep(Duration::from_millis(100)).await;
}
Ok(())
}
#[cfg(feature = "nightly")]
mod bench {
use futures_util::future::{FutureExt, TryFutureExt};
use tokio::runtime::Runtime;
use crate::{prelude::Queryable, test_misc::get_opts, Pool, PoolConstraints, PoolOpts};
use std::time::Duration;
#[bench]
fn get_conn(bencher: &mut test::Bencher) {
let mut runtime = Runtime::new().unwrap();
let pool = Pool::new(get_opts());
bencher.iter(|| {
let fut = pool
.get_conn()
.and_then(|mut conn| async { conn.ping().await.map(|_| conn) });
runtime.block_on(fut).unwrap();
});
runtime.block_on(pool.disconnect()).unwrap();
}
#[bench]
fn new_conn_on_pool_soft_boundary(bencher: &mut test::Bencher) {
let mut runtime = Runtime::new().unwrap();
let pool_constraints = PoolConstraints::new(0, 1).unwrap();
let pool_opts = PoolOpts::default()
.with_constraints(pool_constraints)
.with_inactive_connection_ttl(Duration::from_secs(1));
let pool = Pool::new(get_opts().pool_opts(pool_opts));
bencher.iter(|| {
let fut = pool.get_conn().map(drop);
runtime.block_on(fut);
});
runtime.block_on(pool.disconnect()).unwrap();
}
}
}