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;
6
7use async_trait::async_trait;
8use bytes::Bytes;
9
10use crate::config::CacheStoreConfig;
11use crate::{CacheValue, Error};
12
13/// Raw storage contract implemented by cache backends.
14///
15/// Stores know how to persist bytes. Selection, value encoding, configuration,
16/// and default-store behavior live above this boundary.
17#[async_trait]
18pub trait CacheStore: Any + Send + Sync + 'static {
19    fn store_name(&self) -> &str;
20    fn driver_name(&self) -> &str;
21    fn as_any(&self) -> &dyn Any;
22    fn supports_ttl(&self) -> bool;
23    /// Return an immutable owning buffer, valid independently of this store.
24    /// Memory backends share the allocation; eviction must not invalidate it.
25    async fn get(
26        &self,
27        key: &str,
28    ) -> crate::Result<Option<Bytes>>;
29    /// Store `value` under `key`. An owned buffer lets a backend that retains
30    /// bytes in process keep the allocation; others borrow it.
31    async fn put(
32        &self,
33        key: &str,
34        value: Cow<'_, [u8]>,
35        ttl: Option<Duration>,
36    ) -> crate::Result<()>;
37    async fn forget(
38        &self,
39        key: &str,
40    ) -> crate::Result<()>;
41
42    async fn clear(&self) -> crate::Result<()> {
43        Err(Error::Rejected(format!(
44            "cache store '{}' with driver '{}' does not support clearing its namespace",
45            self.store_name(),
46            self.driver_name()
47        )))
48    }
49}
50
51/// Read-only view of the complete candidate store graph during composition.
52///
53/// Drivers use this only to resolve cross-store dependencies after every
54/// store has been constructed. The view may represent the boot generation or
55/// a not-yet-published reload generation.
56pub trait CacheStoreResolver {
57    fn store(
58        &self,
59        name: &str,
60    ) -> crate::Result<Arc<dyn CacheStore>>;
61}
62
63impl CacheStoreResolver for HashMap<String, Arc<dyn CacheStore>> {
64    fn store(
65        &self,
66        name: &str,
67    ) -> crate::Result<Arc<dyn CacheStore>> {
68        self.get(name).cloned().ok_or_else(|| {
69            Error::Missing(format!("cache store '{name}' is not registered"))
70        })
71    }
72}
73
74/// Build-time factory for one cache backend family.
75///
76/// Third-party drivers register this trait with
77/// [`CacheRegistry`](crate::CacheRegistry). They may deserialize the common
78/// `cache.yaml` store options, ignore them, or use configuration owned by their
79/// own provider.
80pub trait CacheDriver: Any + Send + Sync + 'static {
81    fn driver_name(&self) -> &'static str;
82
83    fn create_store(
84        self: Arc<Self>,
85        store_name: &str,
86        config: &CacheStoreConfig,
87    ) -> crate::Result<Arc<dyn CacheStore>>;
88
89    /// Build a store for a reload candidate.
90    ///
91    /// Most drivers use ordinary construction. Drivers backed by a
92    /// process-lifetime service may reject a first runtime registration or
93    /// reuse a logical store already owned by that service.
94    fn create_reload_store(
95        self: Arc<Self>,
96        store_name: &str,
97        config: &CacheStoreConfig,
98    ) -> crate::Result<Arc<dyn CacheStore>> {
99        self.create_store(store_name, config)
100    }
101
102    /// Complete links that require all named stores to exist.
103    fn finish_store(
104        &self,
105        _store: &Arc<dyn CacheStore>,
106        _stores: &dyn CacheStoreResolver,
107    ) -> crate::Result<()> {
108        Ok(())
109    }
110}
111
112/// Driver-neutral operations for one named cache store.
113///
114/// The repository owns common value encoding while the underlying store stays
115/// byte-oriented.
116pub struct CacheRepository {
117    store: Arc<dyn CacheStore>,
118}
119
120impl CacheRepository {
121    pub(crate) fn new(store: Arc<dyn CacheStore>) -> Self {
122        Self { store }
123    }
124
125    pub fn store_name(&self) -> &str {
126        self.store.store_name()
127    }
128
129    pub fn driver_name(&self) -> &str {
130        self.store.driver_name()
131    }
132
133    pub fn supports_ttl(&self) -> bool {
134        self.store.supports_ttl()
135    }
136
137    pub fn as_any(&self) -> &dyn Any {
138        self.store.as_any()
139    }
140
141    pub fn store(&self) -> Arc<dyn CacheStore> {
142        self.store.clone()
143    }
144
145    /// Read bytes without copying a memory backend's allocation.
146    /// Keep this owner alive while borrowing with [`CacheValue::view`].
147    pub async fn get(
148        &self,
149        key: &str,
150    ) -> crate::Result<Option<Bytes>> {
151        self.store.get(key).await
152    }
153
154    pub async fn put<'v>(
155        &self,
156        key: &str,
157        value: impl Into<Cow<'v, [u8]>>,
158        ttl: Option<Duration>,
159    ) -> crate::Result<()> {
160        self.store.put(key, value.into(), ttl).await
161    }
162
163    pub async fn get_value(
164        &self,
165        key: &str,
166    ) -> crate::Result<Option<CacheValue>> {
167        self.get(key)
168            .await?
169            .map(|bytes| CacheValue::decode(&bytes).map_err(Error::from))
170            .transpose()
171    }
172
173    pub async fn put_value(
174        &self,
175        key: &str,
176        value: CacheValue,
177        ttl: Option<Duration>,
178    ) -> crate::Result<()> {
179        let encoded = value.encode().map_err(Error::from)?;
180        self.put(key, encoded, ttl).await
181    }
182
183    pub async fn forget(
184        &self,
185        key: &str,
186    ) -> crate::Result<()> {
187        self.store.forget(key).await
188    }
189
190    pub async fn clear(&self) -> crate::Result<()> {
191        self.store.clear().await
192    }
193}