Skip to main content

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
76/// Read-only view of the complete candidate store graph during composition.
77///
78/// Drivers use this only to resolve cross-store dependencies after every
79/// store has been constructed. The view may represent the boot generation or
80/// a not-yet-published reload generation.
81pub trait CacheStoreResolver {
82    fn store(
83        &self,
84        name: &str,
85    ) -> crate::Result<Arc<dyn CacheStore>>;
86}
87
88impl CacheStoreResolver for HashMap<String, Arc<dyn CacheStore>> {
89    fn store(
90        &self,
91        name: &str,
92    ) -> crate::Result<Arc<dyn CacheStore>> {
93        self.get(name).cloned().ok_or_else(|| {
94            Error::Missing(format!("cache store '{name}' is not registered"))
95        })
96    }
97}
98
99/// Build-time factory for one cache backend family.
100///
101/// Third-party drivers register this trait with
102/// [`CacheRegistry`](crate::CacheRegistry). They may deserialize the common
103/// `cache.yaml` store options, ignore them, or use configuration owned by their
104/// own provider.
105pub trait CacheDriver: Any + Send + Sync + 'static {
106    fn driver_name(&self) -> &'static str;
107
108    fn create_store(
109        self: Arc<Self>,
110        store_name: &str,
111        config: &CacheStoreConfig,
112    ) -> crate::Result<Arc<dyn CacheStore>>;
113
114    /// Build a store for a reload candidate.
115    ///
116    /// Most drivers use ordinary construction. Drivers backed by a
117    /// process-lifetime service may reject a first runtime registration or
118    /// reuse a logical store already owned by that service.
119    fn create_reload_store(
120        self: Arc<Self>,
121        store_name: &str,
122        config: &CacheStoreConfig,
123    ) -> crate::Result<Arc<dyn CacheStore>> {
124        self.create_store(store_name, config)
125    }
126
127    /// Complete links that require all named stores to exist.
128    fn finish_store(
129        &self,
130        _store: &Arc<dyn CacheStore>,
131        _stores: &dyn CacheStoreResolver,
132    ) -> crate::Result<()> {
133        Ok(())
134    }
135}
136
137/// Driver-neutral operations for one named cache store.
138///
139/// The repository owns common value encoding while the underlying store stays
140/// byte-oriented.
141pub struct CacheRepository {
142    store: Arc<dyn CacheStore>,
143}
144
145impl CacheRepository {
146    pub(crate) fn new(store: Arc<dyn CacheStore>) -> Self {
147        Self { store }
148    }
149
150    pub fn store_name(&self) -> &str {
151        self.store.store_name()
152    }
153
154    pub fn driver_name(&self) -> &str {
155        self.store.driver_name()
156    }
157
158    pub fn supports_ttl(&self) -> bool {
159        self.store.supports_ttl()
160    }
161
162    pub fn as_any(&self) -> &dyn Any {
163        self.store.as_any()
164    }
165
166    pub fn store(&self) -> Arc<dyn CacheStore> {
167        self.store.clone()
168    }
169
170    /// Read bytes without copying a memory backend's allocation.
171    /// Keep this owner alive while borrowing with [`CacheValue::view`].
172    pub async fn get(
173        &self,
174        key: &str,
175    ) -> crate::Result<Option<Bytes>> {
176        self.store.get(key).await
177    }
178
179    pub async fn put<'v>(
180        &self,
181        key: &str,
182        value: impl Into<Cow<'v, [u8]>>,
183        ttl: Option<Duration>,
184    ) -> crate::Result<()> {
185        self.store.put(key, value.into(), ttl).await
186    }
187
188    pub async fn get_value(
189        &self,
190        key: &str,
191    ) -> crate::Result<Option<CacheValue>> {
192        self.get(key)
193            .await?
194            .map(|bytes| CacheValue::decode(&bytes).map_err(Error::from))
195            .transpose()
196    }
197
198    pub async fn put_value(
199        &self,
200        key: &str,
201        value: CacheValue,
202        ttl: Option<Duration>,
203    ) -> crate::Result<()> {
204        let encoded = value.encode().map_err(Error::from)?;
205        self.put(key, encoded, ttl).await
206    }
207
208    pub async fn forget(
209        &self,
210        key: &str,
211    ) -> crate::Result<()> {
212        self.store.forget(key).await
213    }
214
215    pub async fn clear(&self) -> crate::Result<()> {
216        self.store.clear().await
217    }
218}