Skip to main content

slabs_cache/
lib.rs

1//! `SQLite`-backed TTL key-value cache for Slabs applications.
2//!
3//! This crate owns [`Cache`], which stores string and JSON entries in the `slabs_cache` system table
4//! with no external cache daemon.
5//!
6//! # Database table
7//!
8//! [`Cache`] reads and writes the `slabs_cache` table created by [`slabs_db::Db::init_system_tables`]:
9//!
10//! - `cache_key TEXT PRIMARY KEY NOT NULL`
11//! - `value_text TEXT NOT NULL`
12//! - `expires_at TEXT NOT NULL` (UTC RFC 3339 timestamp, indexed by `idx_slabs_cache_expires_at`)
13//! - `updated_at TEXT NOT NULL` (UTC RFC 3339 timestamp)
14//!
15//! # Invariants
16//!
17//! - **Strict read-time TTL check**: [`Cache::get`] and [`Cache::get_json`] filter with `expires_at > now` (UTC RFC 3339). Expired rows return `Ok(None)` immediately.
18//! - **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`].
19//! - **Non-positive TTL**: passing `ttl_seconds <= 0` stores a timestamp at or before `now`, so subsequent reads return `Ok(None)`.
20//! - **Pool usage**: all cache operations execute against `db.pool()` (the writer pool), keeping writes and immediate reads serialized.
21//! - **JSON errors**: [`Cache::set_json`] and [`Cache::get_json`] return [`SlabError::Internal`] if `serde_json` fails.
22//!
23//! # Usage
24//!
25//! ```rust,no_run
26//! use serde::{Deserialize, Serialize};
27//! use slabs_cache::Cache;
28//! use slabs_core::SlabResult;
29//! use slabs_db::Db;
30//!
31//! #[derive(Serialize, Deserialize)]
32//! struct RoomStats {
33//!     members: u64,
34//! }
35//!
36//! async fn example(db: Db) -> SlabResult<()> {
37//!     let cache = Cache::new(db);
38//!     cache.set("banner", "maintenance at 02:00 UTC", 300).await?;
39//!     let _banner: Option<String> = cache.get("banner").await?;
40//!
41//!     cache
42//!         .set_json("room:1:stats", &RoomStats { members: 12 }, 60)
43//!         .await?;
44//!     let _stats: Option<RoomStats> = cache.get_json("room:1:stats").await?;
45//!
46//!     let _removed = cache.purge_expired().await?;
47//!     Ok(())
48//! }
49//! ```
50
51use chrono::{Duration, Utc};
52use serde::{de::DeserializeOwned, Serialize};
53use slabs_core::{SlabError, SlabResult};
54use slabs_db::Db;
55
56/// `SQLite`-backed TTL key-value cache reading and writing the `slabs_cache` table.
57///
58/// Requires [`slabs_db::Db::init_system_tables`] (or [`slabs_db::Db::migrate`]) before use.
59#[derive(Debug, Clone)]
60pub struct Cache {
61    db: Db,
62}
63
64impl Cache {
65    /// Creates a [`Cache`] backed by the given [`Db`] handle.
66    #[must_use]
67    pub fn new(db: Db) -> Self {
68        Self { db }
69    }
70
71    /// Upserts `value` under `key` in `slabs_cache` with a UTC expiration of `now + ttl_seconds`.
72    ///
73    /// Overwrites any existing value and TTL for `key`.
74    pub async fn set(&self, key: &str, value: &str, ttl_seconds: i64) -> SlabResult<()> {
75        let now = Utc::now();
76        let expires_at = (now + Duration::seconds(ttl_seconds)).to_rfc3339();
77        let updated_at = now.to_rfc3339();
78
79        sqlx::query(
80            "INSERT INTO slabs_cache (cache_key, value_text, expires_at, updated_at)
81             VALUES (?, ?, ?, ?)
82             ON CONFLICT(cache_key) DO UPDATE SET
83               value_text = excluded.value_text,
84               expires_at = excluded.expires_at,
85               updated_at = excluded.updated_at",
86        )
87        .bind(key)
88        .bind(value)
89        .bind(&expires_at)
90        .bind(&updated_at)
91        .execute(self.db.pool())
92        .await?;
93
94        Ok(())
95    }
96
97    /// Fetches the string value for `key` from `slabs_cache` when `expires_at > Utc::now()`.
98    ///
99    /// Returns `Ok(None)` if `key` is absent or expired. Does not delete expired rows.
100    pub async fn get(&self, key: &str) -> SlabResult<Option<String>> {
101        let now_str = Utc::now().to_rfc3339();
102        let row: Option<(String,)> = sqlx::query_as(
103            "SELECT value_text FROM slabs_cache WHERE cache_key = ? AND expires_at > ?",
104        )
105        .bind(key)
106        .bind(&now_str)
107        .fetch_optional(self.db.pool())
108        .await?;
109
110        Ok(row.map(|(v,)| v))
111    }
112
113    /// Serializes `value` with `serde_json` and upserts it under `key` for `ttl_seconds`.
114    ///
115    /// Returns [`SlabError::Internal`] if serialization fails.
116    pub async fn set_json<T: Serialize>(
117        &self,
118        key: &str,
119        value: &T,
120        ttl_seconds: i64,
121    ) -> SlabResult<()> {
122        let json = serde_json::to_string(value)
123            .map_err(|e| SlabError::internal(format!("cache serialize failed: {e}")))?;
124        self.set(key, &json, ttl_seconds).await
125    }
126
127    /// Fetches a non-expired entry for `key` and deserializes it from JSON.
128    ///
129    /// Returns `Ok(None)` if `key` is absent or expired, and [`SlabError::Internal`] if JSON decoding fails.
130    pub async fn get_json<T: DeserializeOwned>(&self, key: &str) -> SlabResult<Option<T>> {
131        let Some(raw) = self.get(key).await? else {
132            return Ok(None);
133        };
134        let parsed = serde_json::from_str(&raw)
135            .map_err(|e| SlabError::internal(format!("cache deserialize failed: {e}")))?;
136        Ok(Some(parsed))
137    }
138
139    /// Deletes the `slabs_cache` row for `key` if it exists.
140    pub async fn delete(&self, key: &str) -> SlabResult<()> {
141        sqlx::query("DELETE FROM slabs_cache WHERE cache_key = ?")
142            .bind(key)
143            .execute(self.db.pool())
144            .await?;
145        Ok(())
146    }
147
148    /// Deletes all `slabs_cache` rows where `expires_at <= Utc::now()` and returns the deleted row count.
149    pub async fn purge_expired(&self) -> SlabResult<u64> {
150        let now_str = Utc::now().to_rfc3339();
151        let res = sqlx::query("DELETE FROM slabs_cache WHERE expires_at <= ?")
152            .bind(&now_str)
153            .execute(self.db.pool())
154            .await?;
155        Ok(res.rows_affected())
156    }
157}