rainier_cache/cache.rs
1//! The [`Cache`] port and the conveniences every implementation gets.
2
3use std::time::Duration;
4
5use rainier_support::{BoxFuture, Error, Result};
6use serde::de::DeserializeOwned;
7use serde::Serialize;
8
9/// A key/value store with expiry.
10///
11/// Bytes rather than strings, because the interesting things to cache — a
12/// serialised session, a rendered page, a protobuf — are not all text, and
13/// forcing them through UTF-8 would mean base64 on top of an already-encoded
14/// value.
15///
16/// Every method is fallible and **a miss is not a failure**: `get` returns
17/// `Ok(None)` for an absent key and `Err` only when the cache itself could not
18/// be reached. Conflating the two is how a cache outage becomes an outage.
19pub trait Cache: Send + Sync + 'static {
20 /// A label for diagnostics — `"memory"`, `"redis"`, `"memcached"`.
21 fn name(&self) -> &str;
22
23 /// The value at `key`, or `None` if it is absent or expired.
24 fn get<'a>(&'a self, key: &'a str) -> BoxFuture<'a, Result<Option<Vec<u8>>>>;
25
26 /// Store `value`, expiring after `ttl`. `None` means no expiry.
27 fn put<'a>(
28 &'a self,
29 key: &'a str,
30 value: &'a [u8],
31 ttl: Option<Duration>,
32 ) -> BoxFuture<'a, Result<()>>;
33
34 /// Remove a key. `true` if it was there.
35 fn forget<'a>(&'a self, key: &'a str) -> BoxFuture<'a, Result<bool>>;
36
37 /// Remove everything.
38 ///
39 /// On a shared server this removes **everything in the database**, not just
40 /// this application's keys — which is why [`prefix`](crate::PrefixedCache)
41 /// exists and why this is not something to call on a schedule.
42 fn flush(&self) -> BoxFuture<'_, Result<()>>;
43
44 /// Whether this store is visible to other processes.
45 ///
46 /// The question anything cached **for correctness** has to ask: a lock, a
47 /// rate limit, a "has this webhook been handled" marker. Over a per-process
48 /// store each instance answers from its own copy, which for a lock means
49 /// every instance holds it at once.
50 ///
51 /// Defaults to `true`, because almost every implementation is a server
52 /// somewhere. An in-process one **must** override it — silence here is what
53 /// makes the failure quiet.
54 fn is_shared(&self) -> bool {
55 true
56 }
57
58 /// Whether [`add`](Self::add) is genuinely atomic here.
59 ///
60 /// `true` for everything that can compare-and-set — every driver in this
61 /// crate except Cloudflare Workers KV, which has no such operation at all.
62 ///
63 /// It matters because `add` is the primitive a **lock** is built from. A
64 /// store where two callers can both "win" an `add` cannot hold a lock, and
65 /// the failure is silent: both callers proceed, both believe they are the
66 /// only one, and the report goes out twice. So
67 /// [`LockManager::is_shared`](crate::LockManager::is_shared) requires this
68 /// as well as [`is_shared`](Self::is_shared), which is what makes the
69 /// scheduler refuse rather than trusting an operator to have read the
70 /// driver's documentation.
71 fn supports_atomic_add(&self) -> bool {
72 true
73 }
74
75 /// Whether a key is present and unexpired.
76 fn has<'a>(&'a self, key: &'a str) -> BoxFuture<'a, Result<bool>> {
77 Box::pin(async move { Ok(self.get(key).await?.is_some()) })
78 }
79
80 /// Add `by` to a counter, creating it at zero first. Returns the new value.
81 ///
82 /// Atomic where the driver can be — which is the point of having it on the
83 /// port rather than as a get-then-put in application code, because that
84 /// version loses increments under concurrency.
85 fn increment<'a>(&'a self, key: &'a str, by: i64) -> BoxFuture<'a, Result<i64>>;
86
87 /// Store `value` **only if** `key` is absent. `true` if it was stored.
88 ///
89 /// # This must be atomic
90 ///
91 /// Not "atomic where convenient" — atomic. It is the primitive
92 /// [`Lock`](crate::Lock) is built from, and therefore the primitive behind
93 /// `without_overlapping` and `on_one_server`. A `has` followed by a `put`
94 /// satisfies the signature and satisfies no caller: two processes both see
95 /// the key absent, both write, both believe they hold the lock, and the
96 /// scheduled task runs twice.
97 ///
98 /// It is a **required** method with no default for exactly that reason. A
99 /// default would be inherited silently by the next driver somebody adds,
100 /// and the failure it causes is rare, non-local and expensive.
101 ///
102 /// | Driver | How |
103 /// |---|---|
104 /// | memory | inside the same mutex as the map |
105 /// | Redis | `SET key value NX PX ttl` |
106 /// | Memcached | the `add` command, which is atomic by definition |
107 /// | DynamoDB | `PutItem` with a condition on the key not existing |
108 fn add<'a>(
109 &'a self,
110 key: &'a str,
111 value: &'a [u8],
112 ttl: Option<Duration>,
113 ) -> BoxFuture<'a, Result<bool>>;
114
115 /// Remove `key` **only if** it currently holds `expected`. `true` if it was
116 /// removed.
117 ///
118 /// The other half of a lock, and the half people leave out.
119 ///
120 /// Releasing with a plain [`forget`](Self::forget) is wrong in a way that
121 /// only shows up under load. A holder that stalls past its TTL — a long GC
122 /// pause, a slow query, a suspended VM — has already lost the lock; another
123 /// process has taken it. When the first one finally finishes and deletes
124 /// the key, it deletes *someone else's* lock, and now a third process can
125 /// take it while the second still thinks it holds it.
126 ///
127 /// Comparing the value first closes that. The value is the holder's random
128 /// token, so "is this still mine" has an answer.
129 ///
130 /// Also required, and for the same reason as [`add`](Self::add).
131 fn forget_if<'a>(&'a self, key: &'a str, expected: &'a [u8]) -> BoxFuture<'a, Result<bool>>;
132}
133
134/// The typed conveniences every [`Cache`] gets.
135///
136/// Kept out of the object-safe trait so `Arc<dyn Cache>` still exists.
137#[async_trait::async_trait]
138pub trait CacheExt: Cache {
139 /// A value, deserialised from JSON.
140 async fn get_json<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>> {
141 match self.get(key).await? {
142 Some(bytes) => match serde_json::from_slice(&bytes) {
143 Ok(value) => Ok(Some(value)),
144 Err(e) => {
145 // A cached value we cannot parse is a value from an older
146 // shape of the application. Treating it as a miss lets the
147 // caller recompute; failing would make a deploy poison
148 // every request until the cache expired.
149 tracing::warn!(key, error = %e, "discarding an unreadable cached value");
150 Ok(None)
151 }
152 },
153 None => Ok(None),
154 }
155 }
156
157 /// Store a value as JSON.
158 async fn put_json<T: Serialize + Sync>(
159 &self,
160 key: &str,
161 value: &T,
162 ttl: Option<Duration>,
163 ) -> Result<()> {
164 let bytes = serde_json::to_vec(value)?;
165 self.put(key, &bytes, ttl).await
166 }
167
168 /// A string value.
169 async fn get_string(&self, key: &str) -> Result<Option<String>> {
170 match self.get(key).await? {
171 Some(bytes) => Ok(String::from_utf8(bytes).ok()),
172 None => Ok(None),
173 }
174 }
175
176 /// Store a string.
177 async fn put_string(&self, key: &str, value: &str, ttl: Option<Duration>) -> Result<()> {
178 self.put(key, value.as_bytes(), ttl).await
179 }
180
181 /// Store a string only if the key is absent.
182 ///
183 /// [`Cache::add`] with the encoding done for you. Atomic, like the method
184 /// it calls.
185 async fn add_string(&self, key: &str, value: &str, ttl: Option<Duration>) -> Result<bool> {
186 self.add(key, value.as_bytes(), ttl).await
187 }
188
189 /// Subtract from a counter.
190 async fn decrement(&self, key: &str, by: i64) -> Result<i64> {
191 self.increment(key, -by).await
192 }
193
194 /// The cached value at `key`, or `compute` it and cache that.
195 ///
196 /// The pattern nearly every cache use is, written once:
197 ///
198 /// ```ignore
199 /// let settings: Settings = cache
200 /// .remember("settings", Some(Duration::from_secs(300)), || async {
201 /// load_settings(&database).await
202 /// })
203 /// .await?;
204 /// ```
205 ///
206 /// # A failure is never cached
207 ///
208 /// If `compute` returns an error, the error is returned and **nothing is
209 /// stored**. Caching a failure for five minutes turns one bad second into
210 /// five bad minutes, and the request that would have succeeded never gets
211 /// to try. Cache a *value*; let the next caller retry.
212 ///
213 /// A cached value that will not deserialise is treated as a miss and
214 /// recomputed — see [`get_json`](Self::get_json).
215 ///
216 /// # It is not a lock
217 ///
218 /// Ten simultaneous misses run `compute` ten times and the last write
219 /// wins. That is the right trade for a cache: serialising them would mean
220 /// nine requests waiting on a lock held by a tenth that might fail. When
221 /// the computation is expensive enough that a stampede matters, take a
222 /// [`Lock`](crate::Lock) around it explicitly.
223 async fn remember<T, F, Fut>(&self, key: &str, ttl: Option<Duration>, compute: F) -> Result<T>
224 where
225 T: Serialize + DeserializeOwned + Sync + Send,
226 F: FnOnce() -> Fut + Send,
227 Fut: std::future::Future<Output = Result<T>> + Send,
228 {
229 if let Some(cached) = self.get_json::<T>(key).await? {
230 return Ok(cached);
231 }
232
233 let value = compute().await?;
234
235 // A cache that cannot be written to is a slow application, not a
236 // broken one — the value in hand is still the right answer.
237 if let Err(e) = self.put_json(key, &value, ttl).await {
238 tracing::warn!(key, error = %e.message(), "could not cache a computed value");
239 }
240
241 Ok(value)
242 }
243
244 /// [`remember`](Self::remember), with no expiry.
245 ///
246 /// For something that changes only when the
247 /// application says so — and which therefore needs
248 /// [`forget`](Cache::forget) somewhere, or it is a leak with a nice name.
249 async fn remember_forever<T, F, Fut>(&self, key: &str, compute: F) -> Result<T>
250 where
251 T: Serialize + DeserializeOwned + Sync + Send,
252 F: FnOnce() -> Fut + Send,
253 Fut: std::future::Future<Output = Result<T>> + Send,
254 {
255 self.remember(key, None, compute).await
256 }
257}
258
259impl<C: Cache + ?Sized> CacheExt for C {}
260
261/// Encode a counter for storage.
262///
263/// Decimal text rather than little-endian bytes, so a counter set by Rainier
264/// reads the same as one set by `redis-cli INCR` — and so `INCR` works on it at
265/// all, since Redis parses the stored string.
266pub(crate) fn encode_counter(value: i64) -> Vec<u8> {
267 value.to_string().into_bytes()
268}
269
270/// Decode a counter, treating anything unparseable as zero.
271pub(crate) fn decode_counter(bytes: &[u8]) -> Result<i64> {
272 if bytes.is_empty() {
273 return Ok(0);
274 }
275 std::str::from_utf8(bytes)
276 .ok()
277 .and_then(|text| text.trim().parse::<i64>().ok())
278 .ok_or_else(|| Error::internal("the cached value is not a counter"))
279}
280
281#[cfg(test)]
282mod tests {
283 use super::*;
284
285 #[test]
286 fn counters_round_trip_as_decimal_text() {
287 for value in [0i64, 1, -1, i64::MAX, i64::MIN] {
288 assert_eq!(decode_counter(&encode_counter(value)).unwrap(), value);
289 }
290 assert_eq!(encode_counter(42), b"42".to_vec(), "readable by redis-cli");
291 }
292
293 #[test]
294 fn an_empty_value_counts_as_zero() {
295 assert_eq!(decode_counter(b"").unwrap(), 0);
296 }
297
298 #[test]
299 fn a_non_counter_is_an_error_rather_than_zero() {
300 // Silently treating "hello" as 0 would let an increment overwrite an
301 // unrelated value.
302 assert!(decode_counter(b"hello").is_err());
303 }
304
305 #[tokio::test]
306 async fn remember_computes_once_and_then_reads_the_cache() {
307 use crate::MemoryCache;
308 use std::sync::atomic::{AtomicUsize, Ordering};
309 use std::sync::Arc;
310
311 let cache = MemoryCache::new();
312 let calls = Arc::new(AtomicUsize::new(0));
313
314 for _ in 0..3 {
315 let calls = Arc::clone(&calls);
316 let value: String = cache
317 .remember("settings", None, || async move {
318 calls.fetch_add(1, Ordering::SeqCst);
319 Ok("computed".to_string())
320 })
321 .await
322 .unwrap();
323
324 assert_eq!(value, "computed");
325 }
326
327 assert_eq!(calls.load(Ordering::SeqCst), 1, "it recomputed a value it already had");
328 }
329
330 #[tokio::test]
331 async fn remember_does_not_cache_a_failure() {
332 // The whole point. Caching an error for five minutes turns one bad
333 // second into five bad minutes, and the request that would have
334 // succeeded never gets to try.
335 use crate::MemoryCache;
336
337 let cache = MemoryCache::new();
338
339 let failed: Result<String> = cache
340 .remember("thing", None, || async { Err(Error::internal("upstream is down")) })
341 .await;
342 assert!(failed.is_err());
343
344 assert!(cache.get("thing").await.unwrap().is_none(), "the failure was cached");
345
346 // And the next caller gets to succeed.
347 let recovered: String = cache
348 .remember("thing", None, || async { Ok("it works now".to_string()) })
349 .await
350 .unwrap();
351 assert_eq!(recovered, "it works now");
352 }
353
354 #[tokio::test]
355 async fn remember_recomputes_a_value_it_can_no_longer_read() {
356 // A deploy changed the shape of the cached type. Treating that as a
357 // miss is what stops one deploy poisoning every request until the TTL.
358 use crate::MemoryCache;
359
360 let cache = MemoryCache::new();
361 cache.put("count", b"\"not a number\"", None).await.unwrap();
362
363 let count: u32 = cache.remember("count", None, || async { Ok(7) }).await.unwrap();
364 assert_eq!(count, 7);
365 }
366}