pub async fn remember<T, F, Fut>(
key: &str,
ttl: Duration,
f: F,
) -> Result<T, AppError>Expand description
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.
A put failure after f already succeeded is logged, not propagated -
reported directly, from a real production incident: a corrupted SQLite
database (unrelated to this crate - see docs/GOTCHAS.md) made every
put fail while reads/the underlying fetch still worked, and the old
behavior here (a bare put(...).await?) threw away the value f had
already successfully fetched, turning “the cache is broken” into “the
whole feature is down” for the caller - a real API response, already in
hand, discarded over a caching concern that has nothing to do with
whether the fetch itself succeeded. A broken cache should degrade to “no
caching, fetch every time,” never to “no data at all.” Deliberately
asymmetric with get above: a get failure still propagates as-is (see
that function’s own doc comment - it needs to surface a real caller bug,
like a type mismatch against what’s actually stored, not just a broken
backend), so this only changes what happens after f has already
produced a real value to hand back regardless.
Not race-safe under concurrent callers missing on the same key at once -
same accepted tradeoff as this crate’s own
PostController::find_or_create_tag in demo/examples/blog. Both
would run f and both would put; harmless (both drivers’ put is
last-write-wins), just not exactly-once.