use redis::aio::MultiplexedConnection;
use redis::{RedisError, RedisResult};
use std::sync::{Mutex, MutexGuard, PoisonError};
pub(super) struct SharedConnection {
client: redis::Client,
cached: Mutex<CachedConnection>,
}
#[derive(Default)]
struct CachedConnection {
generation: u64,
connection: Option<MultiplexedConnection>,
}
pub(super) struct ConnectionHandle {
pub(super) generation: u64,
pub(super) connection: MultiplexedConnection,
}
impl SharedConnection {
pub(super) fn new(client: redis::Client) -> Self {
Self {
client,
cached: Mutex::new(CachedConnection::default()),
}
}
pub(super) async fn connection(&self) -> RedisResult<ConnectionHandle> {
if let Some(handle) = self.cached_handle() {
return Ok(handle);
}
let connection = self.client.get_multiplexed_async_connection().await?;
let mut cached = self.lock();
if let Some(existing) = &cached.connection {
return Ok(ConnectionHandle {
generation: cached.generation,
connection: existing.clone(),
});
}
cached.generation = cached.generation.wrapping_add(1);
cached.connection = Some(connection.clone());
Ok(ConnectionHandle {
generation: cached.generation,
connection,
})
}
fn cached_handle(&self) -> Option<ConnectionHandle> {
let cached = self.lock();
let connection = cached.connection.clone()?;
Some(ConnectionHandle {
generation: cached.generation,
connection,
})
}
pub(super) fn discard_if_broken(&self, generation: u64, error: &RedisError) {
if !(error.is_unrecoverable_error() || error.is_connection_dropped()) {
return;
}
let mut cached = self.lock();
if cached.generation == generation {
cached.connection = None;
}
}
fn lock(&self) -> MutexGuard<'_, CachedConnection> {
self.cached.lock().unwrap_or_else(PoisonError::into_inner)
}
}