mockforge-core 0.3.115

Shared logic for MockForge - routing, validation, latency, proxy
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
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::{RwLock, Semaphore};
use tracing::{debug, warn};

/// Connection pool configuration
#[derive(Debug, Clone)]
pub struct PoolConfig {
    /// Maximum number of connections
    pub max_connections: usize,
    /// Minimum number of idle connections to maintain
    pub min_idle: usize,
    /// Maximum idle time before connection is closed
    pub max_idle_time: Duration,
    /// Connection timeout
    pub connection_timeout: Duration,
    /// Enable connection health checks
    pub health_check_enabled: bool,
    /// Health check interval
    pub health_check_interval: Duration,
}

impl Default for PoolConfig {
    fn default() -> Self {
        Self {
            max_connections: 100,
            min_idle: 10,
            max_idle_time: Duration::from_secs(600), // 10 minutes
            connection_timeout: Duration::from_secs(30),
            health_check_enabled: true,
            health_check_interval: Duration::from_secs(60),
        }
    }
}

/// Connection wrapper with metadata
pub struct PooledConnection<T> {
    inner: T,
    created_at: Instant,
    last_used: Instant,
}

impl<T> PooledConnection<T> {
    /// Creates a new pooled connection wrapper
    pub fn new(connection: T) -> Self {
        let now = Instant::now();
        Self {
            inner: connection,
            created_at: now,
            last_used: now,
        }
    }

    /// Gets a reference to the underlying connection
    pub fn get(&self) -> &T {
        &self.inner
    }

    /// Gets a mutable reference to the underlying connection and updates last used time
    pub fn get_mut(&mut self) -> &mut T {
        self.last_used = Instant::now();
        &mut self.inner
    }

    /// Checks if the connection is stale based on idle time
    pub fn is_stale(&self, max_idle_time: Duration) -> bool {
        self.last_used.elapsed() > max_idle_time
    }

    /// Returns the age of the connection since creation
    pub fn age(&self) -> Duration {
        self.created_at.elapsed()
    }
}

/// Generic connection pool
pub struct ConnectionPool<T> {
    config: PoolConfig,
    available: Arc<RwLock<Vec<PooledConnection<T>>>>,
    semaphore: Arc<Semaphore>,
    metrics: Arc<RwLock<PoolMetrics>>,
}

/// Metrics for connection pool usage and health
#[derive(Debug, Default, Clone)]
pub struct PoolMetrics {
    /// Number of currently active connections
    pub active_connections: usize,
    /// Number of idle connections available
    pub idle_connections: usize,
    /// Total number of connection acquisitions
    pub total_acquired: u64,
    /// Total number of connection releases
    pub total_released: u64,
    /// Total number of connections created
    pub total_created: u64,
    /// Total number of connections closed
    pub total_closed: u64,
    /// Number of acquire timeouts
    pub acquire_timeouts: u64,
    /// Number of health check failures
    pub health_check_failures: u64,
}

impl<T> ConnectionPool<T>
where
    T: Send + 'static,
{
    /// Creates a new connection pool with the given configuration
    pub fn new(config: PoolConfig) -> Self {
        Self {
            semaphore: Arc::new(Semaphore::new(config.max_connections)),
            available: Arc::new(RwLock::new(Vec::with_capacity(config.max_connections))),
            metrics: Arc::new(RwLock::new(PoolMetrics::default())),
            config,
        }
    }

    /// Acquire a connection from the pool
    pub async fn acquire<F, Fut>(&self, create_fn: F) -> Result<PooledConnection<T>, PoolError>
    where
        F: FnOnce() -> Fut,
        Fut: std::future::Future<Output = Result<T, PoolError>>,
    {
        // Wait for available slot
        let permit = tokio::time::timeout(
            self.config.connection_timeout,
            self.semaphore.clone().acquire_owned(),
        )
        .await
        .map_err(|_| {
            debug!("Connection pool acquire timeout");
            PoolError::Timeout
        })?
        .map_err(|_| PoolError::Closed)?;

        // Try to get an existing connection
        let mut available = self.available.write().await;

        // Remove stale connections
        available.retain(|conn| !conn.is_stale(self.config.max_idle_time));

        let connection = if let Some(mut conn) = available.pop() {
            // Reuse existing connection
            conn.last_used = Instant::now();
            drop(available);

            let mut metrics = self.metrics.write().await;
            metrics.total_acquired += 1;
            metrics.active_connections += 1;
            metrics.idle_connections = metrics.idle_connections.saturating_sub(1);
            drop(metrics);

            debug!("Reusing pooled connection");
            conn
        } else {
            drop(available);

            // Create new connection
            let inner = create_fn().await?;
            let conn = PooledConnection::new(inner);

            let mut metrics = self.metrics.write().await;
            metrics.total_created += 1;
            metrics.total_acquired += 1;
            metrics.active_connections += 1;
            drop(metrics);

            debug!("Created new pooled connection");
            conn
        };

        // Permit will be returned when connection is released
        std::mem::forget(permit);

        Ok(connection)
    }

    /// Release a connection back to the pool
    pub async fn release(&self, connection: PooledConnection<T>) {
        let mut available = self.available.write().await;

        // Don't return to pool if we're above max idle or connection is stale
        if available.len() >= self.config.min_idle && connection.is_stale(self.config.max_idle_time)
        {
            drop(available);

            let mut metrics = self.metrics.write().await;
            metrics.total_closed += 1;
            metrics.active_connections = metrics.active_connections.saturating_sub(1);
            drop(metrics);

            self.semaphore.add_permits(1);
            debug!("Closed stale connection");
            return;
        }

        available.push(connection);
        drop(available);

        let mut metrics = self.metrics.write().await;
        metrics.total_released += 1;
        metrics.active_connections = metrics.active_connections.saturating_sub(1);
        metrics.idle_connections += 1;
        drop(metrics);

        self.semaphore.add_permits(1);
        debug!("Released connection to pool");
    }

    /// Get current pool metrics
    pub async fn metrics(&self) -> PoolMetrics {
        self.metrics.read().await.clone()
    }

    /// Get current pool size
    pub async fn size(&self) -> usize {
        self.available.read().await.len()
    }

    /// Run health checks on idle connections
    pub async fn health_check<F, Fut>(&self, check_fn: F)
    where
        F: Fn(&T) -> Fut,
        Fut: std::future::Future<Output = bool>,
    {
        if !self.config.health_check_enabled {
            return;
        }

        let mut available = self.available.write().await;
        let mut healthy = Vec::new();
        let mut failures = 0;

        for conn in available.drain(..) {
            if check_fn(conn.get()).await {
                healthy.push(conn);
            } else {
                failures += 1;
                warn!("Connection failed health check");
            }
        }

        *available = healthy;
        drop(available);

        if failures > 0 {
            let mut metrics = self.metrics.write().await;
            metrics.health_check_failures += failures;
            metrics.total_closed += failures;
            metrics.idle_connections = metrics.idle_connections.saturating_sub(failures as usize);
            drop(metrics);

            self.semaphore.add_permits(failures as usize);
        }
    }

    /// Maintain minimum idle connections
    pub async fn maintain_idle<F, Fut>(&self, create_fn: F)
    where
        F: Fn() -> Fut,
        Fut: std::future::Future<Output = Result<T, PoolError>>,
    {
        let current_idle = self.available.read().await.len();

        if current_idle < self.config.min_idle {
            let needed = self.config.min_idle - current_idle;

            for _ in 0..needed {
                if let Ok(permit) = self.semaphore.clone().try_acquire_owned() {
                    match create_fn().await {
                        Ok(conn) => {
                            let pooled = PooledConnection::new(conn);
                            self.available.write().await.push(pooled);

                            let mut metrics = self.metrics.write().await;
                            metrics.total_created += 1;
                            metrics.idle_connections += 1;

                            std::mem::forget(permit);
                        }
                        Err(e) => {
                            warn!("Failed to create idle connection: {:?}", e);
                            drop(permit);
                        }
                    }
                } else {
                    break;
                }
            }
        }
    }
}

/// Errors that can occur in connection pool operations
#[derive(Debug, thiserror::Error)]
pub enum PoolError {
    /// Connection acquisition timed out
    #[error("Connection pool timeout")]
    Timeout,

    /// Connection pool has been closed
    #[error("Connection pool closed")]
    Closed,

    /// Failed to create a new connection
    #[error("Failed to create connection: {0}")]
    CreateError(String),

    /// Error during connection operation
    #[error("Connection error: {0}")]
    ConnectionError(String),
}

/// HTTP client connection pool (example usage)
pub type HttpClientPool = ConnectionPool<reqwest::Client>;

impl HttpClientPool {
    /// Creates a new HTTP client pool with the given configuration
    pub fn new_http(config: PoolConfig) -> Self {
        Self::new(config)
    }

    /// Acquires an HTTP client from the pool
    pub async fn acquire_client(&self) -> Result<PooledConnection<reqwest::Client>, PoolError> {
        self.acquire(|| async {
            reqwest::Client::builder()
                .timeout(Duration::from_secs(30))
                .pool_max_idle_per_host(10)
                .build()
                .map_err(|e| PoolError::CreateError(e.to_string()))
        })
        .await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};

    // PoolConfig tests
    #[test]
    fn test_pool_config_default() {
        let config = PoolConfig::default();
        assert_eq!(config.max_connections, 100);
        assert_eq!(config.min_idle, 10);
        assert_eq!(config.max_idle_time, Duration::from_secs(600));
        assert_eq!(config.connection_timeout, Duration::from_secs(30));
        assert!(config.health_check_enabled);
        assert_eq!(config.health_check_interval, Duration::from_secs(60));
    }

    #[test]
    fn test_pool_config_clone() {
        let config = PoolConfig {
            max_connections: 50,
            min_idle: 5,
            ..Default::default()
        };
        let cloned = config.clone();
        assert_eq!(cloned.max_connections, config.max_connections);
        assert_eq!(cloned.min_idle, config.min_idle);
    }

    #[test]
    fn test_pool_config_debug() {
        let config = PoolConfig::default();
        let debug = format!("{:?}", config);
        assert!(debug.contains("PoolConfig"));
        assert!(debug.contains("max_connections"));
    }

    // PooledConnection tests
    #[test]
    fn test_pooled_connection_new() {
        let conn = PooledConnection::new(42u32);
        assert_eq!(*conn.get(), 42);
    }

    #[test]
    fn test_pooled_connection_get() {
        let conn = PooledConnection::new("test".to_string());
        assert_eq!(*conn.get(), "test");
    }

    #[test]
    fn test_pooled_connection_get_mut() {
        let mut conn = PooledConnection::new(vec![1, 2, 3]);
        conn.get_mut().push(4);
        assert_eq!(*conn.get(), vec![1, 2, 3, 4]);
    }

    #[test]
    fn test_pooled_connection_is_stale() {
        let conn = PooledConnection::new(42u32);
        // Just created, should not be stale
        assert!(!conn.is_stale(Duration::from_secs(1)));
        // With zero duration, should be stale immediately
        assert!(conn.is_stale(Duration::from_nanos(0)));
    }

    #[test]
    fn test_pooled_connection_age() {
        let conn = PooledConnection::new(42u32);
        let age = conn.age();
        // Should be very small (just created)
        assert!(age < Duration::from_secs(1));
    }

    // PoolMetrics tests
    #[test]
    fn test_pool_metrics_default() {
        let metrics = PoolMetrics::default();
        assert_eq!(metrics.active_connections, 0);
        assert_eq!(metrics.idle_connections, 0);
        assert_eq!(metrics.total_acquired, 0);
        assert_eq!(metrics.total_released, 0);
        assert_eq!(metrics.total_created, 0);
        assert_eq!(metrics.total_closed, 0);
        assert_eq!(metrics.acquire_timeouts, 0);
        assert_eq!(metrics.health_check_failures, 0);
    }

    #[test]
    fn test_pool_metrics_clone() {
        let metrics = PoolMetrics {
            total_acquired: 10,
            active_connections: 5,
            ..Default::default()
        };
        let cloned = metrics.clone();
        assert_eq!(cloned.total_acquired, 10);
        assert_eq!(cloned.active_connections, 5);
    }

    #[test]
    fn test_pool_metrics_debug() {
        let metrics = PoolMetrics::default();
        let debug = format!("{:?}", metrics);
        assert!(debug.contains("PoolMetrics"));
        assert!(debug.contains("active_connections"));
    }

    // PoolError tests
    #[test]
    fn test_pool_error_timeout() {
        let error = PoolError::Timeout;
        assert!(error.to_string().contains("timeout"));
    }

    #[test]
    fn test_pool_error_closed() {
        let error = PoolError::Closed;
        assert!(error.to_string().contains("closed"));
    }

    #[test]
    fn test_pool_error_create_error() {
        let error = PoolError::CreateError("connection failed".to_string());
        let msg = error.to_string();
        assert!(msg.contains("create connection"));
        assert!(msg.contains("connection failed"));
    }

    #[test]
    fn test_pool_error_connection_error() {
        let error = PoolError::ConnectionError("network issue".to_string());
        let msg = error.to_string();
        assert!(msg.contains("Connection error"));
        assert!(msg.contains("network issue"));
    }

    #[test]
    fn test_pool_error_debug() {
        let error = PoolError::Timeout;
        let debug = format!("{:?}", error);
        assert!(debug.contains("Timeout"));
    }

    // ConnectionPool tests
    #[tokio::test]
    async fn test_connection_pool() {
        let config = PoolConfig {
            max_connections: 5,
            min_idle: 2,
            ..Default::default()
        };

        let pool = ConnectionPool::<u32>::new(config);

        // Acquire connection
        let conn1 = pool.acquire(|| async { Ok(42) }).await.unwrap();

        assert_eq!(*conn1.get(), 42);

        // Release connection
        pool.release(conn1).await;

        // Verify metrics
        let metrics = pool.metrics().await;
        assert_eq!(metrics.total_created, 1);
        assert_eq!(metrics.total_acquired, 1);
        assert_eq!(metrics.total_released, 1);
    }

    #[tokio::test]
    async fn test_connection_pool_new() {
        let config = PoolConfig {
            max_connections: 10,
            min_idle: 2,
            ..Default::default()
        };
        let pool = ConnectionPool::<u32>::new(config);

        // Pool should start empty
        assert_eq!(pool.size().await, 0);
    }

    #[tokio::test]
    async fn test_connection_pool_acquire_creates_connection() {
        let config = PoolConfig::default();
        let pool = ConnectionPool::<String>::new(config);

        let conn = pool.acquire(|| async { Ok("test-connection".to_string()) }).await.unwrap();

        assert_eq!(*conn.get(), "test-connection");

        let metrics = pool.metrics().await;
        assert_eq!(metrics.total_created, 1);
        assert_eq!(metrics.total_acquired, 1);
    }

    #[tokio::test]
    async fn test_connection_pool_reuses_connection() {
        let config = PoolConfig {
            max_connections: 5,
            min_idle: 1,
            ..Default::default()
        };
        let pool = ConnectionPool::<u32>::new(config);
        let create_count = Arc::new(AtomicUsize::new(0));

        // First acquire - creates connection
        let create_count_clone = create_count.clone();
        let conn1 = pool
            .acquire(move || {
                let count = create_count_clone.clone();
                async move {
                    count.fetch_add(1, Ordering::SeqCst);
                    Ok(42u32)
                }
            })
            .await
            .unwrap();

        // Release it
        pool.release(conn1).await;

        // Second acquire - should reuse
        let create_count_clone = create_count.clone();
        let conn2 = pool
            .acquire(move || {
                let count = create_count_clone.clone();
                async move {
                    count.fetch_add(1, Ordering::SeqCst);
                    Ok(100u32)
                }
            })
            .await
            .unwrap();

        // Should still be the original connection (value 42), not a new one
        assert_eq!(*conn2.get(), 42);
        assert_eq!(create_count.load(Ordering::SeqCst), 1); // Only created once

        let metrics = pool.metrics().await;
        assert_eq!(metrics.total_created, 1);
        assert_eq!(metrics.total_acquired, 2);
    }

    #[tokio::test]
    async fn test_connection_pool_release() {
        let config = PoolConfig::default();
        let pool = ConnectionPool::<u32>::new(config);

        let conn = pool.acquire(|| async { Ok(42) }).await.unwrap();
        assert_eq!(pool.size().await, 0); // Connection in use, not in pool

        pool.release(conn).await;
        assert_eq!(pool.size().await, 1); // Connection returned to pool

        let metrics = pool.metrics().await;
        assert_eq!(metrics.total_released, 1);
        assert_eq!(metrics.idle_connections, 1);
    }

    #[tokio::test]
    async fn test_connection_pool_metrics() {
        let config = PoolConfig::default();
        let pool = ConnectionPool::<u32>::new(config);

        // Initial metrics
        let metrics = pool.metrics().await;
        assert_eq!(metrics.total_created, 0);

        // Acquire and release
        let conn = pool.acquire(|| async { Ok(1) }).await.unwrap();
        pool.release(conn).await;

        let metrics = pool.metrics().await;
        assert_eq!(metrics.total_created, 1);
        assert_eq!(metrics.total_acquired, 1);
        assert_eq!(metrics.total_released, 1);
    }

    #[tokio::test]
    async fn test_connection_pool_size() {
        let config = PoolConfig::default();
        let pool = ConnectionPool::<u32>::new(config);

        assert_eq!(pool.size().await, 0);

        let conn1 = pool.acquire(|| async { Ok(1) }).await.unwrap();
        let conn2 = pool.acquire(|| async { Ok(2) }).await.unwrap();

        // Connections in use, pool is empty
        assert_eq!(pool.size().await, 0);

        pool.release(conn1).await;
        assert_eq!(pool.size().await, 1);

        pool.release(conn2).await;
        assert_eq!(pool.size().await, 2);
    }

    #[tokio::test]
    async fn test_connection_pool_multiple_concurrent_acquires() {
        let config = PoolConfig {
            max_connections: 10,
            ..Default::default()
        };
        let pool = Arc::new(ConnectionPool::<u32>::new(config));

        let mut handles = vec![];
        for i in 0..5 {
            let pool_clone = pool.clone();
            let handle = tokio::spawn(async move {
                let conn = pool_clone.acquire(move || async move { Ok(i as u32) }).await.unwrap();
                // Simulate some work
                tokio::time::sleep(Duration::from_millis(10)).await;
                pool_clone.release(conn).await;
            });
            handles.push(handle);
        }

        for handle in handles {
            handle.await.unwrap();
        }

        let metrics = pool.metrics().await;
        assert_eq!(metrics.total_acquired, 5);
        assert_eq!(metrics.total_released, 5);
    }

    #[tokio::test]
    async fn test_connection_pool_acquire_error() {
        let config = PoolConfig::default();
        let pool = ConnectionPool::<u32>::new(config);

        let result = pool
            .acquire(|| async { Err(PoolError::CreateError("test error".to_string())) })
            .await;

        assert!(result.is_err());
        if let Err(PoolError::CreateError(msg)) = result {
            assert_eq!(msg, "test error");
        }
    }

    #[tokio::test]
    async fn test_connection_pool_health_check() {
        let config = PoolConfig {
            max_connections: 5,
            min_idle: 0,
            health_check_enabled: true,
            ..Default::default()
        };
        let pool = ConnectionPool::<u32>::new(config);

        // Add some connections to pool
        let conn1 = pool.acquire(|| async { Ok(1) }).await.unwrap();
        let conn2 = pool.acquire(|| async { Ok(2) }).await.unwrap();
        pool.release(conn1).await;
        pool.release(conn2).await;

        // Health check - all connections pass
        pool.health_check(|_| async { true }).await;

        assert_eq!(pool.size().await, 2);

        // Health check - all connections fail
        pool.health_check(|_| async { false }).await;

        assert_eq!(pool.size().await, 0);

        let metrics = pool.metrics().await;
        assert_eq!(metrics.health_check_failures, 2);
    }

    #[tokio::test]
    async fn test_connection_pool_health_check_disabled() {
        let config = PoolConfig {
            health_check_enabled: false,
            ..Default::default()
        };
        let pool = ConnectionPool::<u32>::new(config);

        let conn = pool.acquire(|| async { Ok(1) }).await.unwrap();
        pool.release(conn).await;

        // Health check should do nothing when disabled
        pool.health_check(|_| async { false }).await;

        // Connection should still be there
        assert_eq!(pool.size().await, 1);
    }

    #[tokio::test]
    async fn test_connection_pool_maintain_idle() {
        let config = PoolConfig {
            max_connections: 10,
            min_idle: 3,
            ..Default::default()
        };
        let pool = ConnectionPool::<u32>::new(config);

        // Pool starts empty
        assert_eq!(pool.size().await, 0);

        // Maintain idle should create min_idle connections
        pool.maintain_idle(|| async { Ok(42u32) }).await;

        assert_eq!(pool.size().await, 3);

        let metrics = pool.metrics().await;
        assert_eq!(metrics.total_created, 3);
        assert_eq!(metrics.idle_connections, 3);
    }

    #[tokio::test]
    async fn test_connection_pool_maintain_idle_already_sufficient() {
        let config = PoolConfig {
            max_connections: 10,
            min_idle: 2,
            ..Default::default()
        };
        let pool = ConnectionPool::<u32>::new(config);

        // Manually add 3 connections
        let conn1 = pool.acquire(|| async { Ok(1) }).await.unwrap();
        let conn2 = pool.acquire(|| async { Ok(2) }).await.unwrap();
        let conn3 = pool.acquire(|| async { Ok(3) }).await.unwrap();
        pool.release(conn1).await;
        pool.release(conn2).await;
        pool.release(conn3).await;

        let initial_created = pool.metrics().await.total_created;

        // Maintain idle should not create more since we have 3 > min_idle(2)
        pool.maintain_idle(|| async { Ok(100u32) }).await;

        let final_created = pool.metrics().await.total_created;
        assert_eq!(initial_created, final_created);
    }

    #[tokio::test]
    async fn test_connection_pool_maintain_idle_error() {
        let config = PoolConfig {
            max_connections: 10,
            min_idle: 3,
            ..Default::default()
        };
        let pool = ConnectionPool::<u32>::new(config);

        // maintain_idle with failing create function
        pool.maintain_idle(|| async { Err(PoolError::CreateError("test".to_string())) })
            .await;

        // Pool should still be empty
        assert_eq!(pool.size().await, 0);
    }

    // HttpClientPool tests
    #[tokio::test]
    async fn test_http_client_pool_new() {
        let config = PoolConfig::default();
        let pool = HttpClientPool::new_http(config);
        assert_eq!(pool.size().await, 0);
    }

    #[tokio::test]
    async fn test_http_client_pool_acquire() {
        let config = PoolConfig::default();
        let pool = HttpClientPool::new_http(config);

        let result = pool.acquire_client().await;
        assert!(result.is_ok());

        let conn = result.unwrap();
        // Verify it's a valid reqwest client
        let _client: &reqwest::Client = conn.get();
    }

    // Edge cases
    #[tokio::test]
    async fn test_connection_pool_stale_connection_not_returned() {
        let config = PoolConfig {
            max_connections: 5,
            min_idle: 0, // Set to 0 so stale connections get closed
            max_idle_time: Duration::from_millis(1), // Very short idle time
            ..Default::default()
        };
        let pool = ConnectionPool::<u32>::new(config);

        let conn = pool.acquire(|| async { Ok(42) }).await.unwrap();

        // Wait for connection to become stale
        tokio::time::sleep(Duration::from_millis(10)).await;

        // Release stale connection
        pool.release(conn).await;

        // Stale connection should be closed, not returned to pool
        let metrics = pool.metrics().await;
        assert_eq!(metrics.total_closed, 1);
    }

    #[tokio::test]
    async fn test_connection_pool_with_complex_type() {
        #[derive(Debug, Clone)]
        struct ComplexConnection {
            id: u32,
            data: Vec<String>,
        }

        let config = PoolConfig::default();
        let pool = ConnectionPool::<ComplexConnection>::new(config);

        let conn = pool
            .acquire(|| async {
                Ok(ComplexConnection {
                    id: 123,
                    data: vec!["test".to_string()],
                })
            })
            .await
            .unwrap();

        assert_eq!(conn.get().id, 123);
        assert_eq!(conn.get().data, vec!["test".to_string()]);
    }

    #[tokio::test]
    async fn test_pooled_connection_updates_last_used() {
        let mut conn = PooledConnection::new(42u32);
        let initial_time = conn.last_used;

        // Sleep a tiny bit
        tokio::time::sleep(Duration::from_millis(1)).await;

        // get_mut should update last_used
        let _ = conn.get_mut();

        assert!(conn.last_used > initial_time);
    }

    #[tokio::test]
    async fn test_connection_pool_partial_health_check() {
        let config = PoolConfig {
            max_connections: 10,
            min_idle: 0,
            health_check_enabled: true,
            ..Default::default()
        };
        let pool = ConnectionPool::<u32>::new(config);

        // Add connections with different values
        let conn1 = pool.acquire(|| async { Ok(1) }).await.unwrap();
        let conn2 = pool.acquire(|| async { Ok(2) }).await.unwrap();
        let conn3 = pool.acquire(|| async { Ok(3) }).await.unwrap();
        pool.release(conn1).await;
        pool.release(conn2).await;
        pool.release(conn3).await;

        // Health check that fails only even numbers
        pool.health_check(|val| {
            let v = *val;
            async move { v % 2 != 0 }
        })
        .await;

        // Only odd-valued connections should remain
        assert_eq!(pool.size().await, 2); // 1 and 3

        let metrics = pool.metrics().await;
        assert_eq!(metrics.health_check_failures, 1); // Connection with value 2
    }
}