larust_cache/store.rs
1//! Laravel's `Cache::put()`/`get()`/`forget()`/`remember()` - dispatches
2//! to [`crate::sql_store`] (the default, `Config::cache_driver ==
3//! "database"`) or [`crate::redis_store`] (`"redis"`) at each call,
4//! mirroring `larust_mail::send::deliver`'s own `match config.mail_driver
5//! .as_str() { ... }` shape - the one existing "a config string picks a
6//! runtime code path" precedent in this codebase. Neither backend module
7//! is reachable from outside this crate (both `pub(crate)`); every public
8//! signature here is unchanged from before Redis support existed, so
9//! nothing about *using* this crate depends on which driver is active.
10
11use larust_core::AppError;
12use serde::de::DeserializeOwned;
13use serde::Serialize;
14use std::future::Future;
15use std::time::Duration;
16
17/// Uses `larust_core::try_config()`, not `config()` - this crate's own
18/// functions have never required `Application::new()` to have run first
19/// (they only ever needed `larust_orm::connect()`), and some callers
20/// (narrow test helpers building a bare pool directly, matching
21/// `larust_http::session::cookie_name()`'s own identical reasoning) still
22/// don't call it. Falling back to `"database"` (the same default
23/// `Config::cache_driver` itself has) when no config has been published
24/// yet keeps this a purely additive change rather than a new panic path
25/// for code that worked before Redis support existed.
26fn cache_driver() -> &'static str {
27 larust_core::try_config()
28 .map(|config| config.cache_driver.as_str())
29 .unwrap_or("database")
30}
31
32/// Stores `value` under `key`, serialized as JSON, expiring after `ttl`.
33/// Overwrites any existing entry under the same key (Laravel's own `put()`
34/// semantics - not an error to reuse a key).
35pub async fn put<T: Serialize>(key: &str, value: &T, ttl: Duration) -> Result<(), AppError> {
36 match cache_driver() {
37 "redis" => crate::redis_store::put(key, value, ttl).await,
38 _ => crate::sql_store::put(key, value, ttl).await,
39 }
40}
41
42/// Returns `Ok(None)` for a missing or expired key (an ordinary cache
43/// miss). A key that exists but whose stored JSON can't be coerced into
44/// `T` - e.g. reading a key back with an incompatible type than it was
45/// `put` with - is a caller bug, not a miss, so it surfaces as
46/// `Err(AppError::Internal)` rather than silently degrading to `None` the
47/// way Laravel's own cache would.
48pub async fn get<T: DeserializeOwned>(key: &str) -> Result<Option<T>, AppError> {
49 match cache_driver() {
50 "redis" => crate::redis_store::get(key).await,
51 _ => crate::sql_store::get(key).await,
52 }
53}
54
55/// Removes `key`, if present. Not an error to forget a key that was never
56/// set or has already expired.
57pub async fn forget(key: &str) -> Result<(), AppError> {
58 match cache_driver() {
59 "redis" => crate::redis_store::forget(key).await,
60 _ => crate::sql_store::forget(key).await,
61 }
62}
63
64/// Unconditionally sweeps every expired entry, regardless of traffic -
65/// unlike the opportunistic sweep `get`/`put` already do inline (gated to
66/// once every five minutes, and only ever triggered by a real call), this
67/// runs even if the app has had no cache traffic at all since the last
68/// sweep. Intended for a periodic scheduled caller (see
69/// `larust_support::maintenance::clean`), not request-path code. A no-op
70/// for the `"redis"` driver - Redis's own native key TTL already expires
71/// entries with zero application-level bookkeeping needed.
72pub async fn sweep_expired() -> Result<(), AppError> {
73 match cache_driver() {
74 "redis" => Ok(()),
75 _ => crate::sql_store::sweep_expired(larust_orm::pool()?).await,
76 }
77}
78
79/// Returns the cached value under `key` if present and unexpired;
80/// otherwise calls `f`, stores its result under `key` for `ttl`, and
81/// returns it. `f` is a plain generic closure, not a trait method, so
82/// there's no async-fn-in-traits `Send` pitfall to work around here (see
83/// `docs/GOTCHAS.md`). Implemented purely in terms of `get`/`put` above,
84/// so it needs no driver-specific logic of its own.
85///
86/// A `put` failure after `f` already succeeded is logged, not propagated -
87/// reported directly, from a real production incident: a corrupted SQLite
88/// database (unrelated to this crate - see `docs/GOTCHAS.md`) made every
89/// `put` fail while reads/the underlying fetch still worked, and the old
90/// behavior here (a bare `put(...).await?`) threw away the value `f` had
91/// *already successfully fetched*, turning "the cache is broken" into "the
92/// whole feature is down" for the caller - a real API response, already in
93/// hand, discarded over a caching concern that has nothing to do with
94/// whether the fetch itself succeeded. A broken cache should degrade to "no
95/// caching, fetch every time," never to "no data at all." Deliberately
96/// asymmetric with `get` above: a `get` failure still propagates as-is (see
97/// that function's own doc comment - it needs to surface a real caller bug,
98/// like a type mismatch against what's actually stored, not just a broken
99/// backend), so this only changes what happens *after* `f` has already
100/// produced a real value to hand back regardless.
101///
102/// Not race-safe under concurrent callers missing on the same key at once -
103/// same accepted tradeoff as this crate's own
104/// `PostController::find_or_create_tag` in `demo`/`examples/blog`. Both
105/// would run `f` and both would `put`; harmless (both drivers' `put` is
106/// last-write-wins), just not exactly-once.
107pub async fn remember<T, F, Fut>(key: &str, ttl: Duration, f: F) -> Result<T, AppError>
108where
109 T: Serialize + DeserializeOwned,
110 F: FnOnce() -> Fut,
111 Fut: Future<Output = Result<T, AppError>>,
112{
113 if let Some(value) = get::<T>(key).await? {
114 return Ok(value);
115 }
116
117 let value = f().await?;
118 if let Err(error) = put(key, &value, ttl).await {
119 tracing::warn!(
120 %error,
121 key,
122 "failed to cache a freshly-fetched value - returning it uncached instead of failing \
123 the whole request"
124 );
125 }
126 Ok(value)
127}
128
129#[cfg(test)]
130mod tests {
131 use super::*;
132
133 async fn connect_test_db() {
134 let dir = tempfile::tempdir().unwrap().keep();
135 let database_url = format!("sqlite://{}/test.sqlite", dir.display());
136 larust_orm::connect(&database_url).await.unwrap();
137 }
138
139 /// No `Application::new()` call anywhere in this test - proves
140 /// `put`/`get`/`forget`/`remember` still work with no published
141 /// `Config` at all (the `"database"` driver, via `cache_driver()`'s
142 /// own fallback), the same guarantee this crate has always given,
143 /// unaffected by Redis support existing now.
144 #[tokio::test]
145 async fn cache_round_trips_through_the_database_driver_with_no_published_config() {
146 connect_test_db().await;
147
148 put("greeting", &"hello", Duration::from_secs(60))
149 .await
150 .unwrap();
151 let value: Option<String> = get("greeting").await.unwrap();
152 assert_eq!(value, Some("hello".to_string()));
153
154 forget("greeting").await.unwrap();
155 let value: Option<String> = get("greeting").await.unwrap();
156 assert_eq!(value, None);
157
158 let remembered = remember("computed", Duration::from_secs(60), || async {
159 Ok::<_, AppError>("computed value".to_string())
160 })
161 .await
162 .unwrap();
163 assert_eq!(remembered, "computed value");
164
165 // The actual regression guard for the real production incident
166 // `remember`'s own doc comment describes: a `put` failure after `f`
167 // already succeeded must not throw away the value `f` fetched. A
168 // type whose `Serialize` impl always errors exercises the exact
169 // same `put(...).await` failure `remember` has to handle -
170 // `remember`'s own logic doesn't care *why* `put` failed (a
171 // corrupted database in the real incident, a serialization bug
172 // here), only that it must still hand back what `f` already
173 // produced rather than propagating the error and losing it.
174 struct AlwaysFailsToSerialize;
175
176 impl serde::Serialize for AlwaysFailsToSerialize {
177 fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
178 where
179 S: serde::Serializer,
180 {
181 Err(serde::ser::Error::custom("deliberate failure for the test"))
182 }
183 }
184
185 impl<'de> serde::Deserialize<'de> for AlwaysFailsToSerialize {
186 // Never actually exercised: `remember` only reaches `get`
187 // *before* calling `f`, against a key nothing has ever `put`
188 // under, so there's no stored JSON to decode - this impl exists
189 // purely to satisfy `T: DeserializeOwned`.
190 fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error>
191 where
192 D: serde::Deserializer<'de>,
193 {
194 Ok(AlwaysFailsToSerialize)
195 }
196 }
197
198 let result = remember("uncacheable", Duration::from_secs(60), || async {
199 Ok::<_, AppError>(AlwaysFailsToSerialize)
200 })
201 .await;
202 assert!(
203 result.is_ok(),
204 "remember must return the freshly-fetched value even when caching it fails, got: \
205 {:?}",
206 result.err()
207 );
208 }
209}