slabs-cache 0.5.0

SQLite-backed TTL key-value cache battery (Solid Cache style)
Documentation
//! `SQLite`-backed TTL key-value cache for Slabs applications.
//!
//! This crate owns [`Cache`], which stores string and JSON entries in the `slabs_cache` system table
//! with no external cache daemon.
//!
//! # Database table
//!
//! [`Cache`] reads and writes the `slabs_cache` table created by [`slabs_db::Db::init_system_tables`]:
//!
//! - `cache_key TEXT PRIMARY KEY NOT NULL`
//! - `value_text TEXT NOT NULL`
//! - `expires_at TEXT NOT NULL` (UTC RFC 3339 timestamp, indexed by `idx_slabs_cache_expires_at`)
//! - `updated_at TEXT NOT NULL` (UTC RFC 3339 timestamp)
//!
//! # Invariants
//!
//! - **Strict read-time TTL check**: [`Cache::get`] and [`Cache::get_json`] filter with `expires_at > now` (fixed-width UTC RFC 3339 microseconds). Expired rows return `Ok(None)` immediately.
//! - **Lazy row cleanup**: expired rows stay in `slabs_cache` until overwritten by [`Cache::set`] or [`Cache::set_json`], removed by [`Cache::delete`], or swept by [`Cache::purge_expired`].
//! - **Positive TTL required**: passing `ttl_seconds <= 0` or an overflowing TTL returns [`SlabError::BadRequest`].
//! - **Pool usage**: all cache operations execute against `db.pool()` (the writer pool), keeping writes and immediate reads serialized.
//! - **JSON errors**: [`Cache::set_json`] and [`Cache::get_json`] return [`SlabError::Internal`] if `serde_json` fails.
//!
//! # Usage
//!
//! ```rust,no_run
//! use serde::{Deserialize, Serialize};
//! use slabs_cache::Cache;
//! use slabs_core::SlabResult;
//! use slabs_db::Db;
//!
//! #[derive(Serialize, Deserialize)]
//! struct RoomStats {
//!     members: u64,
//! }
//!
//! async fn example(db: Db) -> SlabResult<()> {
//!     let cache = Cache::new(db);
//!     cache.set("banner", "maintenance at 02:00 UTC", 300).await?;
//!     let _banner: Option<String> = cache.get("banner").await?;
//!
//!     cache
//!         .set_json("room:1:stats", &RoomStats { members: 12 }, 60)
//!         .await?;
//!     let _stats: Option<RoomStats> = cache.get_json("room:1:stats").await?;
//!
//!     let _removed = cache.purge_expired().await?;
//!     Ok(())
//! }
//! ```

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))
}

/// `SQLite`-backed TTL key-value cache reading and writing the `slabs_cache` table.
///
/// Requires [`slabs_db::Db::init_system_tables`] (or [`slabs_db::Db::migrate`]) before use.
#[derive(Debug, Clone)]
pub struct Cache {
    db: Db,
}

impl Cache {
    /// Creates a [`Cache`] backed by the given [`Db`] handle.
    #[must_use]
    pub fn new(db: Db) -> Self {
        Self { db }
    }

    /// Upserts `value` under `key` in `slabs_cache` with a UTC expiration of `now + ttl_seconds`.
    ///
    /// Overwrites any existing value and TTL for `key`. Returns [`SlabError::BadRequest`] if
    /// `ttl_seconds <= 0` or if computing the expiration timestamp overflows.
    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(())
    }

    /// Fetches the string value for `key` from `slabs_cache` when `expires_at > Utc::now()`.
    ///
    /// Returns `Ok(None)` if `key` is absent or expired. Does not delete expired rows.
    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))
    }

    /// Serializes `value` with `serde_json` and upserts it under `key` for `ttl_seconds`.
    ///
    /// Returns [`SlabError::Internal`] if serialization fails.
    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
    }

    /// Fetches a non-expired entry for `key` and deserializes it from JSON.
    ///
    /// Returns `Ok(None)` if `key` is absent or expired, and [`SlabError::Internal`] if JSON decoding fails.
    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))
    }

    /// Deletes the `slabs_cache` row for `key` if it exists.
    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(())
    }

    /// Deletes all `slabs_cache` rows where `expires_at <= Utc::now()` and returns the deleted row count.
    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));
    }
}