use std::{error::Error, future::Future, pin::Pin};
#[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
use std::time::Duration;
#[cfg(feature = "connection-elasticsearch")]
mod elasticsearch;
mod error;
#[cfg(feature = "connection-etcd")]
mod etcd;
#[cfg(feature = "connection-kafka")]
mod kafka;
#[cfg(feature = "connection-mqtt")]
mod mqtt;
#[cfg(feature = "connection-mysql")]
mod mysql;
#[cfg(feature = "connection-postgres")]
mod postgres;
#[cfg(feature = "connection-redis")]
mod redis;
#[cfg(all(
feature = "logging",
any(feature = "connection-mysql", feature = "connection-postgres")
))]
mod sql_logging_pool;
#[cfg(feature = "connection-elasticsearch")]
pub use elasticsearch::{ElasticsearchClient, ElasticsearchConnector, ElasticsearchCredentials};
#[cfg(any(
feature = "connection-mysql",
feature = "connection-postgres",
feature = "connection-redis",
feature = "connection-kafka",
feature = "connection-etcd",
feature = "connection-mqtt",
feature = "connection-elasticsearch"
))]
pub use error::ConnectionError;
pub use error::{ConnectionUnavailable, ManagedConnectionError};
#[cfg(feature = "connection-etcd")]
pub use etcd::{EtcdClient, EtcdConnectOptions, EtcdConnector};
#[cfg(feature = "connection-kafka")]
pub use kafka::{
KafkaConnector, KafkaConsumer, KafkaConsumerApi, KafkaConsumerConnector, KafkaProducer,
KafkaProducerConnector, KafkaStreamConsumer,
};
#[cfg(feature = "connection-mqtt")]
pub use mqtt::{MqttClient, MqttConnection, MqttConnector, MqttOptions};
#[cfg(feature = "connection-mysql")]
pub use mysql::{DEFAULT_MYSQL_SQL_MODE, DEFAULT_MYSQL_TIME_ZONE, MySqlConnector, MySqlPool};
#[cfg(feature = "connection-postgres")]
pub use postgres::{PgPool, PostgresConnector};
#[cfg(feature = "connection-redis")]
pub use redis::{RedisConnectionManager, RedisConnectionManagerConfig, RedisConnector};
#[cfg(all(
feature = "logging",
any(feature = "connection-mysql", feature = "connection-postgres")
))]
pub use sql_logging_pool::SqlLoggingPool;
pub type BoxConnectionFuture<'a, T, E> = Pin<Box<dyn Future<Output = Result<T, E>> + Send + 'a>>;
pub trait ConnectionSpec: Send + Sync {
type Connection: Send + Sync;
type Error: Error + Send + Sync + 'static;
fn name(&self) -> &str;
fn enabled(&self) -> bool {
true
}
}
pub trait Connect: ConnectionSpec {
fn connect(&self) -> BoxConnectionFuture<'_, Self::Connection, Self::Error>;
}
pub trait Verify: ConnectionSpec {
fn verify<'a>(
&'a self,
connection: &'a Self::Connection,
) -> BoxConnectionFuture<'a, (), Self::Error>;
}
pub trait Close: ConnectionSpec {
fn close(&self, connection: Self::Connection) -> BoxConnectionFuture<'_, (), Self::Error>;
}
pub trait Connector: Connect + Verify + Close {}
impl<T> Connector for T where T: Connect + Verify + Close {}
pub struct ManagedConnection<C>
where
C: Connector,
{
connector: C,
connection: Option<C::Connection>,
}
impl<C> ManagedConnection<C>
where
C: Connector,
{
pub fn connection(&self) -> Result<&C::Connection, ConnectionUnavailable> {
self.connection
.as_ref()
.ok_or_else(|| ConnectionUnavailable::new(self.connector.name()))
}
pub const fn connector(&self) -> &C {
&self.connector
}
pub const fn is_connected(&self) -> bool {
self.connection.is_some()
}
pub async fn verify(&self) -> Result<(), ManagedConnectionError<C::Error>> {
let connection = self.connection()?;
Verify::verify(&self.connector, connection)
.await
.map_err(ManagedConnectionError::Connector)
}
pub async fn close(self) -> Result<(), C::Error> {
let Self {
connector,
connection,
} = self;
match connection {
Some(connection) => Close::close(&connector, connection).await,
None => Ok(()),
}
}
pub fn into_inner(self) -> Result<C::Connection, ConnectionUnavailable> {
self.connection
.ok_or_else(|| ConnectionUnavailable::new(self.connector.name()))
}
}
pub async fn connect<C>(connector: C) -> Result<ManagedConnection<C>, C::Error>
where
C: Connector,
{
if !connector.enabled() {
tracing::warn!(connector = connector.name(), "中间件未启用,跳过连接初始化");
return Ok(ManagedConnection {
connector,
connection: None,
});
}
let connection = Connect::connect(&connector).await?;
if let Err(error) = Verify::verify(&connector, &connection).await {
let _ = Close::close(&connector, connection).await;
return Err(error);
}
Ok(ManagedConnection {
connector,
connection: Some(connection),
})
}
#[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[must_use = "连接池配置需要传给连接器才会生效"]
pub struct PoolOptions {
pub min_connections: u32,
pub max_connections: u32,
pub acquire_timeout: Duration,
}
#[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
impl PoolOptions {
pub const DEFAULT: Self = Self::new(1, 20, Duration::from_secs(5));
pub const fn new(
min_connections: u32,
max_connections: u32,
acquire_timeout: Duration,
) -> Self {
Self {
min_connections,
max_connections,
acquire_timeout,
}
}
pub fn try_new(
min_connections: u32,
max_connections: u32,
acquire_timeout: Duration,
) -> Result<Self, ConnectionError> {
Self::new(min_connections, max_connections, acquire_timeout).validate()
}
pub fn validate(self) -> Result<Self, ConnectionError> {
if self.max_connections == 0 || self.min_connections > self.max_connections {
return Err(ConnectionError::InvalidPoolOptions(
"最大连接数必须大于 0,且不能小于最小连接数".to_owned(),
));
}
if self.acquire_timeout.is_zero() {
return Err(ConnectionError::InvalidPoolOptions(
"获取连接的超时时间必须大于 0".to_owned(),
));
}
Ok(self)
}
}
#[cfg(any(feature = "connection-mysql", feature = "connection-postgres"))]
impl Default for PoolOptions {
fn default() -> Self {
Self::DEFAULT
}
}
#[cfg(all(
test,
any(feature = "connection-mysql", feature = "connection-postgres")
))]
mod tests {
use std::time::Duration;
use super::PoolOptions;
#[test]
fn 连接池使用约定的默认参数() {
assert_eq!(
PoolOptions::default(),
PoolOptions::new(1, 20, Duration::from_secs(5))
);
assert_eq!(PoolOptions::DEFAULT, PoolOptions::default());
}
}