use larust_core::AppError;
use larust_orm::Backend;
use serde::de::DeserializeOwned;
use serde::Serialize;
use sqlx::AnyPool;
use std::sync::atomic::{AtomicI64, Ordering};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::sync::OnceCell;
static TABLE_READY: OnceCell<()> = OnceCell::const_new();
static LAST_EXPIRY_SWEEP: AtomicI64 = AtomicI64::new(0);
const EXPIRY_SWEEP_INTERVAL_SECS: i64 = 300;
async fn ensure_table(pool: &AnyPool) -> Result<(), AppError> {
TABLE_READY
.get_or_try_init(|| async {
let create_table = match larust_orm::backend() {
Backend::Sqlite => {
"CREATE TABLE IF NOT EXISTS cache_items (\
\"key\" TEXT PRIMARY KEY, \
value TEXT NOT NULL, \
expires_at INTEGER NOT NULL\
)"
}
Backend::MySql => {
"CREATE TABLE IF NOT EXISTS cache_items (\
\"key\" VARCHAR(255) PRIMARY KEY, \
value VARCHAR(4000) NOT NULL, \
expires_at INTEGER NOT NULL\
)"
}
Backend::Postgres => {
"CREATE TABLE IF NOT EXISTS cache_items (\
\"key\" TEXT PRIMARY KEY, \
value TEXT NOT NULL, \
expires_at INTEGER NOT NULL\
)"
}
};
sqlx::query(create_table)
.execute(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
match larust_orm::backend() {
Backend::Sqlite | Backend::Postgres => {
sqlx::query(
"CREATE INDEX IF NOT EXISTS idx_cache_items_expires_at ON cache_items(expires_at)",
)
.execute(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
}
Backend::MySql => {
if let Err(error) = sqlx::query(
"CREATE INDEX idx_cache_items_expires_at ON cache_items(expires_at)",
)
.execute(pool)
.await
{
let duplicate_key = matches!(&error, sqlx::Error::Database(database)
if database.message().contains("Duplicate key name"));
if !duplicate_key {
return Err(AppError::Internal(Box::new(error)));
}
}
}
}
Ok(())
})
.await?;
Ok(())
}
fn now_unix_secs() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system clock is before the Unix epoch")
.as_secs() as i64
}
async fn sweep_expired_if_due(pool: &AnyPool) {
let now = now_unix_secs();
let previous = LAST_EXPIRY_SWEEP.load(Ordering::Relaxed);
if now - previous < EXPIRY_SWEEP_INTERVAL_SECS
|| LAST_EXPIRY_SWEEP
.compare_exchange(previous, now, Ordering::Relaxed, Ordering::Relaxed)
.is_err()
{
return;
}
let sql = format!(
"DELETE FROM cache_items WHERE expires_at <= {}",
larust_orm::placeholder(larust_orm::backend(), 1)
);
if let Err(error) = sqlx::query(&sql).bind(now).execute(pool).await {
tracing::warn!(%error, "failed to sweep expired cache entries");
}
}
pub(crate) async fn put<T: Serialize>(key: &str, value: &T, ttl: Duration) -> Result<(), AppError> {
let pool = larust_orm::pool()?;
ensure_table(pool).await?;
sweep_expired_if_due(pool).await;
let json =
serde_json::to_string(value).map_err(|source| AppError::Internal(Box::new(source)))?;
let expires_at = now_unix_secs() + ttl.as_secs() as i64;
let upsert_sql = match larust_orm::backend() {
Backend::Sqlite => {
"INSERT INTO cache_items (\"key\", value, expires_at) VALUES (?, ?, ?) \
ON CONFLICT(\"key\") DO UPDATE SET value = excluded.value, expires_at = excluded.expires_at"
}
Backend::MySql => {
"INSERT INTO cache_items (\"key\", value, expires_at) VALUES (?, ?, ?) \
ON DUPLICATE KEY UPDATE value = VALUES(value), expires_at = VALUES(expires_at)"
}
Backend::Postgres => {
"INSERT INTO cache_items (\"key\", value, expires_at) VALUES ($1, $2, $3) \
ON CONFLICT(\"key\") DO UPDATE SET value = excluded.value, expires_at = excluded.expires_at"
}
};
sqlx::query(upsert_sql)
.bind(key)
.bind(json)
.bind(expires_at)
.execute(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
Ok(())
}
pub(crate) async fn get<T: DeserializeOwned>(key: &str) -> Result<Option<T>, AppError> {
let pool = larust_orm::pool()?;
ensure_table(pool).await?;
sweep_expired_if_due(pool).await;
let select_sql = format!(
"SELECT value, expires_at FROM cache_items WHERE \"key\" = {}",
larust_orm::placeholder(larust_orm::backend(), 1)
);
let row: Option<(String, i64)> = sqlx::query_as(&select_sql)
.bind(key)
.fetch_optional(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
let Some((json, expires_at)) = row else {
return Ok(None);
};
if expires_at <= now_unix_secs() {
let delete_sql = format!(
"DELETE FROM cache_items WHERE \"key\" = {}",
larust_orm::placeholder(larust_orm::backend(), 1)
);
let _ = sqlx::query(&delete_sql).bind(key).execute(pool).await;
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 pool = larust_orm::pool()?;
ensure_table(pool).await?;
let sql = format!(
"DELETE FROM cache_items WHERE \"key\" = {}",
larust_orm::placeholder(larust_orm::backend(), 1)
);
sqlx::query(&sql)
.bind(key)
.execute(pool)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
Ok(())
}