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 #[cfg(feature = "orbit")]
23 pub(crate) config: CacheConfig,
24 default: String,
25 stores: HashMap<String, Arc<dyn CacheStore>>,
26 repositories: HashMap<String, Arc<CacheRepository>>,
27}
28
29impl CacheCatalog {
30 pub(crate) fn new(
31 config: CacheConfig,
32 stores: HashMap<String, Arc<dyn CacheStore>>,
33 ) -> Self {
34 let repositories = stores
35 .iter()
36 .map(|(name, store)| {
37 (name.clone(), Arc::new(CacheRepository::new(store.clone())))
38 })
39 .collect();
40 Self {
41 default: config.default.clone(),
42 #[cfg(feature = "orbit")]
43 config,
44 stores,
45 repositories,
46 }
47 }
48
49 pub(crate) fn store(
50 &self,
51 name: &str,
52 ) -> crate::Result<Arc<dyn CacheStore>> {
53 self.stores.get(name).cloned().ok_or_else(|| {
54 Error::Missing(format!("cache store '{name}' is not registered"))
55 })
56 }
57}
58
59pub struct CacheProvider {
70 config_path: PathBuf,
71 initial_config: Option<CacheConfig>,
72 catalog: ArcSwapOption<CacheCatalog>,
73 registry: OnceLock<Weak<CacheRegistry>>,
74 reload_lock: Mutex<()>,
75}
76
77impl Register<AppState> for CacheProvider {
78 fn register(state: &AppState) -> claviron_runtime::Result<()> {
79 crate::register(state)
80 }
81}
82
83impl CacheProvider {
84 pub(crate) fn new(config_path: PathBuf) -> Self {
85 Self {
86 config_path,
87 initial_config: None,
88 catalog: ArcSwapOption::empty(),
89 registry: OnceLock::new(),
90 reload_lock: Mutex::new(()),
91 }
92 }
93
94 pub(crate) fn from_config(config: CacheConfig) -> Self {
95 Self { initial_config: Some(config), ..Self::new(PathBuf::new()) }
96 }
97
98 pub(crate) fn is_file_configured(&self) -> bool {
99 self.initial_config.is_none()
100 }
101
102 pub(crate) fn attach_registry(
103 &self,
104 registry: Weak<CacheRegistry>,
105 ) -> crate::Result<()> {
106 self.registry.set(registry).map_err(|_| {
107 Error::Rejected("cache registry is already attached".to_string())
108 })
109 }
110
111 pub(crate) fn install(
112 &self,
113 catalog: CacheCatalog,
114 ) -> crate::Result<()> {
115 if self.catalog.load().is_some() {
116 return Err(Error::Rejected(
117 "cache provider is already built".to_string(),
118 ));
119 }
120 self.publish(catalog);
121 Ok(())
122 }
123
124 pub(crate) fn publish(
125 &self,
126 catalog: CacheCatalog,
127 ) {
128 self.catalog.store(Some(Arc::new(catalog)));
129 }
130
131 pub(crate) fn catalog(&self) -> crate::Result<Arc<CacheCatalog>> {
132 self.catalog.load_full().ok_or_else(|| {
133 Error::Missing("cache provider is not built yet".to_string())
134 })
135 }
136
137 pub(crate) fn raw_store(
138 &self,
139 name: &str,
140 ) -> crate::Result<Arc<dyn CacheStore>> {
141 self.catalog()?.store(name)
142 }
143
144 pub fn store(
145 &self,
146 name: &str,
147 ) -> crate::Result<Arc<CacheRepository>> {
148 self.catalog()?.repositories.get(name).cloned().ok_or_else(|| {
149 Error::Missing(format!("cache store '{name}' is not registered"))
150 })
151 }
152
153 pub fn default_store_name(&self) -> crate::Result<String> {
154 Ok(self.catalog()?.default.clone())
155 }
156
157 pub fn default_store(&self) -> crate::Result<Arc<CacheRepository>> {
158 let catalog = self.catalog()?;
159 catalog.repositories.get(&catalog.default).cloned().ok_or_else(|| {
160 Error::Missing(format!(
161 "cache default store '{}' is missing",
162 catalog.default
163 ))
164 })
165 }
166
167 fn registry(
168 &self
169 ) -> claviron_runtime::registry::Result<Arc<CacheRegistry>> {
170 self.registry.get().and_then(Weak::upgrade).ok_or_else(|| {
171 claviron_runtime::registry::Error::msg(
172 "CacheRegistry is unavailable",
173 )
174 })
175 }
176
177 fn republish(
179 &self,
180 registry: &CacheRegistry,
181 config: CacheConfig,
182 ) -> claviron_runtime::registry::Result<()> {
183 let candidate =
184 registry.build_reload_catalog(config).map_err(|error| {
185 claviron_runtime::registry::Error::msg(format!(
186 "cache catalog reload failed: {error}"
187 ))
188 })?;
189 self.publish(candidate.commit());
190 Ok(())
191 }
192
193 pub async fn get(
194 &self,
195 key: &str,
196 ) -> crate::Result<Option<bytes::Bytes>> {
197 self.default_store()?.get(key).await
198 }
199
200 pub async fn put<'v>(
201 &self,
202 key: &str,
203 value: impl Into<Cow<'v, [u8]>>,
204 ttl: Option<Duration>,
205 ) -> crate::Result<()> {
206 self.default_store()?.put(key, value, ttl).await
207 }
208
209 pub async fn get_value(
210 &self,
211 key: &str,
212 ) -> crate::Result<Option<CacheValue>> {
213 self.default_store()?.get_value(key).await
214 }
215
216 pub async fn put_value(
217 &self,
218 key: &str,
219 value: CacheValue,
220 ttl: Option<Duration>,
221 ) -> crate::Result<()> {
222 self.default_store()?.put_value(key, value, ttl).await
223 }
224
225 pub async fn forget(
226 &self,
227 key: &str,
228 ) -> crate::Result<()> {
229 self.default_store()?.forget(key).await
230 }
231
232 pub async fn clear(&self) -> crate::Result<()> {
233 self.default_store()?.clear().await
234 }
235}
236
237impl Component<AppState> for CacheProvider {
238 type Deps = ();
239
240 fn name(&self) -> &'static str {
241 "CacheProvider"
242 }
243
244 fn validate(
245 &self,
246 _state: &AppState,
247 ) -> claviron_runtime::registry::Result<()> {
248 self.catalog().map(|_| ()).map_err(|error| {
249 claviron_runtime::registry::Error::msg(error.to_string())
250 })
251 }
252
253 fn as_reloadable(&self) -> Option<&dyn Reloadable<AppState>> {
254 self.is_file_configured().then_some(self)
255 }
256
257 fn as_configurable(&self) -> Option<&dyn congif::ConfigRegistration> {
258 self.is_file_configured().then_some(self)
259 }
260
261 fn as_bootable(&self) -> Option<&dyn Bootable<AppState, Self::Deps>> {
262 Some(self)
263 }
264}
265
266#[async_trait]
267impl Bootable<AppState> for CacheProvider {
268 async fn boot(
269 &self,
270 _deps: (),
271 _state: &AppState,
272 ) -> claviron_runtime::registry::Result<()> {
273 if let Some(config) = &self.initial_config {
274 self.configure(config).await?;
275 }
276 Ok(())
277 }
278}
279
280#[async_trait]
281impl Configurable for CacheProvider {
282 type Config = CacheConfig;
283
284 fn source(&self) -> ConfigFile {
285 ConfigFile::yaml(&self.config_path)
286 }
287
288 fn absent_source(&self) -> Option<CacheConfig> {
290 Some(CacheConfig::default())
291 }
292
293 fn validate_config(
294 &self,
295 config: &CacheConfig,
296 ) -> congif::Result<()> {
297 crate::registry::validate_config(config)
298 .map_err(congif::Error::validation)
299 }
300
301 async fn configure(
302 &self,
303 config: &CacheConfig,
304 ) -> congif::Result<()> {
305 let registry = self.registry().map_err(congif::Error::msg)?;
306 registry
307 .configure(config.clone())
308 .map_err(congif::Error::validation)?;
309 registry.seal().map_err(congif::Error::validation)
312 }
313
314 fn as_config_observer(
315 &self
316 ) -> Option<&dyn ConfigObserver<Config = Self::Config>> {
317 Some(self)
318 }
319}
320
321#[async_trait]
322impl ConfigObserver for CacheProvider {
323 async fn config_changed(
326 &self,
327 config: &CacheConfig,
328 ) -> congif::Result<()> {
329 let _guard = self.reload_lock.lock().await;
330 let registry = self.registry().map_err(congif::Error::msg)?;
331 if !registry.is_sealed() {
332 return registry
333 .configure(config.clone())
334 .map_err(congif::Error::validation);
335 }
336 self.republish(®istry, config.clone())
337 .map_err(congif::Error::msg)?;
338 info!(path = %self.config_path.display(), "🔁 CacheProvider reconfigured");
339 Ok(())
340 }
341}
342
343#[async_trait]
344impl Reloadable<AppState> for CacheProvider {
345 async fn reload(
346 &self,
347 state: &AppState,
348 ) -> claviron_runtime::registry::Result<()> {
349 let _guard = self.reload_lock.lock().await;
350 let registry = self.registry()?;
351 let config = state.config_reader().snapshot::<Self>()?;
352 self.republish(®istry, (*config).clone())?;
353 info!(path = %self.config_path.display(), "🔁 CacheProvider reloaded");
354 Ok(())
355 }
356}