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