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
52pub 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 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 fn supports_tags(&self) -> crate::Result<bool> {
221 Ok(self.default_store()?.supports_tags())
222 }
223
224 pub async fn put_tagged<'v>(
225 &self,
226 key: &str,
227 value: impl Into<Cow<'v, [u8]>>,
228 ttl: Option<Duration>,
229 tags: &[&str],
230 ) -> crate::Result<()> {
231 self.default_store()?.put_tagged(key, value, ttl, tags).await
232 }
233
234 pub async fn put_value_tagged(
235 &self,
236 key: &str,
237 value: CacheValue,
238 ttl: Option<Duration>,
239 tags: &[&str],
240 ) -> crate::Result<()> {
241 self.default_store()?.put_value_tagged(key, value, ttl, tags).await
242 }
243
244 pub async fn invalidate_tags(
245 &self,
246 tags: &[&str],
247 ) -> crate::Result<()> {
248 self.default_store()?.invalidate_tags(tags).await
249 }
250
251 pub async fn forget(
252 &self,
253 key: &str,
254 ) -> crate::Result<()> {
255 self.default_store()?.forget(key).await
256 }
257
258 pub async fn clear(&self) -> crate::Result<()> {
259 self.default_store()?.clear().await
260 }
261}
262
263impl Component<AppState> for CacheProvider {
264 type Deps = ();
265
266 fn name(&self) -> &'static str {
267 "CacheProvider"
268 }
269
270 fn validate(
271 &self,
272 _state: &AppState,
273 ) -> claviron_runtime::registry::Result<()> {
274 self.catalog().map(|_| ()).map_err(|error| {
275 claviron_runtime::registry::Error::msg(error.to_string())
276 })
277 }
278
279 fn as_reloadable(&self) -> Option<&dyn Reloadable<AppState>> {
280 self.is_file_configured().then_some(self)
281 }
282
283 fn as_configurable(&self) -> Option<&dyn congif::ConfigRegistration> {
284 self.is_file_configured().then_some(self)
285 }
286
287 fn as_bootable(&self) -> Option<&dyn Bootable<AppState, Self::Deps>> {
288 Some(self)
289 }
290}
291
292#[async_trait]
293impl Bootable<AppState> for CacheProvider {
294 async fn boot(
295 &self,
296 _deps: (),
297 _state: &AppState,
298 ) -> claviron_runtime::registry::Result<()> {
299 if let Some(config) = &self.initial_config {
300 self.configure(config).await?;
301 }
302 Ok(())
303 }
304}
305
306#[async_trait]
307impl Configurable for CacheProvider {
308 type Config = CacheConfig;
309
310 fn source(&self) -> ConfigFile {
311 ConfigFile::yaml(&self.config_path)
312 }
313
314 fn absent_source(&self) -> Option<CacheConfig> {
316 Some(CacheConfig::default())
317 }
318
319 fn validate_config(
320 &self,
321 config: &CacheConfig,
322 ) -> congif::Result<()> {
323 crate::registry::validate_config(config)
324 .map_err(congif::Error::validation)
325 }
326
327 async fn configure(
328 &self,
329 config: &CacheConfig,
330 ) -> congif::Result<()> {
331 let registry = self.registry().map_err(congif::Error::msg)?;
332 registry
333 .configure(config.clone())
334 .map_err(congif::Error::validation)?;
335 registry.seal().map_err(congif::Error::validation)
338 }
339
340 fn as_config_observer(
341 &self
342 ) -> Option<&dyn ConfigObserver<Config = Self::Config>> {
343 Some(self)
344 }
345}
346
347#[async_trait]
348impl ConfigObserver for CacheProvider {
349 async fn config_changed(
352 &self,
353 config: &CacheConfig,
354 ) -> congif::Result<()> {
355 let _guard = self.reload_lock.lock().await;
356 let registry = self.registry().map_err(congif::Error::msg)?;
357 if !registry.is_sealed() {
358 return registry
359 .configure(config.clone())
360 .map_err(congif::Error::validation);
361 }
362 self.republish(®istry, config.clone())
363 .map_err(congif::Error::msg)?;
364 info!(path = %self.config_path.display(), "🔁 CacheProvider reconfigured");
365 Ok(())
366 }
367}
368
369#[async_trait]
370impl Reloadable<AppState> for CacheProvider {
371 async fn reload(
372 &self,
373 state: &AppState,
374 ) -> claviron_runtime::registry::Result<()> {
375 let _guard = self.reload_lock.lock().await;
376 let registry = self.registry()?;
377 let config = state.config_reader().snapshot::<Self>()?;
378 self.republish(®istry, (*config).clone())?;
379 info!(path = %self.config_path.display(), "🔁 CacheProvider reloaded");
380 Ok(())
381 }
382}