mod config;
use std::{
ops::{Deref, DerefMut},
sync::atomic::{AtomicUsize, Ordering},
};
use deadpool::managed;
use redis::{aio::ConnectionLike, IntoConnectionInfo, RedisError, RedisResult};
use redis;
pub use redis::cluster::ClusterClient;
pub use redis::cluster_async::ClusterConnection;
pub use self::config::{Config, ConfigError};
pub use deadpool::managed::reexports::*;
deadpool::managed_reexports!(
"redis_cluster",
Manager,
Connection,
RedisError,
ConfigError
);
type RecycleResult = managed::RecycleResult<RedisError>;
#[allow(missing_debug_implementations)] pub struct Connection {
conn: Object,
}
impl Connection {
#[must_use]
pub fn take(this: Self) -> ClusterConnection {
Object::take(this.conn)
}
}
impl From<Object> for Connection {
fn from(conn: Object) -> Self {
Self { conn }
}
}
impl Deref for Connection {
type Target = ClusterConnection;
fn deref(&self) -> &ClusterConnection {
&self.conn
}
}
impl DerefMut for Connection {
fn deref_mut(&mut self) -> &mut ClusterConnection {
&mut self.conn
}
}
impl AsRef<ClusterConnection> for Connection {
fn as_ref(&self) -> &ClusterConnection {
&self.conn
}
}
impl AsMut<ClusterConnection> for Connection {
fn as_mut(&mut self) -> &mut ClusterConnection {
&mut self.conn
}
}
impl ConnectionLike for Connection {
fn req_packed_command<'a>(
&'a mut self,
cmd: &'a redis::Cmd,
) -> redis::RedisFuture<'a, redis::Value> {
self.conn.req_packed_command(cmd)
}
fn req_packed_commands<'a>(
&'a mut self,
cmd: &'a redis::Pipeline,
offset: usize,
count: usize,
) -> redis::RedisFuture<'a, Vec<redis::Value>> {
self.conn.req_packed_commands(cmd, offset, count)
}
fn get_db(&self) -> i64 {
self.conn.get_db()
}
}
pub struct Manager {
client: ClusterClient,
ping_number: AtomicUsize,
}
impl std::fmt::Debug for Manager {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Manager")
.field("client", &format!("{:p}", &self.client))
.field("ping_number", &self.ping_number)
.finish()
}
}
impl Manager {
pub fn new<T: IntoConnectionInfo>(params: Vec<T>) -> RedisResult<Self> {
Ok(Self {
client: ClusterClient::new(params)?,
ping_number: AtomicUsize::new(0),
})
}
}
impl managed::Manager for Manager {
type Type = ClusterConnection;
type Error = RedisError;
async fn create(&self) -> Result<ClusterConnection, RedisError> {
let conn = self.client.get_async_connection().await?;
Ok(conn)
}
async fn recycle(&self, conn: &mut ClusterConnection, _: &Metrics) -> RecycleResult {
let ping_number = self.ping_number.fetch_add(1, Ordering::Relaxed).to_string();
let n = redis::cmd("PING")
.arg(&ping_number)
.query_async::<_, String>(conn)
.await?;
if n == ping_number {
Ok(())
} else {
Err(managed::RecycleError::message("Invalid PING response"))
}
}
}