loveyu-kit 0.2.0

面向 Axum 项目的可组合 API 工具库
Documentation
//! 可扩展的中间件连接生命周期管理。

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;

/// 连接生命周期方法的统一 Future 类型。
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>;
}

/// 校验已建立的连接是否可用。
///
/// `ManagedConnection` 只会在底层连接已经初始化时调用此方法;未启用状态由工具库统一转换为
/// `ManagedConnectionError::Unavailable`,扩展实现无需自行处理。
pub trait Verify: ConnectionSpec {
    fn verify<'a>(
        &'a self,
        connection: &'a Self::Connection,
    ) -> BoxConnectionFuture<'a, (), Self::Error>;
}

/// 显式关闭连接并释放底层资源。
///
/// `ManagedConnection` 只会在底层连接已经初始化时调用此方法;未启用状态没有资源需要释放,
/// 工具库会直接返回 `Ok(())`,扩展实现无需自行处理。
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,
{
    /// 获取底层连接的引用。
    ///
    /// # Errors
    ///
    /// 连接器未启用、因而没有初始化底层连接时返回 [`ConnectionUnavailable`]。
    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()
    }

    /// 重新执行连接健康检查。
    ///
    /// # Errors
    ///
    /// 连接未初始化或连接器健康检查失败时返回错误。
    pub async fn verify(&self) -> Result<(), ManagedConnectionError<C::Error>> {
        let connection = self.connection()?;
        Verify::verify(&self.connector, connection)
            .await
            .map_err(ManagedConnectionError::Connector)
    }

    /// 显式关闭连接;连接器未启用时没有资源需要释放,因此幂等返回成功。
    ///
    /// # Errors
    ///
    /// 底层连接的关闭或刷新流程失败时返回连接器错误。
    pub async fn close(self) -> Result<(), C::Error> {
        let Self {
            connector,
            connection,
        } = self;
        match connection {
            Some(connection) => Close::close(&connector, connection).await,
            None => Ok(()),
        }
    }

    /// 取出底层连接,由调用方接管后续生命周期。
    ///
    /// # Errors
    ///
    /// 连接器未启用、因而没有底层连接时返回 [`ConnectionUnavailable`]。
    pub fn into_inner(self) -> Result<C::Connection, ConnectionUnavailable> {
        self.connection
            .ok_or_else(|| ConnectionUnavailable::new(self.connector.name()))
    }
}

/// 根据连接器配置建立连接,并在返回前完成首次健康检查。
///
/// # Errors
///
/// 建立连接或首次健康检查失败时返回连接器错误。
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 {
    /// 默认连接池配置:最少 1 条、最多 20 条连接,获取连接超时 5 秒。
    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,
        }
    }

    /// 创建并立即校验连接池配置,适合处理配置文件或用户输入。
    ///
    /// # Errors
    ///
    /// 连接数范围非法或获取超时为零时返回 [`ConnectionError::InvalidPoolOptions`]。
    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()
    }

    /// 校验连接池参数并返回自身,便于在构建配置时继续链式调用。
    ///
    /// # Errors
    ///
    /// 连接数范围非法或获取超时为零时返回 [`ConnectionError::InvalidPoolOptions`]。
    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());
    }
}