sisa_caching_redis/settings.rs
1//! Settings for the Redis store.
2
3use serde::{Deserialize, Serialize};
4use sisa_caching_core::{
5 cache::CacheError,
6 settings::{CacheSettings, NoUnknownFields},
7};
8
9/// The Redis store's own settings, apart from the shared ones. A hybrid store's Redis layer takes
10/// these too, under `distributed`.
11#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
12#[serde(default, deny_unknown_fields)]
13#[non_exhaustive]
14pub struct RedisSettings {
15 /// How many keys each `SCAN` asks for while `remove_prefix` or `clear` walks the store's
16 /// keys: 1,000 by default. Redis treats it as a hint and may return more or fewer. A larger
17 /// batch means fewer round trips but more server work per call. `validate` rejects `0`.
18 pub scan_batch_size: u32,
19}
20
21// A hundred times Redis's own `COUNT` default of 10, so a walk takes few round trips.
22impl Default for RedisSettings {
23 fn default() -> Self {
24 Self {
25 scan_batch_size: 1_000,
26 }
27 }
28}
29
30impl RedisSettings {
31 /// Fails when `scan_batch_size` is 0.
32 pub fn validate(&self) -> Result<(), CacheError> {
33 if self.scan_batch_size == 0 {
34 return Err(CacheError::invalid_settings(
35 "scan_batch_size",
36 "is 0; it must be at least 1",
37 ));
38 }
39
40 Ok(())
41 }
42}
43
44/// Settings for a [`RedisCacheStore`](crate::store::RedisCacheStore): the shared ones and the
45/// Redis store's own. In a config file both sit side by side, and an unknown field fails, so a
46/// misspelled setting can't silently keep its default:
47///
48/// ```
49/// # use sisa_caching_redis::settings::RedisCacheSettings;
50/// let settings: RedisCacheSettings =
51/// serde_json::from_str(r#"{ "default_ttl_secs": 300, "scan_batch_size": 500 }"#).unwrap();
52///
53/// assert_eq!(settings.common.default_ttl_secs, Some(300));
54/// assert_eq!(settings.redis.scan_batch_size, 500);
55/// let misspelled = r#"{ "default_ttl_sec": 300 }"#;
56/// assert!(serde_json::from_str::<RedisCacheSettings>(misspelled).is_err());
57/// ```
58#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
59#[serde(default)]
60#[non_exhaustive]
61pub struct RedisCacheSettings {
62 /// The settings every store has: the default TTL, refresh-ahead and the `get_or_set` lock wait.
63 #[serde(flatten)]
64 pub common: CacheSettings,
65
66 /// The Redis store's own settings: how it walks keys.
67 #[serde(flatten)]
68 pub redis: RedisSettings,
69
70 // Last, so it sees only the fields no other one took, and fails on them.
71 #[serde(flatten, skip_serializing)]
72 pub(crate) unknown_fields: NoUnknownFields,
73}
74
75// Every setting at its default, as `RedisSettings` and `CacheSettings` give them.
76impl Default for RedisCacheSettings {
77 fn default() -> Self {
78 Self {
79 common: CacheSettings::default(),
80 redis: RedisSettings::default(),
81 unknown_fields: NoUnknownFields,
82 }
83 }
84}
85
86impl RedisCacheSettings {
87 /// Fails when a setting is out of range, as [`RedisSettings::validate`] and
88 /// [`CacheSettings::validate`](sisa_caching_core::settings::CacheSettings::validate) say.
89 pub fn validate(&self) -> Result<(), CacheError> {
90 self.common.validate()?;
91 self.redis.validate()
92 }
93}
94
95#[cfg(test)]
96mod tests {
97 use sisa_caching_core::settings::MAX_TTL_SECS;
98
99 use super::*;
100
101 #[test]
102 fn out_of_range_settings_are_rejected() {
103 let batch = |scan_batch_size| RedisCacheSettings {
104 redis: RedisSettings { scan_batch_size },
105 ..RedisCacheSettings::default()
106 };
107 let ttl = RedisCacheSettings {
108 common: {
109 let mut settings = CacheSettings::default();
110 settings.default_ttl_secs = Some(MAX_TTL_SECS + 1);
111 settings
112 },
113 ..RedisCacheSettings::default()
114 };
115
116 assert!(batch(1).validate().is_ok());
117 for (field, settings) in [("scan_batch_size", batch(0)), ("default_ttl_secs", ttl)] {
118 assert!(
119 matches!(settings.validate(), Err(CacheError::InvalidSettings { field: rejected, .. }) if rejected == field),
120 "{field}"
121 );
122 }
123 }
124}