1use crate::{CleanupConfig, ConnectionManager, ConnectionPool, ManagedConnection};
2use std::{sync::Arc, time::Duration};
3use tokio::net::{TcpStream, ToSocketAddrs};
4
5#[derive(Clone)]
7pub struct TcpConnectionManager<A: ToSocketAddrs + Send + Sync + Clone + 'static> {
8 pub address: A,
9}
10
11impl<A> ConnectionManager for TcpConnectionManager<A>
12where
13 A: ToSocketAddrs + Send + Sync + Clone + 'static,
14{
15 type Connection = TcpStream;
16 type Error = std::io::Error;
17 type CreateFut = std::pin::Pin<Box<dyn Future<Output = Result<TcpStream, Self::Error>> + Send>>;
18 type ValidFut<'a> = std::pin::Pin<Box<dyn Future<Output = bool> + Send + 'a>>;
19
20 fn create_connection(&self) -> Self::CreateFut {
21 let addr = self.address.clone();
22 Box::pin(async move { TcpStream::connect(addr).await })
23 }
24
25 fn is_valid<'a>(&'a self, stream: &'a mut Self::Connection) -> Self::ValidFut<'a> {
26 Box::pin(async move {
27 stream.peer_addr().is_ok()
29 })
30 }
31}
32
33pub type TcpConnectionPool<A = std::net::SocketAddr> = ConnectionPool<TcpConnectionManager<A>>;
35
36pub type TcpManagedConnection<A = std::net::SocketAddr> = ManagedConnection<TcpConnectionManager<A>>;
38
39impl<A> TcpConnectionPool<A>
40where
41 A: ToSocketAddrs + Send + Sync + Clone + 'static,
42{
43 pub fn new_tcp(
45 max_size: Option<usize>,
46 max_idle_time: Option<Duration>,
47 connection_timeout: Option<Duration>,
48 cleanup_config: Option<CleanupConfig>,
49 address: A,
50 ) -> Arc<Self> {
51 log::info!("Creating TCP connection pool");
52 let manager = TcpConnectionManager { address };
53 Self::new(max_size, max_idle_time, connection_timeout, cleanup_config, manager)
54 }
55}