claviron_cache/store.rs
1use std::any::Any;
2use std::borrow::Cow;
3use std::collections::HashMap;
4use std::sync::Arc;
5use std::time::{Duration, Instant};
6
7use async_trait::async_trait;
8use bytes::Bytes;
9
10use crate::config::CacheStoreConfig;
11use crate::{CacheValue, Error};
12
13/// Expiry observed with a backing value in the same read.
14#[derive(Clone, Copy, Debug)]
15pub enum CacheExpiry {
16 Unknown,
17 Never,
18 At(Instant),
19}
20
21pub struct CacheEntry {
22 pub bytes: Bytes,
23 pub expiry: CacheExpiry,
24}
25
26/// Raw storage contract implemented by cache backends.
27///
28/// Stores know how to persist bytes. Selection, value encoding, configuration,
29/// and default-store behavior live above this boundary.
30#[async_trait]
31pub trait CacheStore: Any + Send + Sync + 'static {
32 fn store_name(&self) -> &str;
33 fn driver_name(&self) -> &str;
34 fn as_any(&self) -> &dyn Any;
35 fn supports_ttl(&self) -> bool;
36 /// Return an immutable owning buffer, valid independently of this store.
37 /// Memory backends share the allocation; eviction must not invalidate it.
38 async fn get(
39 &self,
40 key: &str,
41 ) -> crate::Result<Option<Bytes>>;
42
43 /// Read a value and its expiry together for a cache that can retain it.
44 /// Backends without this information can still serve the current miss.
45 async fn get_entry(
46 &self,
47 key: &str,
48 ) -> crate::Result<Option<CacheEntry>> {
49 Ok(self
50 .get(key)
51 .await?
52 .map(|bytes| CacheEntry { bytes, expiry: CacheExpiry::Unknown }))
53 }
54 /// Store `value` under `key`. An owned buffer lets a backend that retains
55 /// bytes in process keep the allocation; others borrow it.
56 async fn put(
57 &self,
58 key: &str,
59 value: Cow<'_, [u8]>,
60 ttl: Option<Duration>,
61 ) -> crate::Result<()>;
62 async fn forget(
63 &self,
64 key: &str,
65 ) -> crate::Result<()>;
66
67 async fn clear(&self) -> crate::Result<()> {
68 Err(Error::Rejected(format!(
69 "cache store '{}' with driver '{}' does not support clearing its namespace",
70 self.store_name(),
71 self.driver_name()
72 )))
73 }
74
75 /// This store's tagged operations, or `None` when it cannot keep tags.
76 ///
77 /// The answer belongs to the built store, not to its driver: one driver
78 /// can build stores that differ, as an Orbit store does with and without
79 /// a backing store. A store answers `Some` only when an invalidation
80 /// reaches every value it can return afterwards, including what a miss
81 /// reads from a lower tier. Untagged operations do not depend on it.
82 fn tagged(&self) -> Option<&dyn TaggedCacheStore> {
83 None
84 }
85}
86
87/// A position on a store's tag-invalidation clock, read before a backing
88/// read and given back to [`TaggedCacheStore::fill_tagged`] with its result.
89///
90/// Opaque to everyone but the store that issued it: `source` names the
91/// clock, `clock` the position on it. A store refuses a token from another
92/// clock as [`Fill::Invalidated`]. 16 bytes, `Copy`.
93#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
94pub struct FillToken {
95 source: u64,
96 clock: u64,
97}
98
99impl FillToken {
100 /// For a store implementing [`TaggedCacheStore::fill_token`].
101 pub const fn new(
102 source: u64,
103 clock: u64,
104 ) -> Self {
105 Self { source, clock }
106 }
107
108 pub const fn source(self) -> u64 {
109 self.source
110 }
111
112 pub const fn clock(self) -> u64 {
113 self.clock
114 }
115}
116
117/// What [`TaggedCacheStore::fill_tagged`] did with its value. Every variant
118/// but [`Fill::Kept`] leaves the store as it was, and none is an error: the
119/// value is still the right answer for the read that produced it.
120#[must_use = "a refused fill is not an error, but nothing was stored"]
121#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
122pub enum Fill {
123 /// Stored; reads may return it until a newer write of its key, an
124 /// invalidation of one of its tags newer than its token, its expiry, or
125 /// eviction.
126 Kept,
127 /// Refused by the fence: an invalidation of one of its tags may be newer
128 /// than the token, or the token is from another clock.
129 Invalidated,
130 /// Refused by its key: the store holds or has recorded a write of this
131 /// key newer than the token.
132 Superseded,
133 /// Not kept, for a reason that says nothing about staleness, such as an
134 /// already expired value or no room.
135 Skipped,
136}
137
138impl Fill {
139 pub const fn is_kept(self) -> bool {
140 matches!(self, Self::Kept)
141 }
142}
143
144/// Tagged writes, fenced fills and invalidation by tag for a store that
145/// supports them.
146///
147/// Reached through [`CacheStore::tagged`]. These are separate entry points
148/// rather than an optional argument to `put`, so a store without tags refuses
149/// the tagged call instead of silently dropping its tags. Reads are the same
150/// for tagged and untagged entries. A store with tags has the fenced fill as
151/// well: without it, a value read from a source while one of its tags was
152/// invalidated could be cached with nothing left to remove it.
153#[async_trait]
154pub trait TaggedCacheStore: Send + Sync {
155 /// Store `value` under `key` so that [`Self::invalidate_tags`] of any of
156 /// `tags` makes it a miss. An empty set is an untagged put. A set larger
157 /// than the store keeps is [`Error::TooManyTags`]; nothing is truncated.
158 async fn put_tagged(
159 &self,
160 key: &str,
161 value: Cow<'_, [u8]>,
162 ttl: Option<Duration>,
163 tags: &[&str],
164 ) -> crate::Result<()>;
165
166 /// This store's position on its tag-invalidation clock. Take it
167 /// immediately before reading the authoritative source, and before any
168 /// snapshot that read uses.
169 async fn fill_token(&self) -> crate::Result<FillToken>;
170
171 /// Store `value`, read from the authoritative source after `token` was
172 /// taken, under `tags`, unless an invalidation of one of them is newer
173 /// than the token: an invalidation whose clock position is at or below
174 /// the token ran before the read began and is in what it returned; one
175 /// above it refuses the fill ([`Fill::Invalidated`]), whether it reaches
176 /// the store before the fill or after. Arguments the store refuses are
177 /// errors, as for [`Self::put_tagged`]; an empty set is an untagged fill.
178 async fn fill_tagged(
179 &self,
180 token: FillToken,
181 key: &str,
182 value: Cow<'_, [u8]>,
183 ttl: Option<Duration>,
184 tags: &[&str],
185 ) -> crate::Result<Fill>;
186
187 /// Make every entry carrying any of `tags`, written before this call, a
188 /// miss. An empty set is [`Error::TagsEmpty`]. Change the source first,
189 /// then invalidate: a fill whose token was read after this call returns
190 /// is kept.
191 async fn invalidate_tags(
192 &self,
193 tags: &[&str],
194 ) -> crate::Result<()>;
195}
196
197/// Read-only view of the complete candidate store graph during composition.
198///
199/// Drivers use this only to resolve cross-store dependencies after every
200/// store has been constructed. The view may represent the boot generation or
201/// a not-yet-published reload generation.
202pub trait CacheStoreResolver {
203 fn store(
204 &self,
205 name: &str,
206 ) -> crate::Result<Arc<dyn CacheStore>>;
207}
208
209impl CacheStoreResolver for HashMap<String, Arc<dyn CacheStore>> {
210 fn store(
211 &self,
212 name: &str,
213 ) -> crate::Result<Arc<dyn CacheStore>> {
214 self.get(name).cloned().ok_or_else(|| {
215 Error::Missing(format!("cache store '{name}' is not registered"))
216 })
217 }
218}
219
220/// Build-time factory for one cache backend family.
221///
222/// Third-party drivers register this trait with
223/// [`CacheRegistry`](crate::CacheRegistry). They may deserialize the common
224/// `cache.yaml` store options, ignore them, or use configuration owned by their
225/// own provider.
226pub trait CacheDriver: Any + Send + Sync + 'static {
227 fn driver_name(&self) -> &'static str;
228
229 fn create_store(
230 self: Arc<Self>,
231 store_name: &str,
232 config: &CacheStoreConfig,
233 ) -> crate::Result<Arc<dyn CacheStore>>;
234
235 /// Build a store for a reload candidate.
236 ///
237 /// Most drivers use ordinary construction. Drivers backed by a
238 /// process-lifetime service may reject a first runtime registration or
239 /// reuse a logical store already owned by that service.
240 fn create_reload_store(
241 self: Arc<Self>,
242 store_name: &str,
243 config: &CacheStoreConfig,
244 ) -> crate::Result<Arc<dyn CacheStore>> {
245 self.create_store(store_name, config)
246 }
247
248 /// Complete links that require all named stores to exist.
249 fn finish_store(
250 &self,
251 _store: &Arc<dyn CacheStore>,
252 _stores: &dyn CacheStoreResolver,
253 ) -> crate::Result<()> {
254 Ok(())
255 }
256}
257
258/// Driver-neutral operations for one named cache store.
259///
260/// The repository owns common value encoding while the underlying store stays
261/// byte-oriented.
262pub struct CacheRepository {
263 store: Arc<dyn CacheStore>,
264}
265
266impl CacheRepository {
267 pub(crate) fn new(store: Arc<dyn CacheStore>) -> Self {
268 Self { store }
269 }
270
271 pub fn store_name(&self) -> &str {
272 self.store.store_name()
273 }
274
275 pub fn driver_name(&self) -> &str {
276 self.store.driver_name()
277 }
278
279 pub fn supports_ttl(&self) -> bool {
280 self.store.supports_ttl()
281 }
282
283 /// Whether this store accepts [`Self::put_tagged`] and
284 /// [`Self::invalidate_tags`]. Fixed for the store's life; a reload that
285 /// changes it builds another store, resolved again through the provider.
286 pub fn supports_tags(&self) -> bool {
287 self.store.tagged().is_some()
288 }
289
290 pub fn as_any(&self) -> &dyn Any {
291 self.store.as_any()
292 }
293
294 pub fn store(&self) -> Arc<dyn CacheStore> {
295 self.store.clone()
296 }
297
298 /// Read bytes without copying a memory backend's allocation.
299 /// Keep this owner alive while borrowing with [`CacheValue::view`].
300 pub async fn get(
301 &self,
302 key: &str,
303 ) -> crate::Result<Option<Bytes>> {
304 self.store.get(key).await
305 }
306
307 pub async fn put<'v>(
308 &self,
309 key: &str,
310 value: impl Into<Cow<'v, [u8]>>,
311 ttl: Option<Duration>,
312 ) -> crate::Result<()> {
313 self.store.put(key, value.into(), ttl).await
314 }
315
316 pub async fn get_value(
317 &self,
318 key: &str,
319 ) -> crate::Result<Option<CacheValue>> {
320 self.get(key)
321 .await?
322 .map(|bytes| CacheValue::decode(&bytes).map_err(Error::from))
323 .transpose()
324 }
325
326 pub async fn put_value(
327 &self,
328 key: &str,
329 value: CacheValue,
330 ttl: Option<Duration>,
331 ) -> crate::Result<()> {
332 let encoded = value.encode().map_err(Error::from)?;
333 self.put(key, encoded, ttl).await
334 }
335
336 /// Store bytes that an invalidation of any of `tags` makes a miss.
337 /// Refused with [`Error::TagsUnsupported`] when [`Self::supports_tags`]
338 /// is false, before anything is written.
339 pub async fn put_tagged<'v>(
340 &self,
341 key: &str,
342 value: impl Into<Cow<'v, [u8]>>,
343 ttl: Option<Duration>,
344 tags: &[&str],
345 ) -> crate::Result<()> {
346 self.tagged()?.put_tagged(key, value.into(), ttl, tags).await
347 }
348
349 pub async fn put_value_tagged(
350 &self,
351 key: &str,
352 value: CacheValue,
353 ttl: Option<Duration>,
354 tags: &[&str],
355 ) -> crate::Result<()> {
356 let tagged = self.tagged()?;
357 let encoded = value.encode().map_err(Error::from)?;
358 tagged.put_tagged(key, encoded.into(), ttl, tags).await
359 }
360
361 /// The token to take before a backing read whose result goes to
362 /// [`Self::fill_tagged`]. Refused like [`Self::put_tagged`].
363 pub async fn fill_token(&self) -> crate::Result<FillToken> {
364 self.tagged()?.fill_token().await
365 }
366
367 /// Store bytes read from an authoritative source after `token`, unless
368 /// an invalidation of one of `tags` is newer than the token; see
369 /// [`TaggedCacheStore::fill_tagged`]. Refused like [`Self::put_tagged`].
370 pub async fn fill_tagged<'v>(
371 &self,
372 token: FillToken,
373 key: &str,
374 value: impl Into<Cow<'v, [u8]>>,
375 ttl: Option<Duration>,
376 tags: &[&str],
377 ) -> crate::Result<Fill> {
378 self.tagged()?.fill_tagged(token, key, value.into(), ttl, tags).await
379 }
380
381 /// Make every entry carrying any of `tags` a miss. Refused like
382 /// [`Self::put_tagged`].
383 pub async fn invalidate_tags(
384 &self,
385 tags: &[&str],
386 ) -> crate::Result<()> {
387 self.tagged()?.invalidate_tags(tags).await
388 }
389
390 pub async fn forget(
391 &self,
392 key: &str,
393 ) -> crate::Result<()> {
394 self.store.forget(key).await
395 }
396
397 pub async fn clear(&self) -> crate::Result<()> {
398 self.store.clear().await
399 }
400
401 fn tagged(&self) -> crate::Result<&dyn TaggedCacheStore> {
402 self.store.tagged().ok_or_else(|| Error::TagsUnsupported {
403 store: self.store_name().into(),
404 driver: self.driver_name().into(),
405 })
406 }
407}