sisa_caching_core/
settings.rs1use std::{fmt, time::Duration};
4
5use serde::{
6 Deserialize, Deserializer, Serialize,
7 de::{self, MapAccess, Visitor},
8};
9
10use crate::cache::CacheError;
11
12pub const MAX_TTL_SECS: u64 = 365 * 24 * 60 * 60;
14
15#[doc(hidden)]
19#[derive(Debug, Clone, Copy, Default, PartialEq)]
20pub struct NoUnknownFields;
21
22impl<'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
29impl<'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#[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
68#[serde(default)]
69#[non_exhaustive]
70pub struct CacheSettings {
71 pub default_ttl_secs: Option<u64>,
74
75 pub refresh_threshold: Option<f64>,
79
80 pub lock_timeout_ms: Option<u64>,
85}
86
87impl 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 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 pub fn default_ttl(&self) -> Option<Duration> {
128 self.default_ttl_secs.map(Duration::from_secs)
129 }
130
131 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}