loveyu-kit 0.2.0

面向 Axum 项目的可组合 API 工具库
Documentation
use std::{fmt, time::Duration};

use redis::AsyncCommands;

use super::{BoxConnectionFuture, Close, Connect, ConnectionError, ConnectionSpec, Verify};

pub use redis::aio::{
    ConnectionManager as RedisConnectionManager,
    ConnectionManagerConfig as RedisConnectionManagerConfig,
};

/// Redis 连接管理器连接器。
#[derive(Clone)]
#[must_use = "连接器配置需要传给 connect 才会生效"]
pub struct RedisConnector {
    name: String,
    enabled: bool,
    url: String,
    manager_config: RedisConnectionManagerConfig,
}

impl RedisConnector {
    pub fn new(url: impl Into<String>) -> Self {
        Self {
            name: "redis".to_owned(),
            enabled: true,
            url: url.into(),
            manager_config: RedisConnectionManagerConfig::new()
                .set_connection_timeout(Some(Duration::from_secs(5)))
                .set_response_timeout(Some(Duration::from_secs(5))),
        }
    }

    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = name.into();
        self
    }

    pub const fn with_enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }

    /// 替换 Redis 原生连接管理配置,可设置超时、重连退避和并发限制。
    pub fn with_manager_config(mut self, config: RedisConnectionManagerConfig) -> Self {
        self.manager_config = config;
        self
    }
}

impl fmt::Debug for RedisConnector {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("RedisConnector")
            .field("name", &self.name)
            .field("enabled", &self.enabled)
            .field("url", &"[已隐藏]")
            .field("manager_config", &"[已隐藏]")
            .finish()
    }
}

impl ConnectionSpec for RedisConnector {
    type Connection = RedisConnectionManager;
    type Error = ConnectionError;

    fn name(&self) -> &str {
        &self.name
    }

    fn enabled(&self) -> bool {
        self.enabled
    }
}

impl Connect for RedisConnector {
    fn connect(&self) -> BoxConnectionFuture<'_, Self::Connection, Self::Error> {
        Box::pin(async move {
            if self
                .manager_config
                .connection_timeout()
                .is_some_and(|timeout| timeout.is_zero())
            {
                return Err(ConnectionError::InvalidConfig {
                    connector: "Redis",
                    message: "连接超时必须大于 0",
                });
            }
            if self
                .manager_config
                .response_timeout()
                .is_some_and(|timeout| timeout.is_zero())
            {
                return Err(ConnectionError::InvalidConfig {
                    connector: "Redis",
                    message: "响应超时必须大于 0",
                });
            }
            let client = redis::Client::open(self.url.as_str())?;
            RedisConnectionManager::new_with_config(client, self.manager_config.clone())
                .await
                .map_err(Into::into)
        })
    }
}

impl Verify for RedisConnector {
    fn verify<'a>(
        &'a self,
        connection: &'a Self::Connection,
    ) -> BoxConnectionFuture<'a, (), Self::Error> {
        Box::pin(async move {
            let mut connection = connection.clone();
            let pong: String = connection.ping().await?;
            if pong != "PONG" {
                return Err(ConnectionError::UnexpectedRedisPing(pong));
            }
            Ok(())
        })
    }
}

impl Close for RedisConnector {
    fn close(&self, connection: Self::Connection) -> BoxConnectionFuture<'_, (), Self::Error> {
        Box::pin(async move {
            // ConnectionManager 没有异步 close API,消费并丢弃句柄即可关闭当前引用。
            drop(connection);
            Ok(())
        })
    }
}