Skip to main content

sisa_caching_core/
settings.rs

1//! The settings every store has, and the 365-day limit on durations.
2
3use std::{fmt, time::Duration};
4
5use serde::{
6    Deserialize, Deserializer, Serialize,
7    de::{self, MapAccess, Visitor},
8};
9
10use crate::cache::CacheError;
11
12/// The longest any duration setting, or a write's TTL, may be: 365 days.
13pub const MAX_TTL_SECS: u64 = 365 * 24 * 60 * 60;
14
15/// The last field of a settings type that flattens [`CacheSettings`]: it takes whatever fields
16/// no other field did, and fails on the first, so a misspelled setting can't silently keep its
17/// default. Serde's `deny_unknown_fields` doesn't work beside `flatten`.
18#[doc(hidden)]
19#[derive(Debug, Clone, Copy, Default, PartialEq)]
20pub struct NoUnknownFields;
21
22// Fails at the first field it is given: every known one was taken before it.
23impl<'de> Deserialize<'de> for NoUnknownFields {
24    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
25        deserializer.deserialize_map(NoUnknownFields)
26    }
27}
28
29// Reads the fields left over, as a map, and fails at the first one.
30impl<'de> Visitor<'de> for NoUnknownFields {
31    type Value = Self;
32
33    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
34        formatter.write_str("no fields other than the known settings")
35    }
36
37    fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self, A::Error> {
38        match map.next_key::<String>()? {
39            Some(field) => Err(de::Error::custom(format!("unknown field `{field}`"))),
40            None => Ok(self),
41        }
42    }
43}
44
45/// Fails when a duration setting is 0, with `if_zero` as the fix, or over [`MAX_TTL_SECS`]. A
46/// setting that `None` turns off passes `None` through.
47#[doc(hidden)]
48pub fn check_duration(
49    field: &'static str,
50    duration: impl Into<Option<Duration>>,
51    if_zero: &str,
52) -> Result<(), CacheError> {
53    match duration.into() {
54        Some(duration) if duration.is_zero() => Err(CacheError::invalid_settings(
55            field,
56            format!("is 0; {if_zero}"),
57        )),
58        Some(duration) if duration > Duration::from_secs(MAX_TTL_SECS) => {
59            Err(CacheError::too_long(field, duration))
60        }
61        _ => Ok(()),
62    }
63}
64
65/// Settings every store has. Each store's settings flatten them, so in a config file they sit
66/// beside the store's own: `{ "default_ttl_secs": 300, "max_entries": 10000 }`.
67#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
68#[serde(default)]
69#[non_exhaustive]
70pub struct CacheSettings {
71    /// The TTL of a write that doesn't set one: none by default. `None` keeps values until
72    /// removed or evicted; `validate` rejects `0`, which would expire every write at once.
73    pub default_ttl_secs: Option<u64>,
74
75    /// The share of an entry's TTL after which `get_or_set` reloads it ahead of expiry, such as
76    /// `0.8`: off by default. `None` turns refresh-ahead off; `validate` rejects a value outside
77    /// `(0, 1)`.
78    pub refresh_threshold: Option<f64>,
79
80    /// How long `get_or_set` waits for another caller's load of the same key before it loads the
81    /// value itself: 30 seconds by default. `None` waits until that load finishes, so a loader
82    /// that hangs holds up every caller of its key for as long. `validate` rejects `0`, which
83    /// would let every caller load at once.
84    pub lock_timeout_ms: Option<u64>,
85}
86
87// No default TTL or early refresh, and 30 seconds before a waiting caller loads on its own.
88impl Default for CacheSettings {
89    fn default() -> Self {
90        Self {
91            default_ttl_secs: None,
92            refresh_threshold: None,
93            lock_timeout_ms: Some(30_000),
94        }
95    }
96}
97
98impl CacheSettings {
99    /// Fails when `default_ttl_secs` or `lock_timeout_ms` is 0 or over [`MAX_TTL_SECS`], or
100    /// `refresh_threshold` is not between 0 and 1.
101    pub fn validate(&self) -> Result<(), CacheError> {
102        check_duration(
103            "default_ttl_secs",
104            self.default_ttl(),
105            "use None for no TTL",
106        )?;
107        check_duration(
108            "lock_timeout_ms",
109            self.lock_timeout(),
110            "use None to wait without a limit",
111        )?;
112
113        match self.refresh_threshold {
114            Some(threshold) if !(threshold > 0.0 && threshold < 1.0) => {
115                Err(CacheError::invalid_settings(
116                    "refresh_threshold",
117                    format!(
118                        "is {threshold}; it is a share of the TTL between 0 and 1, such as 0.8"
119                    ),
120                ))
121            }
122            _ => Ok(()),
123        }
124    }
125
126    /// `default_ttl_secs` as a `Duration`, or `None` when a write without a TTL never expires.
127    pub fn default_ttl(&self) -> Option<Duration> {
128        self.default_ttl_secs.map(Duration::from_secs)
129    }
130
131    /// `lock_timeout_ms` as a `Duration`, or `None` to wait as long as the other load takes.
132    pub fn lock_timeout(&self) -> Option<Duration> {
133        self.lock_timeout_ms.map(Duration::from_millis)
134    }
135}
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140
141    #[test]
142    fn by_default_get_or_set_waits_30_seconds_for_another_load() {
143        let settings = CacheSettings::default();
144
145        assert_eq!(settings.lock_timeout(), Some(Duration::from_secs(30)));
146        assert_eq!(settings.default_ttl(), None);
147        assert_eq!(settings.refresh_threshold, None);
148    }
149
150    #[test]
151    fn out_of_range_settings_are_rejected() {
152        let ttl = |secs| CacheSettings {
153            default_ttl_secs: Some(secs),
154            ..CacheSettings::default()
155        };
156        let wait = |lock_timeout_ms| CacheSettings {
157            lock_timeout_ms: Some(lock_timeout_ms),
158            ..CacheSettings::default()
159        };
160        let refresh = |threshold| CacheSettings {
161            refresh_threshold: Some(threshold),
162            ..CacheSettings::default()
163        };
164        let year_ms = MAX_TTL_SECS * 1_000;
165
166        for settings in [ttl(MAX_TTL_SECS), wait(year_ms), refresh(0.8)] {
167            assert!(settings.validate().is_ok(), "{settings:?}");
168        }
169        for (field, settings) in [
170            ("default_ttl_secs", ttl(0)),
171            ("default_ttl_secs", ttl(MAX_TTL_SECS + 1)),
172            ("lock_timeout_ms", wait(0)),
173            ("lock_timeout_ms", wait(year_ms + 1)),
174            ("refresh_threshold", refresh(0.0)),
175            ("refresh_threshold", refresh(1.0)),
176            ("refresh_threshold", refresh(80.0)),
177            ("refresh_threshold", refresh(f64::NAN)),
178        ] {
179            assert!(
180                matches!(settings.validate(), Err(CacheError::InvalidSettings { field: rejected, .. }) if rejected == field),
181                "{settings:?}"
182            );
183        }
184    }
185}