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/// Returns the cached value under `key` if present and unexpired;
65/// otherwise calls `f`, stores its result under `key` for `ttl`, and
66/// returns it. `f` is a plain generic closure, not a trait method, so
67/// there's no async-fn-in-traits `Send` pitfall to work around here (see
68/// `docs/GOTCHAS.md`). Implemented purely in terms of `get`/`put` above,
69/// so it needs no driver-specific logic of its own.
70///
71/// A `put` failure after `f` already succeeded is logged, not propagated -
72/// reported directly, from a real production incident: a corrupted SQLite
73/// database (unrelated to this crate - see `docs/GOTCHAS.md`) made every
74/// `put` fail while reads/the underlying fetch still worked, and the old
75/// behavior here (a bare `put(...).await?`) threw away the value `f` had
76/// *already successfully fetched*, turning "the cache is broken" into "the
77/// whole feature is down" for the caller - a real API response, already in
78/// hand, discarded over a caching concern that has nothing to do with
79/// whether the fetch itself succeeded. A broken cache should degrade to "no
80/// caching, fetch every time," never to "no data at all." Deliberately
81/// asymmetric with `get` above: a `get` failure still propagates as-is (see
82/// that function's own doc comment - it needs to surface a real caller bug,
83/// like a type mismatch against what's actually stored, not just a broken
84/// backend), so this only changes what happens *after* `f` has already
85/// produced a real value to hand back regardless.
86///
87/// Not race-safe under concurrent callers missing on the same key at once -
88/// same accepted tradeoff as this crate's own
89/// `PostController::find_or_create_tag` in `demo`/`examples/blog`. Both
90/// would run `f` and both would `put`; harmless (both drivers' `put` is
91/// last-write-wins), just not exactly-once.
92pub async fn remember<T, F, Fut>(key: &str, ttl: Duration, f: F) -> Result<T, AppError>
93where
94 T: Serialize + DeserializeOwned,
95 F: FnOnce() -> Fut,
96 Fut: Future<Output = Result<T, AppError>>,
97{
98 if let Some(value) = get::<T>(key).await? {
99 return Ok(value);
100 }
101
102 let value = f().await?;
103 if let Err(error) = put(key, &value, ttl).await {
104 tracing::warn!(
105 %error,
106 key,
107 "failed to cache a freshly-fetched value - returning it uncached instead of failing \
108 the whole request"
109 );
110 }
111 Ok(value)
112}
113
114#[cfg(test)]
115mod tests {
116 use super::*;
117
118 async fn connect_test_db() {
119 let dir = tempfile::tempdir().unwrap().keep();
120 let database_url = format!("sqlite://{}/test.sqlite", dir.display());
121 larust_orm::connect(&database_url).await.unwrap();
122 }
123
124 /// No `Application::new()` call anywhere in this test - proves
125 /// `put`/`get`/`forget`/`remember` still work with no published
126 /// `Config` at all (the `"database"` driver, via `cache_driver()`'s
127 /// own fallback), the same guarantee this crate has always given,
128 /// unaffected by Redis support existing now.
129 #[tokio::test]
130 async fn cache_round_trips_through_the_database_driver_with_no_published_config() {
131 connect_test_db().await;
132
133 put("greeting", &"hello", Duration::from_secs(60))
134 .await
135 .unwrap();
136 let value: Option<String> = get("greeting").await.unwrap();
137 assert_eq!(value, Some("hello".to_string()));
138
139 forget("greeting").await.unwrap();
140 let value: Option<String> = get("greeting").await.unwrap();
141 assert_eq!(value, None);
142
143 let remembered = remember("computed", Duration::from_secs(60), || async {
144 Ok::<_, AppError>("computed value".to_string())
145 })
146 .await
147 .unwrap();
148 assert_eq!(remembered, "computed value");
149
150 // The actual regression guard for the real production incident
151 // `remember`'s own doc comment describes: a `put` failure after `f`
152 // already succeeded must not throw away the value `f` fetched. A
153 // type whose `Serialize` impl always errors exercises the exact
154 // same `put(...).await` failure `remember` has to handle -
155 // `remember`'s own logic doesn't care *why* `put` failed (a
156 // corrupted database in the real incident, a serialization bug
157 // here), only that it must still hand back what `f` already
158 // produced rather than propagating the error and losing it.
159 struct AlwaysFailsToSerialize;
160
161 impl serde::Serialize for AlwaysFailsToSerialize {
162 fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
163 where
164 S: serde::Serializer,
165 {
166 Err(serde::ser::Error::custom("deliberate failure for the test"))
167 }
168 }
169
170 impl<'de> serde::Deserialize<'de> for AlwaysFailsToSerialize {
171 // Never actually exercised: `remember` only reaches `get`
172 // *before* calling `f`, against a key nothing has ever `put`
173 // under, so there's no stored JSON to decode - this impl exists
174 // purely to satisfy `T: DeserializeOwned`.
175 fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error>
176 where
177 D: serde::Deserializer<'de>,
178 {
179 Ok(AlwaysFailsToSerialize)
180 }
181 }
182
183 let result = remember("uncacheable", Duration::from_secs(60), || async {
184 Ok::<_, AppError>(AlwaysFailsToSerialize)
185 })
186 .await;
187 assert!(
188 result.is_ok(),
189 "remember must return the freshly-fetched value even when caching it fails, got: \
190 {:?}",
191 result.err()
192 );
193 }
194}