use larust_core::AppError;
use redis::aio::ConnectionManager;
use redis::AsyncCommands;
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::time::Duration;
use tokio::sync::OnceCell;
static CONNECTION: OnceCell<ConnectionManager> = OnceCell::const_new();
async fn connection() -> Result<ConnectionManager, AppError> {
let manager = CONNECTION
.get_or_try_init(|| async {
let url = larust_support_env("REDIS_URL", "redis://127.0.0.1:6379");
let client = redis::Client::open(url).map_err(|e| AppError::Config(Box::new(e)))?;
ConnectionManager::new(client)
.await
.map_err(|e| AppError::Internal(Box::new(e)))
})
.await?;
Ok(manager.clone())
}
fn larust_support_env(key: &str, default: &str) -> String {
std::env::var(key).unwrap_or_else(|_| default.to_string())
}
pub(crate) async fn put<T: Serialize>(key: &str, value: &T, ttl: Duration) -> Result<(), AppError> {
let json =
serde_json::to_string(value).map_err(|source| AppError::Internal(Box::new(source)))?;
let mut conn = connection().await?;
let ttl_secs = ttl.as_secs().max(1);
conn.set_ex::<_, _, ()>(key, json, ttl_secs)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
Ok(())
}
pub(crate) async fn get<T: DeserializeOwned>(key: &str) -> Result<Option<T>, AppError> {
let mut conn = connection().await?;
let value: Option<String> = conn
.get(key)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
let Some(json) = value else {
return Ok(None);
};
serde_json::from_str(&json)
.map(Some)
.map_err(|source| AppError::Internal(Box::new(source)))
}
pub(crate) async fn forget(key: &str) -> Result<(), AppError> {
let mut conn = connection().await?;
conn.del::<_, ()>(key)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
Ok(())
}