use agent_framework_core::error::{Error, Result};
use redis::aio::MultiplexedConnection;
use tokio::sync::OnceCell;
pub(crate) struct LazyConnection {
client: redis::Client,
cell: OnceCell<MultiplexedConnection>,
}
impl LazyConnection {
pub(crate) fn open(url: &str) -> Result<Self> {
let client = redis::Client::open(url)
.map_err(|e| Error::Configuration(format!("invalid Redis URL '{url}': {e}")))?;
Ok(Self {
client,
cell: OnceCell::new(),
})
}
pub(crate) async fn get(&self) -> Result<MultiplexedConnection> {
self.cell
.get_or_try_init(|| async { self.client.get_multiplexed_async_connection().await })
.await
.cloned()
.map_err(map_redis_err)
}
}
pub(crate) fn map_redis_err(e: redis::RedisError) -> Error {
Error::service(format!("redis error: {e}"))
}