fast_pool 1.0.4

The Fast Pool based on channel
Documentation
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
833
834
835
836
837
838
839
840
use fast_pool::{Manager, Pool};
use std::fmt::Display;
use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;

#[derive(Debug)]
pub struct TestManager {}

impl TestManager {
    pub fn new() -> TestManager {
        TestManager {}
    }
    pub fn hello(&self) {
        println!("hello")
    }
}

#[derive(Debug, Clone)]
pub struct TestConnection {
    pub inner: String,
}

impl TestConnection {
    pub fn new() -> TestConnection {
        println!("new Connection");
        TestConnection {
            inner: "".to_string(),
        }
    }
}

impl Display for TestConnection {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.inner)
    }
}
impl Deref for TestConnection {
    type Target = String;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl DerefMut for TestConnection {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

impl Drop for TestConnection {
    fn drop(&mut self) {
        println!("drop Connection");
    }
}

impl Manager for TestManager {
    type Connection = TestConnection;
    type Error = String;

    async fn connect(&self) -> Result<Self::Connection, Self::Error> {
        Ok(TestConnection::new())
    }

    async fn check(&self, conn: &mut Self::Connection) -> Result<(), Self::Error> {
        if conn.inner != "" {
            return Err(Self::Error::from(&conn.to_string()));
        }
        Ok(())
    }
}

#[tokio::test]
async fn test_debug() {
    let p = Pool::new(TestManager {});
    println!("{:?}", p);
}

#[tokio::test]
async fn test_clone() {
    let p = Pool::new(TestManager {});
    let p2 = p.clone();
    assert_eq!(p.state(), p2.state());
}

// --nocapture
#[tokio::test]
async fn test_pool_get() {
    let p = Pool::new(TestManager {});
    p.set_max_open(10);
    let mut arr = vec![];
    for i in 0..10 {
        let v = p.get().await.unwrap();
        println!("{},{}", i, v.deref());
        arr.push(v);
    }
}

#[tokio::test]
async fn test_pool_get2() {
    let p = Pool::new(TestManager {});
    p.set_max_open(10);
    for i in 0..3 {
        let v = p.get().await.unwrap();
        println!("{},{}", i, v.deref().inner.as_str());
    }
    assert_eq!(p.state().idle, 3);
}

#[tokio::test]
async fn test_pool_get_timeout() {
    let p = Pool::new(TestManager {});
    p.set_max_open(10);
    let mut arr = vec![];
    for i in 0..10 {
        let v = p.get().await.unwrap();
        println!("{},{}", i, v.deref());
        arr.push(v);
    }
    assert_eq!(
        p.get_timeout(Some(Duration::from_secs(0))).await.is_err(),
        true
    );
}

#[tokio::test]
async fn test_pool_check() {
    let p = Pool::new(TestManager {});
    p.set_max_open(10);
    let mut v = p.get().await.unwrap();
    *v.inner.as_mut().unwrap() = TestConnection {
        inner: "error".to_string(),
    };
    for _i in 0..10 {
        let v = p.get().await.unwrap();
        assert_eq!(v.deref().inner == "error", false);
    }
}

#[tokio::test]
async fn test_pool_resize() {
    let p = Pool::new(TestManager {});
    p.set_max_open(10);
    let mut arr = vec![];
    for i in 0..10 {
        let v = p.get().await.unwrap();
        println!("{},{}", i, v.deref());
        arr.push(v);
    }
    assert_eq!(
        p.get_timeout(Some(Duration::from_secs(0))).await.is_err(),
        true
    );
    p.set_max_open(11);
    assert_eq!(
        p.get_timeout(Some(Duration::from_secs(0))).await.is_err(),
        false
    );
    arr.push(p.get().await.unwrap());
    assert_eq!(
        p.get_timeout(Some(Duration::from_secs(0))).await.is_err(),
        true
    );
}

#[tokio::test]
async fn test_pool_resize2() {
    let p = Pool::new(TestManager {});
    p.set_max_open(2);
    let mut arr = vec![];
    for _i in 0..2 {
        let v = p.get().await.unwrap();
        arr.push(v);
    }
    p.set_max_open(1);
    drop(arr);
    println!("{:?}", p.state());
    assert_eq!(
        p.get_timeout(Some(Duration::from_secs(0))).await.is_err(),
        false
    );
}

#[tokio::test]
async fn test_concurrent_access() {
    let p = Pool::new(TestManager {});
    p.set_max_open(10);
    let mut handles = vec![];
    for _ in 0..10 {
        let pool = p.clone();
        let handle = tokio::spawn(async move {
            let _ = pool.get().await.unwrap();
        });
        handles.push(handle);
    }
    for handle in handles {
        handle.await.unwrap();
    }
    assert_eq!(p.state().connections, 10);
}

#[tokio::test]
async fn test_invalid_connection() {
    let p = Pool::new(TestManager {});
    p.set_max_open(1);

    let mut conn = p.get().await.unwrap();
    //conn timeout
    *conn.inner.as_mut().unwrap() = TestConnection {
        inner: "error".to_string(),
    };
    drop(conn);
    println!("pool state: {}", p.state());
    // Attempt to get a new connection, should not be the invalid one
    let new_conn = p.get().await.unwrap();
    assert_ne!(new_conn.deref().inner, "error".to_string());
}

#[tokio::test]
async fn test_connection_lifetime() {
    let p = Pool::new(TestManager {});
    p.set_max_open(10);

    let conn = p.get().await.unwrap();
    // Perform operations using the connection
    // ...

    drop(conn); // Drop the connection

    // Ensure dropped connection is not in use
    assert_eq!(p.state().in_use, 0);

    // Acquire a new connection
    let new_conn = p.get().await.unwrap();
    assert_ne!(new_conn.deref().inner, "error".to_string());
}

#[tokio::test]
async fn test_boundary_conditions() {
    let p = Pool::new(TestManager {});
    p.set_max_open(2);

    // Acquire connections until pool is full
    let conn_1 = p.get().await.unwrap();
    let _conn_2 = p.get().await.unwrap();
    println!("{}", p.state());
    assert_eq!(p.state().in_use, 2);

    // Attempt to acquire another connection (pool is full)
    assert!(p.get_timeout(Some(Duration::from_secs(0))).await.is_err());

    // Release one connection, pool is no longer full
    drop(conn_1);
    assert_eq!(p.state().in_use, 1);

    // Acquire another connection (pool has space)
    let _conn_3 = p.get().await.unwrap();
    assert_eq!(p.state().in_use, 2);

    // Increase pool size
    p.set_max_open(3);
    // Acquire another connection after increasing pool size
    let _conn_4 = p.get().await.unwrap();
    assert_eq!(p.state().in_use, 3);
}

#[tokio::test]
async fn test_pool_wait() {
    let p = Pool::new(TestManager {});
    p.set_max_open(1);
    let v = p.get().await.unwrap();
    let p1 = p.clone();
    tokio::spawn(async move {
        p1.get().await.unwrap();
        drop(p1);
    });
    let p1 = p.clone();
    tokio::spawn(async move {
        p1.get().await.unwrap();
        drop(p1);
    });
    tokio::time::sleep(Duration::from_secs(1)).await;
    println!("{:?}", p.state());
    assert_eq!(p.state().waits, 2);
    drop(v);
}

#[tokio::test]
async fn test_high_concurrency_with_timeout() {
    // Create a pool with small connection limit
    let p = Pool::new(TestManager {});
    p.set_max_open(5);

    // Counter for successful connection acquisition
    let success_count = Arc::new(AtomicUsize::new(0));
    // Counter for timeout events
    let timeout_count = Arc::new(AtomicUsize::new(0));

    // Create many concurrent tasks, exceeding pool capacity
    let mut handles = vec![];
    let task_count = 50;

    for _ in 0..task_count {
        let pool = p.clone();
        let success = success_count.clone();
        let timeout = timeout_count.clone();

        let handle = tokio::spawn(async move {
            // Use very short timeout to simulate high pressure
            match pool.get_timeout(Some(Duration::from_millis(50))).await {
                Ok(conn) => {
                    // Successfully got connection
                    success.fetch_add(1, Ordering::SeqCst);
                    // Simulate brief connection usage
                    tokio::time::sleep(Duration::from_millis(20)).await;
                    // Return connection to pool
                    drop(conn);
                }
                Err(_) => {
                    // Connection acquisition timed out
                    timeout.fetch_add(1, Ordering::SeqCst);
                }
            }
        });
        handles.push(handle);
    }

    // Wait for all tasks to complete
    for handle in handles {
        handle.await.unwrap();
    }

    // Verify pool state
    println!("Final pool state: {:?}", p.state());
    println!(
        "Successful connections: {}",
        success_count.load(Ordering::SeqCst)
    );
    println!("Timeouts: {}", timeout_count.load(Ordering::SeqCst));

    // Verify success + timeout equals total tasks
    assert_eq!(
        success_count.load(Ordering::SeqCst) + timeout_count.load(Ordering::SeqCst),
        task_count
    );

    // Verify pool connections did not exceed limit
    assert!(p.state().connections <= p.state().max_open);

    // Wait for connections to return to pool
    tokio::time::sleep(Duration::from_millis(100)).await;

    // Pool should be in idle state, all connections in idle queue
    assert_eq!(p.state().in_use, 0);
    assert!(p.state().idle <= p.state().max_open);
}

#[tokio::test]
async fn test_concurrent_create_connection() {
    // Create a connection pool with specific connection limit
    let p = Pool::new(TestManager {});
    let max_connections = 10;
    p.set_max_open(max_connections);

    // Clear the connection pool
    p.set_max_open(0);
    p.set_max_open(max_connections);

    // Number of concurrent tasks, several times the pool limit
    let tasks = 30;
    let mut handles = vec![];

    // Concurrently start multiple tasks all trying to get connections
    for i in 0..tasks {
        let pool = p.clone();
        let handle = tokio::spawn(async move {
            let result = pool.get().await;
            println!("Task {} get connection: {}", i, result.is_ok());
            result
        });
        handles.push(handle);
    }

    // Collect results
    let mut success_count = 0;
    for handle in handles {
        if handle.await.unwrap().is_ok() {
            success_count += 1;
        }
    }

    // Wait for connections to return to pool
    tokio::time::sleep(Duration::from_millis(100)).await;

    println!("Pool state: {:?}", p.state());
    println!("Successfully created connections: {}", success_count);

    // Verify pool did not exceed max connections
    assert!(p.state().connections <= max_connections);

    // All active connections should be returned to pool
    assert_eq!(p.state().in_use, 0);

    // Verify idle connections don't exceed max
    assert!(p.state().idle <= max_connections);
}

#[tokio::test]
async fn test_high_concurrency_long_connections() {
    // Create a connection pool with a specific limit
    let p = Pool::new(TestManager {});
    let max_connections = 20; // Maximum number of connections allowed
    p.set_max_open(max_connections);

    // Clear the connection pool
    p.set_max_open(0);
    p.set_max_open(max_connections);

    // Simulate a high number of concurrent requests
    let task_count = 200; // Reduced for faster test execution
    let connection_duration = Duration::from_secs(3); // Each connection lives for 3 seconds

    let success_count = Arc::new(AtomicUsize::new(0));
    let timeout_count = Arc::new(AtomicUsize::new(0));
    let in_progress = Arc::new(AtomicUsize::new(0));
    let max_in_progress = Arc::new(AtomicUsize::new(0));

    // Track the maximum number of concurrent connections
    let update_max = |current: usize, max_tracker: &Arc<AtomicUsize>| {
        let mut current_max = max_tracker.load(Ordering::Relaxed);
        while current > current_max {
            match max_tracker.compare_exchange_weak(
                current_max,
                current,
                Ordering::SeqCst,
                Ordering::Relaxed,
            ) {
                Ok(_) => break,
                Err(val) => current_max = val,
            }
        }
    };

    println!("Starting high concurrency test with long-lived connections");
    println!(
        "Max connections: {}, Tasks: {}, Connection duration: {:?}",
        max_connections, task_count, connection_duration
    );

    // Create multiple concurrent tasks
    let mut handles = vec![];
    for id in 0..task_count {
        let pool = p.clone();
        let success = success_count.clone();
        let timeout = timeout_count.clone();
        let in_progress_counter = in_progress.clone();
        let max_in_progress_counter = max_in_progress.clone();

        let handle = tokio::spawn(async move {
            // Use timeout to prevent indefinite waiting
            match pool.get_timeout(Some(Duration::from_secs(1))).await {
                Ok(conn) => {
                    // Successfully got a connection
                    success.fetch_add(1, Ordering::SeqCst);

                    // Track in-progress connections
                    let current = in_progress_counter.fetch_add(1, Ordering::SeqCst) + 1;
                    update_max(current, &max_in_progress_counter);

                    println!("Task {} got connection, in-progress: {}", id, current);

                    // Simulate some work with the connection
                    tokio::time::sleep(connection_duration).await;

                    // Decrease in-progress counter
                    let remaining = in_progress_counter.fetch_sub(1, Ordering::SeqCst) - 1;
                    println!("Task {} completed, in-progress: {}", id, remaining);

                    // Connection is automatically returned to the pool when dropped
                    drop(conn);
                }
                Err(_) => {
                    // Timed out waiting for a connection
                    timeout.fetch_add(1, Ordering::SeqCst);
                    println!("Task {} timed out waiting for connection", id);
                }
            }
        });

        handles.push(handle);

        // Small delay to simulate staggered requests
        tokio::time::sleep(Duration::from_millis(20)).await;
    }

    // Periodically print pool stats while waiting
    let p_status = p.clone();
    let in_progress_status = in_progress.clone();
    let status_handle = tokio::spawn(async move {
        for _ in 0..20 {
            tokio::time::sleep(Duration::from_secs(1)).await;
            println!(
                "Pool status: {:?}, In-progress: {}",
                p_status.state(),
                in_progress_status.load(Ordering::SeqCst)
            );
        }
    });

    // Wait for all tasks to complete
    for handle in handles {
        handle.await.unwrap();
    }

    // Wait for status reporting
    let _ = status_handle.await;

    // Print final statistics
    println!("Connection pool stats:");
    println!("  Max connections setting: {}", max_connections);
    println!("  Total tasks: {}", task_count);
    println!(
        "  Successful connections: {}",
        success_count.load(Ordering::SeqCst)
    );
    println!(
        "  Connection timeouts: {}",
        timeout_count.load(Ordering::SeqCst)
    );
    println!(
        "  Max concurrent connections: {}",
        max_in_progress.load(Ordering::SeqCst)
    );
    println!("  Final pool state: {:?}", p.state());

    // Verify pool didn't exceed limits
    assert!(max_in_progress.load(Ordering::SeqCst) <= max_connections as usize);
    assert!(p.state().connections <= max_connections);

    // Wait for connections to be fully returned to the pool
    tokio::time::sleep(Duration::from_millis(200)).await;

    // Verify all connections are idle now
    assert_eq!(p.state().in_use, 0);
}

#[tokio::test]
async fn test_concurrent_create_connection_less_for_max_open() {
    let p = Pool::new(TestManager {});
    p.set_max_open(10);
    for _ in 0..1000 {
        let p1 = p.clone();
        tokio::spawn(async move {
            loop {
                let result = p1.get().await.unwrap();
                tokio::time::sleep(Duration::from_secs(1)).await;
                drop(result);
            }
        });
    }
    for _ in 0..5 {
        let state = p.state();
        println!("{}", state);
        assert_eq!(state.connections <= state.max_open, true);
        assert_eq!(state.in_use <= state.max_open, true);
        assert_eq!(state.idle <= state.max_open, true);
        tokio::time::sleep(Duration::from_secs(1)).await;
    }
}

#[tokio::test]
async fn test_change_max_open() {
    let p = Pool::new(TestManager {});
    p.set_max_open(4);

    let c1 = p.get().await.unwrap();
    let c2 = p.get().await.unwrap();
    let c3 = p.get().await.unwrap();
    let c4 = p.get().await.unwrap();

    p.set_max_open(2);

    drop(c1);
    drop(c2);
    drop(c3);
    drop(c4);

    println!("{}", p.state());
    println!("len {}", p.idle_send.len());
}

#[tokio::test]
async fn test_change_max_open2() {
    let p = Pool::new(TestManager {});
    p.set_max_open(4);

    let c1 = p.get().await.unwrap();
    let c2 = p.get().await.unwrap();
    let c3 = p.get().await.unwrap();
    let c4 = p.get().await.unwrap();

    drop(c1);
    drop(c2);
    drop(c3);
    drop(c4);

    p.set_max_open(2);

    println!("{}", p.state());
    println!("len {}", p.idle_send.len());
}

#[tokio::test]
async fn test_tokio_cancel() {
    let p = Pool::new(TestManager {});
    p.set_max_open(2);
    let p1 = p.clone();
    let task = tokio::spawn(async move {
        let c1 = p1.get().await.unwrap();
        let c2 = p1.get().await.unwrap();
        tokio::time::sleep(Duration::from_secs(10)).await;
        drop(c1);
        drop(c2);
    });
    tokio::time::sleep(Duration::from_secs(1)).await;
    task.abort();
    tokio::time::sleep(Duration::from_secs(1)).await;
    println!("{}", p.state());
    assert_eq!(p.state().in_use, 0);
}

#[tokio::test]
async fn test_tokio_panic() {
    let p = Pool::new(TestManager {});
    p.set_max_open(2);
    let p1 = p.clone();
    let _task = tokio::spawn(async move {
        let _c1 = p1.get().await.unwrap();
        let _c2 = p1.get().await.unwrap();
        panic!("test_tokio_panic");
    });
    tokio::time::sleep(Duration::from_secs(3)).await;
    println!("{}", p.state());
    assert_eq!(p.state().in_use, 0);
}

#[tokio::test]
async fn test_timeout_zero() {
    let p = Pool::new(TestManager {});
    p.set_max_open(1);
    p.set_timeout_check(None);
    let v = p.get().await.unwrap();
    println!("{:?}", v.inner);
}

#[tokio::test]
async fn test_pool_drop() {
    let p = Pool::new(TestManager {});
    p.set_max_open(1);
    let v = p.get().await.unwrap();
    println!("{:?}", v.inner);
    drop(v);
    drop(p);
}

#[tokio::test]
async fn test_connection_check_success_path() {
    #[derive(Debug, Default)]
    struct CheckManager {
        connection_count: std::sync::atomic::AtomicU64,
    }

    #[derive(Debug)]
    struct CheckConnection {
        valid: bool,
    }

    impl Manager for CheckManager {
        type Connection = CheckConnection;
        type Error = String;

        async fn connect(&self) -> Result<Self::Connection, Self::Error> {
            self.connection_count
                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            Ok(CheckConnection { valid: true })
        }

        async fn check(&self, conn: &mut Self::Connection) -> Result<(), Self::Error> {
            // successcheck,this Ok(_) => {  (pool.rs line 123)
            if conn.valid {
                Ok(())
            } else {
                Err("Invalid connection".to_string())
            }
        }
    }

    let manager = CheckManager::default();
    let pool = Pool::new(manager);

    // get connection,thiswillpasssuccesscheck
    let _guard = pool.get().await.unwrap();
    // when guard bycreate,passconnectioncheck, pool.rs line 123  Ok
}

#[tokio::test]
async fn test_downcast() {
    let p = Pool::new(TestManager {});
    p.set_max_open(1);
    let manager = p.downcast_manager::<TestManager>().unwrap();
    manager.hello();
}


#[tokio::test]
async fn test_check_timeout_should_reduce_connections() {
    use std::sync::atomic::AtomicUsize;
    use std::sync::Arc;

    #[derive(Debug)]
    struct FailCheckManager {
        connect_count: Arc<AtomicUsize>,
        check_count: Arc<AtomicUsize>,
    }

    struct TestConnection;

    impl Manager for FailCheckManager {
        type Connection = TestConnection;
        type Error = String;

        async fn connect(&self) -> Result<Self::Connection, Self::Error> {
            self.connect_count.fetch_add(1, Ordering::SeqCst);
            Ok(TestConnection)
        }

        async fn check(&self, _conn: &mut Self::Connection) -> Result<(), Self::Error> {
            self.check_count.fetch_add(1, Ordering::SeqCst);
            Err("check failed".to_string()) // always returns error
        }
    }

    let connect_count = Arc::new(AtomicUsize::new(0));
    let check_count = Arc::new(AtomicUsize::new(0));

    let manager = FailCheckManager {
        connect_count: connect_count.clone(),
        check_count: check_count.clone(),
    };
    let pool = Pool::new(manager);
    pool.set_max_open(2);

    println!("Pool state: {:?}", pool.state());

    let result = pool.get().await;
    println!("First get result: {:?}", result.is_ok());
    println!("Pool state: {:?}", pool.state());


    let result2 = pool.get_timeout(Some(Duration::from_secs(1))).await;
    println!("Second get result: {:?}", result2.is_ok());
    println!("Pool state: {:?}", pool.state());

    assert_eq!(pool.state().connections, 0, "connections should be 0 after failed checks");
}

#[tokio::test]
async fn test_multiple_check_timeouts_should_not_deadlock() {
    // Ensures multiple concurrent requests do not deadlock after check timeouts

    use std::sync::atomic::AtomicUsize;
    use std::sync::Arc;

    #[derive(Debug)]
    struct SlowCheckManager {
        connect_count: Arc<AtomicUsize>,
    }

    struct SlowConnection;

    impl Manager for SlowCheckManager {
        type Connection = SlowConnection;
        type Error = String;

        async fn connect(&self) -> Result<Self::Connection, Self::Error> {
            self.connect_count.fetch_add(1, Ordering::SeqCst);
            Ok(SlowConnection)
        }

        async fn check(&self, _conn: &mut Self::Connection) -> Result<(), Self::Error> {
            // Simulates database being completely unresponsive
            tokio::time::sleep(Duration::from_secs(3600)).await;
            Ok(())
        }
    }

    let connect_count = Arc::new(AtomicUsize::new(0));

    let manager = SlowCheckManager {
        connect_count: connect_count.clone(),
    };
    let pool = Pool::new(manager);
    pool.set_max_open(3);
    pool.set_timeout_check(Some(Duration::from_millis(100)));

    let mut handles = vec![];
    let conn_count = connect_count.clone();

    // Spawn 5 concurrent requests (exceeds max_open=3)
    for i in 0..5 {
        let pool = pool.clone();
        let handle = tokio::spawn(async move {
            let start = std::time::Instant::now();
            let result = pool.get_timeout(Some(Duration::from_secs(2))).await;
            let elapsed = start.elapsed();
            println!("Request {} took {:?}, result: {:?}", i, elapsed, result.is_ok());
            (i, result)
        });
        handles.push(handle);
    }

    // Wait for all requests to complete
    let mut results = vec![];
    for handle in handles {
        results.push(handle.await.unwrap());
    }

    let total_connects = conn_count.load(Ordering::SeqCst);
    println!("Total connections created: {}", total_connects);
    println!("Final pool state: {:?}", pool.state());

    // Verify: all requests should complete within timeout (no deadlock)
    // If the bug exists, some requests would block forever
    assert_eq!(results.len(), 5);

    // connections should not exceed max_open
    assert!(pool.state().connections <= pool.state().max_open);
}