use core::fmt::Display;
use core::ops::{Deref, DerefMut};
use std::future::Future;
use std::string::String;
use std::{sync::Arc, time::Duration};
use crate::net::{ConnectionSettings, NetError, NetResult};
use bb8::PooledConnection;
cfg_if::cfg_if! {
if #[cfg(feature = "tls-with-tokio-rustls")] {
use crate::net::tls::tokio_rustls::{Client, connect};
} else if #[cfg(feature = "async-with-tokio")] {
pub type Client = crate::net::Client<tokio::net::TcpStream>;
} else {
compile_error!("async_pool enabled without any async feature.");
}
}
#[derive(Clone, Debug)]
pub struct KmipConnError(String);
impl From<NetError> for KmipConnError {
fn from(err: NetError) -> Self {
KmipConnError(err.to_string())
}
}
impl<E: std::error::Error + 'static> From<bb8::RunError<E>> for KmipConnError {
fn from(err: bb8::RunError<E>) -> Self {
KmipConnError(format!("{err}"))
}
}
impl Display for KmipConnError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}", self.0)
}
}
pub struct KmipConn<'a> {
conn: PooledConnection<'a, ConnectionManager>,
}
impl<'a> KmipConn<'a> {
fn new(conn: PooledConnection<'a, ConnectionManager>) -> Self {
Self { conn }
}
}
impl<'a> Deref for KmipConn<'a> {
type Target = Client;
fn deref(&self) -> &Self::Target {
self.conn.deref()
}
}
impl<'a> DerefMut for KmipConn<'a> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.conn.deref_mut()
}
}
#[derive(Clone, Debug)]
pub struct ConnPool {
server_id: String,
conn_settings: Arc<ConnectionSettings>,
pool: bb8::Pool<ConnectionManager>,
}
impl ConnPool {
pub async fn new(
server_id: String,
conn_settings: Arc<ConnectionSettings>,
max_conncurrent_connections: u32,
max_life_time: Option<Duration>,
max_idle_time: Option<Duration>,
) -> Result<ConnPool, KmipConnError> {
let pool = bb8::Pool::builder()
.min_idle(Some(0))
.max_size(max_conncurrent_connections)
.test_on_check_out(false)
.max_lifetime(max_life_time)
.idle_timeout(max_idle_time)
.connection_timeout(conn_settings.connect_timeout.unwrap_or(Duration::from_secs(30)))
.build(ConnectionManager {
conn_settings: conn_settings.clone(),
})
.await?;
Ok(Self {
server_id,
conn_settings,
pool,
})
}
pub fn server_id(&self) -> &str {
&self.server_id
}
pub fn conn_settings(&self) -> &ConnectionSettings {
&self.conn_settings
}
pub async fn get(&self) -> Result<KmipConn<'_>, KmipConnError> {
Ok(KmipConn::new(self.pool.get().await?))
}
}
#[derive(Debug)]
pub struct ConnectionManager {
conn_settings: Arc<ConnectionSettings>,
}
impl ConnectionManager
where
Self: bb8::ManageConnection,
{
#[rustfmt::skip]
pub async fn create_connection_pool(
server_id: String,
conn_settings: Arc<ConnectionSettings>,
max_conncurrent_connections: u32,
max_life_time: Option<Duration>,
max_idle_time: Option<Duration>,
) -> Result<ConnPool, KmipConnError> {
ConnPool::new(
server_id,
conn_settings,
max_conncurrent_connections,
max_life_time,
max_idle_time,
).await
}
async fn connect_one_off(settings: &ConnectionSettings) -> NetResult<Client> {
connect(settings).await
}
}
impl bb8::ManageConnection for ConnectionManager {
type Connection = Client;
type Error = NetError;
fn connect(&self) -> impl Future<Output = Result<Self::Connection, Self::Error>> + Send {
Self::connect_one_off(&self.conn_settings)
}
fn is_valid(&self, _conn: &mut Self::Connection) -> impl Future<Output = Result<(), Self::Error>> + Send {
unreachable!();
#[allow(unreachable_code)]
std::future::ready(Ok(()))
}
fn has_broken(&self, conn: &mut Self::Connection) -> bool {
conn.connection_error_count() > 1
}
}