use chrono::{Duration, SecondsFormat, Utc};
use serde::{de::DeserializeOwned, Serialize};
use slabs_core::{SlabError, SlabResult};
use slabs_db::Db;
fn format_utc_timestamp(dt: chrono::DateTime<Utc>) -> String {
dt.to_rfc3339_opts(SecondsFormat::Micros, true)
}
fn compute_expiry(now: chrono::DateTime<Utc>, ttl_seconds: i64) -> SlabResult<String> {
if ttl_seconds <= 0 {
return Err(SlabError::bad_request(
"cache ttl_seconds must be greater than zero",
));
}
let delta = Duration::try_seconds(ttl_seconds)
.ok_or_else(|| SlabError::bad_request("cache ttl_seconds overflow"))?;
let expires = now
.checked_add_signed(delta)
.ok_or_else(|| SlabError::bad_request("cache ttl_seconds overflow"))?;
Ok(format_utc_timestamp(expires))
}
#[derive(Debug, Clone)]
pub struct Cache {
db: Db,
}
impl Cache {
#[must_use]
pub fn new(db: Db) -> Self {
Self { db }
}
pub async fn set(&self, key: &str, value: &str, ttl_seconds: i64) -> SlabResult<()> {
let now = Utc::now();
let expires_at = compute_expiry(now, ttl_seconds)?;
let updated_at = format_utc_timestamp(now);
sqlx::query(
"INSERT INTO slabs_cache (cache_key, value_text, expires_at, updated_at)
VALUES (?, ?, ?, ?)
ON CONFLICT(cache_key) DO UPDATE SET
value_text = excluded.value_text,
expires_at = excluded.expires_at,
updated_at = excluded.updated_at",
)
.bind(key)
.bind(value)
.bind(&expires_at)
.bind(&updated_at)
.execute(self.db.pool())
.await?;
Ok(())
}
pub async fn get(&self, key: &str) -> SlabResult<Option<String>> {
let now_str = format_utc_timestamp(Utc::now());
let row: Option<(String,)> = sqlx::query_as(
"SELECT value_text FROM slabs_cache WHERE cache_key = ? AND expires_at > ?",
)
.bind(key)
.bind(&now_str)
.fetch_optional(self.db.pool())
.await?;
Ok(row.map(|(v,)| v))
}
pub async fn set_json<T: Serialize>(
&self,
key: &str,
value: &T,
ttl_seconds: i64,
) -> SlabResult<()> {
let json = serde_json::to_string(value)
.map_err(|e| SlabError::internal(format!("cache serialize failed: {e}")))?;
self.set(key, &json, ttl_seconds).await
}
pub async fn get_json<T: DeserializeOwned>(&self, key: &str) -> SlabResult<Option<T>> {
let Some(raw) = self.get(key).await? else {
return Ok(None);
};
let parsed = serde_json::from_str(&raw)
.map_err(|e| SlabError::internal(format!("cache deserialize failed: {e}")))?;
Ok(Some(parsed))
}
pub async fn delete(&self, key: &str) -> SlabResult<()> {
sqlx::query("DELETE FROM slabs_cache WHERE cache_key = ?")
.bind(key)
.execute(self.db.pool())
.await?;
Ok(())
}
pub async fn purge_expired(&self) -> SlabResult<u64> {
let now_str = format_utc_timestamp(Utc::now());
let res = sqlx::query("DELETE FROM slabs_cache WHERE expires_at <= ?")
.bind(&now_str)
.execute(self.db.pool())
.await?;
Ok(res.rows_affected())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rejects_non_positive_and_overflow_ttl() {
let now = Utc::now();
assert!(compute_expiry(now, 0).is_err());
assert!(compute_expiry(now, -10).is_err());
assert!(compute_expiry(now, i64::MAX).is_err());
}
#[test]
fn formats_fixed_width_microsecond_rfc3339_timestamps() {
let now = Utc::now();
let ts = compute_expiry(now, 60).unwrap();
assert_eq!(ts.len(), 27);
assert!(ts.ends_with('Z'));
assert!(ts > format_utc_timestamp(now));
}
}