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` (fixed-width UTC RFC 3339 microseconds). 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//! - **Positive TTL required**: passing `ttl_seconds <= 0` or an overflowing TTL returns [`SlabError::BadRequest`].
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, SecondsFormat, Utc};
52use serde::{de::DeserializeOwned, Serialize};
53use slabs_core::{SlabError, SlabResult};
54use slabs_db::Db;
55
56fn format_utc_timestamp(dt: chrono::DateTime<Utc>) -> String {
57 dt.to_rfc3339_opts(SecondsFormat::Micros, true)
58}
59
60fn compute_expiry(now: chrono::DateTime<Utc>, ttl_seconds: i64) -> SlabResult<String> {
61 if ttl_seconds <= 0 {
62 return Err(SlabError::bad_request(
63 "cache ttl_seconds must be greater than zero",
64 ));
65 }
66 let delta = Duration::try_seconds(ttl_seconds)
67 .ok_or_else(|| SlabError::bad_request("cache ttl_seconds overflow"))?;
68 let expires = now
69 .checked_add_signed(delta)
70 .ok_or_else(|| SlabError::bad_request("cache ttl_seconds overflow"))?;
71 Ok(format_utc_timestamp(expires))
72}
73
74/// `SQLite`-backed TTL key-value cache reading and writing the `slabs_cache` table.
75///
76/// Requires [`slabs_db::Db::init_system_tables`] (or [`slabs_db::Db::migrate`]) before use.
77#[derive(Debug, Clone)]
78pub struct Cache {
79 db: Db,
80}
81
82impl Cache {
83 /// Creates a [`Cache`] backed by the given [`Db`] handle.
84 #[must_use]
85 pub fn new(db: Db) -> Self {
86 Self { db }
87 }
88
89 /// Upserts `value` under `key` in `slabs_cache` with a UTC expiration of `now + ttl_seconds`.
90 ///
91 /// Overwrites any existing value and TTL for `key`. Returns [`SlabError::BadRequest`] if
92 /// `ttl_seconds <= 0` or if computing the expiration timestamp overflows.
93 pub async fn set(&self, key: &str, value: &str, ttl_seconds: i64) -> SlabResult<()> {
94 let now = Utc::now();
95 let expires_at = compute_expiry(now, ttl_seconds)?;
96 let updated_at = format_utc_timestamp(now);
97
98 sqlx::query(
99 "INSERT INTO slabs_cache (cache_key, value_text, expires_at, updated_at)
100 VALUES (?, ?, ?, ?)
101 ON CONFLICT(cache_key) DO UPDATE SET
102 value_text = excluded.value_text,
103 expires_at = excluded.expires_at,
104 updated_at = excluded.updated_at",
105 )
106 .bind(key)
107 .bind(value)
108 .bind(&expires_at)
109 .bind(&updated_at)
110 .execute(self.db.pool())
111 .await?;
112
113 Ok(())
114 }
115
116 /// Fetches the string value for `key` from `slabs_cache` when `expires_at > Utc::now()`.
117 ///
118 /// Returns `Ok(None)` if `key` is absent or expired. Does not delete expired rows.
119 pub async fn get(&self, key: &str) -> SlabResult<Option<String>> {
120 let now_str = format_utc_timestamp(Utc::now());
121 let row: Option<(String,)> = sqlx::query_as(
122 "SELECT value_text FROM slabs_cache WHERE cache_key = ? AND expires_at > ?",
123 )
124 .bind(key)
125 .bind(&now_str)
126 .fetch_optional(self.db.pool())
127 .await?;
128
129 Ok(row.map(|(v,)| v))
130 }
131
132 /// Serializes `value` with `serde_json` and upserts it under `key` for `ttl_seconds`.
133 ///
134 /// Returns [`SlabError::Internal`] if serialization fails.
135 pub async fn set_json<T: Serialize>(
136 &self,
137 key: &str,
138 value: &T,
139 ttl_seconds: i64,
140 ) -> SlabResult<()> {
141 let json = serde_json::to_string(value)
142 .map_err(|e| SlabError::internal(format!("cache serialize failed: {e}")))?;
143 self.set(key, &json, ttl_seconds).await
144 }
145
146 /// Fetches a non-expired entry for `key` and deserializes it from JSON.
147 ///
148 /// Returns `Ok(None)` if `key` is absent or expired, and [`SlabError::Internal`] if JSON decoding fails.
149 pub async fn get_json<T: DeserializeOwned>(&self, key: &str) -> SlabResult<Option<T>> {
150 let Some(raw) = self.get(key).await? else {
151 return Ok(None);
152 };
153 let parsed = serde_json::from_str(&raw)
154 .map_err(|e| SlabError::internal(format!("cache deserialize failed: {e}")))?;
155 Ok(Some(parsed))
156 }
157
158 /// Deletes the `slabs_cache` row for `key` if it exists.
159 pub async fn delete(&self, key: &str) -> SlabResult<()> {
160 sqlx::query("DELETE FROM slabs_cache WHERE cache_key = ?")
161 .bind(key)
162 .execute(self.db.pool())
163 .await?;
164 Ok(())
165 }
166
167 /// Deletes all `slabs_cache` rows where `expires_at <= Utc::now()` and returns the deleted row count.
168 pub async fn purge_expired(&self) -> SlabResult<u64> {
169 let now_str = format_utc_timestamp(Utc::now());
170 let res = sqlx::query("DELETE FROM slabs_cache WHERE expires_at <= ?")
171 .bind(&now_str)
172 .execute(self.db.pool())
173 .await?;
174 Ok(res.rows_affected())
175 }
176}
177
178#[cfg(test)]
179mod tests {
180 use super::*;
181
182 #[test]
183 fn rejects_non_positive_and_overflow_ttl() {
184 let now = Utc::now();
185 assert!(compute_expiry(now, 0).is_err());
186 assert!(compute_expiry(now, -10).is_err());
187 assert!(compute_expiry(now, i64::MAX).is_err());
188 }
189
190 #[test]
191 fn formats_fixed_width_microsecond_rfc3339_timestamps() {
192 let now = Utc::now();
193 let ts = compute_expiry(now, 60).unwrap();
194 assert_eq!(ts.len(), 27);
195 assert!(ts.ends_with('Z'));
196 assert!(ts > format_utc_timestamp(now));
197 }
198}