Skip to main content

claviron_cache/
config.rs

1use std::collections::HashMap;
2
3use serde::Deserialize;
4use serde::de::DeserializeOwned;
5
6use crate::drivers::memory;
7
8#[derive(Clone, Debug, Deserialize, Default, PartialEq)]
9#[serde(deny_unknown_fields)]
10pub struct CacheConfig {
11    #[serde(default)]
12    pub default: String,
13    #[serde(default)]
14    pub stores: HashMap<String, CacheStoreConfig>,
15}
16
17impl CacheConfig {
18    /// A document with no explicit store declarations or default.
19    pub fn is_empty(&self) -> bool {
20        self.stores.is_empty() && self.default.trim().is_empty()
21    }
22}
23
24#[derive(Clone, Debug, Deserialize, PartialEq)]
25pub struct CacheStoreConfig {
26    #[serde(default = "default_driver", alias = "kind")]
27    pub driver: String,
28
29    #[serde(flatten)]
30    pub options: HashMap<String, serde_yaml::Value>,
31}
32
33fn default_driver() -> String {
34    memory::NAME.to_owned()
35}
36
37impl Default for CacheStoreConfig {
38    fn default() -> Self {
39        Self { driver: default_driver(), options: HashMap::new() }
40    }
41}
42
43impl CacheStoreConfig {
44    pub fn driver_key(&self) -> String {
45        self.driver.trim().to_ascii_lowercase()
46    }
47
48    pub fn options_value(&self) -> serde_yaml::Value {
49        let mut mapping = serde_yaml::Mapping::new();
50        for (key, value) in &self.options {
51            mapping
52                .insert(serde_yaml::Value::String(key.clone()), value.clone());
53        }
54        serde_yaml::Value::Mapping(mapping)
55    }
56
57    pub fn deserialize_options<T>(&self) -> super::Result<T>
58    where
59        T: DeserializeOwned,
60    {
61        serde_yaml::from_value(self.options_value()).map_err(super::Error::from)
62    }
63}
64
65#[derive(Clone, Deserialize)]
66pub struct FileCacheStoreConfig {
67    pub path: String,
68    #[serde(default)]
69    pub prefix: Option<String>,
70}