Skip to main content

claviron_cache/
provider.rs

1use std::borrow::Cow;
2use std::collections::HashMap;
3use std::path::PathBuf;
4use std::sync::{Arc, OnceLock, Weak};
5use std::time::Duration;
6
7use arc_swap::ArcSwapOption;
8use async_trait::async_trait;
9use claviron_runtime::congif::{
10    self, ConfigFile, ConfigObserver, Configurable,
11};
12use claviron_runtime::registry::{Bootable, Component, Reloadable};
13use claviron_runtime::{AppState, Register};
14use tokio::sync::Mutex;
15use tracing::info;
16
17use crate::config::CacheConfig;
18use crate::store::CacheRepository;
19use crate::{CacheRegistry, CacheStore, CacheValue, Error};
20
21pub(crate) struct CacheCatalog {
22    pub(crate) config: CacheConfig,
23    default: String,
24    stores: HashMap<String, Arc<dyn CacheStore>>,
25    repositories: HashMap<String, Arc<CacheRepository>>,
26}
27
28impl CacheCatalog {
29    pub(crate) fn new(
30        config: CacheConfig,
31        stores: HashMap<String, Arc<dyn CacheStore>>,
32    ) -> Self {
33        let repositories = stores
34            .iter()
35            .map(|(name, store)| {
36                (name.clone(), Arc::new(CacheRepository::new(store.clone())))
37            })
38            .collect();
39        Self { default: config.default.clone(), config, stores, repositories }
40    }
41
42    pub(crate) fn store(
43        &self,
44        name: &str,
45    ) -> crate::Result<Arc<dyn CacheStore>> {
46        self.stores.get(name).cloned().ok_or_else(|| {
47            Error::Missing(format!("cache store '{name}' is not registered"))
48        })
49    }
50}
51
52/// Reloadable runtime cache facade, and the owner of `cache.yaml`.
53///
54/// [`CacheRegistry`] owns driver discovery and candidate construction. This
55/// provider owns the active catalog generation: Congif prepares `cache.yaml`
56/// before boot and in the reload batch; `configure` hands the registry its
57/// composition before the sealing boot, and a reload or a prepared source
58/// change asks the sealed registry to build and validate a complete
59/// replacement, then publishes it atomically. Handles resolved before
60/// publication keep their old repository alive; later resolutions see the new
61/// generation. An absent file selects the built-in memory store.
62pub struct CacheProvider {
63    config_path: PathBuf,
64    initial_config: Option<CacheConfig>,
65    catalog: ArcSwapOption<CacheCatalog>,
66    registry: OnceLock<Weak<CacheRegistry>>,
67    reload_lock: Mutex<()>,
68}
69
70impl Register<AppState> for CacheProvider {
71    fn register(state: &AppState) -> claviron_runtime::Result<()> {
72        crate::register(state)
73    }
74}
75
76impl CacheProvider {
77    pub(crate) fn new(config_path: PathBuf) -> Self {
78        Self {
79            config_path,
80            initial_config: None,
81            catalog: ArcSwapOption::empty(),
82            registry: OnceLock::new(),
83            reload_lock: Mutex::new(()),
84        }
85    }
86
87    pub(crate) fn from_config(config: CacheConfig) -> Self {
88        Self { initial_config: Some(config), ..Self::new(PathBuf::new()) }
89    }
90
91    pub(crate) fn is_file_configured(&self) -> bool {
92        self.initial_config.is_none()
93    }
94
95    pub(crate) fn attach_registry(
96        &self,
97        registry: Weak<CacheRegistry>,
98    ) -> crate::Result<()> {
99        self.registry.set(registry).map_err(|_| {
100            Error::Rejected("cache registry is already attached".to_string())
101        })
102    }
103
104    pub(crate) fn install(
105        &self,
106        catalog: CacheCatalog,
107    ) -> crate::Result<()> {
108        if self.catalog.load().is_some() {
109            return Err(Error::Rejected(
110                "cache provider is already built".to_string(),
111            ));
112        }
113        self.publish(catalog);
114        Ok(())
115    }
116
117    pub(crate) fn publish(
118        &self,
119        catalog: CacheCatalog,
120    ) {
121        self.catalog.store(Some(Arc::new(catalog)));
122    }
123
124    pub(crate) fn catalog(&self) -> crate::Result<Arc<CacheCatalog>> {
125        self.catalog.load_full().ok_or_else(|| {
126            Error::Missing("cache provider is not built yet".to_string())
127        })
128    }
129
130    pub(crate) fn raw_store(
131        &self,
132        name: &str,
133    ) -> crate::Result<Arc<dyn CacheStore>> {
134        self.catalog()?.store(name)
135    }
136
137    pub fn store(
138        &self,
139        name: &str,
140    ) -> crate::Result<Arc<CacheRepository>> {
141        self.catalog()?.repositories.get(name).cloned().ok_or_else(|| {
142            Error::Missing(format!("cache store '{name}' is not registered"))
143        })
144    }
145
146    pub fn default_store_name(&self) -> crate::Result<String> {
147        Ok(self.catalog()?.default.clone())
148    }
149
150    pub fn default_store(&self) -> crate::Result<Arc<CacheRepository>> {
151        let catalog = self.catalog()?;
152        catalog.repositories.get(&catalog.default).cloned().ok_or_else(|| {
153            Error::Missing(format!(
154                "cache default store '{}' is missing",
155                catalog.default
156            ))
157        })
158    }
159
160    fn registry(
161        &self
162    ) -> claviron_runtime::registry::Result<Arc<CacheRegistry>> {
163        self.registry.get().and_then(Weak::upgrade).ok_or_else(|| {
164            claviron_runtime::registry::Error::msg(
165                "CacheRegistry is unavailable",
166            )
167        })
168    }
169
170    /// Publish `config` as the next catalog generation of a sealed registry.
171    fn republish(
172        &self,
173        registry: &CacheRegistry,
174        config: CacheConfig,
175    ) -> claviron_runtime::registry::Result<()> {
176        let candidate =
177            registry.build_reload_catalog(config).map_err(|error| {
178                claviron_runtime::registry::Error::msg(format!(
179                    "cache catalog reload failed: {error}"
180                ))
181            })?;
182        self.publish(candidate.commit());
183        Ok(())
184    }
185
186    pub async fn get(
187        &self,
188        key: &str,
189    ) -> crate::Result<Option<bytes::Bytes>> {
190        self.default_store()?.get(key).await
191    }
192
193    pub async fn put<'v>(
194        &self,
195        key: &str,
196        value: impl Into<Cow<'v, [u8]>>,
197        ttl: Option<Duration>,
198    ) -> crate::Result<()> {
199        self.default_store()?.put(key, value, ttl).await
200    }
201
202    pub async fn get_value(
203        &self,
204        key: &str,
205    ) -> crate::Result<Option<CacheValue>> {
206        self.default_store()?.get_value(key).await
207    }
208
209    pub async fn put_value(
210        &self,
211        key: &str,
212        value: CacheValue,
213        ttl: Option<Duration>,
214    ) -> crate::Result<()> {
215        self.default_store()?.put_value(key, value, ttl).await
216    }
217
218    pub async fn forget(
219        &self,
220        key: &str,
221    ) -> crate::Result<()> {
222        self.default_store()?.forget(key).await
223    }
224
225    pub async fn clear(&self) -> crate::Result<()> {
226        self.default_store()?.clear().await
227    }
228}
229
230impl Component<AppState> for CacheProvider {
231    type Deps = ();
232
233    fn name(&self) -> &'static str {
234        "CacheProvider"
235    }
236
237    fn validate(
238        &self,
239        _state: &AppState,
240    ) -> claviron_runtime::registry::Result<()> {
241        self.catalog().map(|_| ()).map_err(|error| {
242            claviron_runtime::registry::Error::msg(error.to_string())
243        })
244    }
245
246    fn as_reloadable(&self) -> Option<&dyn Reloadable<AppState>> {
247        self.is_file_configured().then_some(self)
248    }
249
250    fn as_configurable(&self) -> Option<&dyn congif::ConfigRegistration> {
251        self.is_file_configured().then_some(self)
252    }
253
254    fn as_bootable(&self) -> Option<&dyn Bootable<AppState, Self::Deps>> {
255        Some(self)
256    }
257}
258
259#[async_trait]
260impl Bootable<AppState> for CacheProvider {
261    async fn boot(
262        &self,
263        _deps: (),
264        _state: &AppState,
265    ) -> claviron_runtime::registry::Result<()> {
266        if let Some(config) = &self.initial_config {
267            self.configure(config).await?;
268        }
269        Ok(())
270    }
271}
272
273#[async_trait]
274impl Configurable for CacheProvider {
275    type Config = CacheConfig;
276
277    fn source(&self) -> ConfigFile {
278        ConfigFile::yaml(&self.config_path)
279    }
280
281    /// An absent file selects the registry's built-in memory store.
282    fn absent_source(&self) -> Option<CacheConfig> {
283        Some(CacheConfig::default())
284    }
285
286    fn validate_config(
287        &self,
288        config: &CacheConfig,
289    ) -> congif::Result<()> {
290        crate::registry::validate_config(config)
291            .map_err(congif::Error::validation)
292    }
293
294    async fn configure(
295        &self,
296        config: &CacheConfig,
297    ) -> congif::Result<()> {
298        let registry = self.registry().map_err(congif::Error::msg)?;
299        registry
300            .configure(config.clone())
301            .map_err(congif::Error::validation)?;
302        // The drivers were registered with the registry; the declared stores
303        // are built from them here, so nothing is left for boot.
304        registry.seal().map_err(congif::Error::validation)
305    }
306
307    fn as_config_observer(
308        &self
309    ) -> Option<&dyn ConfigObserver<Config = Self::Config>> {
310        Some(self)
311    }
312}
313
314#[async_trait]
315impl ConfigObserver for CacheProvider {
316    /// Before the registry seals, the newest preparation is what boot builds;
317    /// after it, a changed file is a new catalog generation.
318    async fn config_changed(
319        &self,
320        config: &CacheConfig,
321    ) -> congif::Result<()> {
322        let _guard = self.reload_lock.lock().await;
323        let registry = self.registry().map_err(congif::Error::msg)?;
324        if !registry.is_sealed() {
325            return registry
326                .configure(config.clone())
327                .map_err(congif::Error::validation);
328        }
329        self.republish(&registry, config.clone())
330            .map_err(congif::Error::msg)?;
331        info!(path = %self.config_path.display(), "🔁 CacheProvider reconfigured");
332        Ok(())
333    }
334}
335
336#[async_trait]
337impl Reloadable<AppState> for CacheProvider {
338    async fn reload(
339        &self,
340        state: &AppState,
341    ) -> claviron_runtime::registry::Result<()> {
342        let _guard = self.reload_lock.lock().await;
343        let registry = self.registry()?;
344        let config = state.config_reader().snapshot::<Self>()?;
345        self.republish(&registry, (*config).clone())?;
346        info!(path = %self.config_path.display(), "🔁 CacheProvider reloaded");
347        Ok(())
348    }
349}