Expand description
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 NULLvalue_text TEXT NOT NULLexpires_at TEXT NOT NULL(UTC RFC 3339 timestamp, indexed byidx_slabs_cache_expires_at)updated_at TEXT NOT NULL(UTC RFC 3339 timestamp)
§Invariants
- Strict read-time TTL check:
Cache::getandCache::get_jsonfilter withexpires_at > now(UTC RFC 3339). Expired rows returnOk(None)immediately. - Lazy row cleanup: expired rows stay in
slabs_cacheuntil overwritten byCache::setorCache::set_json, removed byCache::delete, or swept byCache::purge_expired. - Non-positive TTL: passing
ttl_seconds <= 0stores a timestamp at or beforenow, so subsequent reads returnOk(None). - Pool usage: all cache operations execute against
db.pool()(the writer pool), keeping writes and immediate reads serialized. - JSON errors:
Cache::set_jsonandCache::get_jsonreturnSlabError::Internalifserde_jsonfails.
§Usage
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(())
}Structs§
- Cache
SQLite-backed TTL key-value cache reading and writing theslabs_cachetable.