use crate::{DbError, PoolStatus, Result};
use deadpool_redis::Pool;
use redis::{FromRedisValue, RedisResult, ScriptInvocation};
use std::time::Duration;
#[derive(Clone)]
pub(crate) enum RedisBackend {
Single(Pool),
#[cfg(feature = "redis-cluster")]
Cluster(deadpool_redis::cluster::Pool),
#[cfg(feature = "redis-sentinel")]
Sentinel(deadpool_redis::sentinel::Pool),
}
pub(crate) enum RedisConn {
Single(deadpool_redis::Connection),
#[cfg(feature = "redis-cluster")]
Cluster(deadpool_redis::cluster::Connection),
#[cfg(feature = "redis-sentinel")]
Sentinel(deadpool_redis::sentinel::Connection),
}
impl RedisBackend {
pub(crate) async fn get(&self) -> Result<RedisConn> {
match self {
RedisBackend::Single(pool) => pool
.get()
.await
.map(RedisConn::Single)
.map_err(DbError::from),
#[cfg(feature = "redis-cluster")]
RedisBackend::Cluster(pool) => pool
.get()
.await
.map(RedisConn::Cluster)
.map_err(map_cluster_pool_error),
#[cfg(feature = "redis-sentinel")]
RedisBackend::Sentinel(pool) => pool
.get()
.await
.map(RedisConn::Sentinel)
.map_err(map_sentinel_pool_error),
}
}
pub(crate) fn status(&self) -> PoolStatus {
let status = match self {
RedisBackend::Single(pool) => pool.status(),
#[cfg(feature = "redis-cluster")]
RedisBackend::Cluster(pool) => pool.status(),
#[cfg(feature = "redis-sentinel")]
RedisBackend::Sentinel(pool) => pool.status(),
};
PoolStatus {
max_size: status.max_size,
size: status.size,
available: status.available,
waiting: status.waiting,
}
}
pub(crate) fn close(&self) {
match self {
RedisBackend::Single(pool) => pool.close(),
#[cfg(feature = "redis-cluster")]
RedisBackend::Cluster(pool) => pool.close(),
#[cfg(feature = "redis-sentinel")]
RedisBackend::Sentinel(pool) => pool.close(),
}
}
pub(crate) fn is_closed(&self) -> bool {
match self {
RedisBackend::Single(pool) => pool.is_closed(),
#[cfg(feature = "redis-cluster")]
RedisBackend::Cluster(pool) => pool.is_closed(),
#[cfg(feature = "redis-sentinel")]
RedisBackend::Sentinel(pool) => pool.is_closed(),
}
}
}
impl RedisConn {
pub(crate) fn set_response_timeout(&mut self, timeout: Duration) {
match self {
RedisConn::Single(conn) => conn.set_response_timeout(timeout),
#[cfg(feature = "redis-sentinel")]
RedisConn::Sentinel(conn) => conn.set_response_timeout(timeout),
#[cfg(feature = "redis-cluster")]
RedisConn::Cluster(_) => {}
}
}
pub(crate) async fn query<T>(&mut self, cmd: &redis::Cmd) -> RedisResult<T>
where
T: FromRedisValue,
{
match self {
RedisConn::Single(conn) => cmd.query_async(conn).await,
#[cfg(feature = "redis-cluster")]
RedisConn::Cluster(conn) => cmd.query_async(conn).await,
#[cfg(feature = "redis-sentinel")]
RedisConn::Sentinel(conn) => cmd.query_async(conn).await,
}
}
pub(crate) async fn query_pipeline<T>(&mut self, pipe: &redis::Pipeline) -> RedisResult<T>
where
T: FromRedisValue,
{
match self {
RedisConn::Single(conn) => pipe.query_async(conn).await,
#[cfg(feature = "redis-cluster")]
RedisConn::Cluster(conn) => pipe.query_async(conn).await,
#[cfg(feature = "redis-sentinel")]
RedisConn::Sentinel(conn) => pipe.query_async(conn).await,
}
}
pub(crate) async fn invoke_script<T>(
&mut self,
invocation: ScriptInvocation<'_>,
) -> RedisResult<T>
where
T: FromRedisValue,
{
match self {
RedisConn::Single(conn) => invocation.invoke_async(conn).await,
#[cfg(feature = "redis-cluster")]
RedisConn::Cluster(conn) => invocation.invoke_async(conn).await,
#[cfg(feature = "redis-sentinel")]
RedisConn::Sentinel(conn) => invocation.invoke_async(conn).await,
}
}
}
pub(crate) fn should_reconnect(error: &redis::RedisError) -> bool {
if error.is_timeout() {
return false;
}
error.is_connection_dropped() || error.is_connection_refusal() || error.is_io_error()
}
pub(crate) fn reconnect_delay(attempt: u32, max_delay_ms: u64) -> Duration {
let exponent = attempt.min(10);
let delay = 10u64.saturating_mul(1u64 << exponent);
Duration::from_millis(delay.min(max_delay_ms.max(1)))
}
#[cfg(feature = "redis-cluster")]
fn map_cluster_pool_error(err: deadpool_redis::cluster::PoolError) -> DbError {
use deadpool_redis::cluster::PoolError as E;
match err {
E::Timeout(_) => DbError::RedisTimeoutError("连接池获取连接超时".to_string()),
E::Closed => DbError::RedisPoolClosed,
E::NoRuntimeSpecified => DbError::RedisPoolError("未指定运行时".to_string()),
E::PostCreateHook(source) => {
DbError::RedisPoolError(format!("连接创建后钩子失败: {:?}", source))
}
E::Backend(err) => DbError::from(err),
}
}
#[cfg(feature = "redis-sentinel")]
fn map_sentinel_pool_error(err: deadpool_redis::sentinel::PoolError) -> DbError {
use deadpool_redis::sentinel::PoolError as E;
match err {
E::Timeout(_) => DbError::RedisTimeoutError("连接池获取连接超时".to_string()),
E::Closed => DbError::RedisPoolClosed,
E::NoRuntimeSpecified => DbError::RedisPoolError("未指定运行时".to_string()),
E::PostCreateHook(source) => {
DbError::RedisPoolError(format!("连接创建后钩子失败: {:?}", source))
}
E::Backend(err) => DbError::from(err),
}
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
#[test]
fn timeout_errors_are_not_retried() {
let error = redis::RedisError::from(std::io::Error::new(
std::io::ErrorKind::TimedOut,
"response timeout",
));
assert!(error.is_timeout(), "构造的超时错误应被识别为 timeout");
assert!(
!should_reconnect(&error),
"response timeout 不能触发重连重试,否则非幂等命令会被重复执行"
);
}
#[test]
fn reconnect_delay_is_bounded() {
assert!(reconnect_delay(1, 200) <= Duration::from_millis(200));
assert!(reconnect_delay(10, 50) <= Duration::from_millis(50));
}
}