Skip to main content

Crate larust_cache

Crate larust_cache 

Source
Expand description

A single cache, keyed by string, values serialized as JSON - backed by SQL-family storage (Config::cache_driver == "database", the default) or Redis ("redis"), chosen at each call by [store]’s own dispatch. See [sql_store]/[redis_store] for the two implementations, and store.rs’s own doc comment for the dispatch shape.

Deliberately ships no in-memory driver - mirroring larust_http::session’s own “no in-memory option in the public API” stance (an in-memory cache is the same trap: it “works” in every manual test, then silently starts missing on every deploy/restart). Laravel’s own default (CACHE_STORE=database since Laravel 11) points the same direction - the "redis" option here mirrors Laravel’s other common production choice, not an in-memory one.

Functions§

forget
Removes key, if present. Not an error to forget a key that was never set or has already expired.
get
Returns Ok(None) for a missing or expired key (an ordinary cache miss). A key that exists but whose stored JSON can’t be coerced into T - e.g. reading a key back with an incompatible type than it was put with - is a caller bug, not a miss, so it surfaces as Err(AppError::Internal) rather than silently degrading to None the way Laravel’s own cache would.
put
Stores value under key, serialized as JSON, expiring after ttl. Overwrites any existing entry under the same key (Laravel’s own put() semantics - not an error to reuse a key).
remember
Returns the cached value under key if present and unexpired; otherwise calls f, stores its result under key for ttl, and returns it. f is a plain generic closure, not a trait method, so there’s no async-fn-in-traits Send pitfall to work around here (see docs/GOTCHAS.md). Implemented purely in terms of get/put above, so it needs no driver-specific logic of its own.
sweep_expired
Unconditionally sweeps every expired entry, regardless of traffic - unlike the opportunistic sweep get/put already do inline (gated to once every five minutes, and only ever triggered by a real call), this runs even if the app has had no cache traffic at all since the last sweep. Intended for a periodic scheduled caller (see larust_support::maintenance::clean), not request-path code. A no-op for the "redis" driver - Redis’s own native key TTL already expires entries with zero application-level bookkeeping needed.