Skip to main content

loco_rs/config/
cache.rs

1use serde::{Deserialize, Serialize};
2
3/// Cache configurations for the application
4#[derive(Debug, Clone, Default, Deserialize, Serialize)]
5#[serde(tag = "kind")]
6#[non_exhaustive]
7pub enum CacheConfig {
8    #[cfg(feature = "cache_inmem")]
9    /// In-memory cache
10    InMem(InMemCacheConfig),
11    #[cfg(feature = "cache_redis")]
12    /// Redis cache
13    Redis(RedisCacheConfig),
14    #[cfg(feature = "with-db")]
15    /// Cache stored in the application database (Postgres or `SQLite`)
16    Database(DatabaseCacheConfig),
17    /// Null cache
18    #[default]
19    Null,
20}
21
22#[derive(Debug, Clone, Deserialize, Serialize)]
23pub struct InMemCacheConfig {
24    #[serde(default = "cache_in_mem_max_capacity")]
25    pub max_capacity: u64,
26}
27
28fn cache_in_mem_max_capacity() -> u64 {
29    32 * 1024 * 1024
30}
31
32#[derive(Debug, Clone, Deserialize, Serialize)]
33pub struct RedisCacheConfig {
34    pub uri: String,
35    /// Sets the maximum number of connections managed by the pool.
36    pub max_size: u32,
37}
38
39/// Settings of the database cache (`cache.kind: Database`). Both fields have
40/// defaults, so `kind: Database` alone is a complete configuration.
41#[cfg(feature = "with-db")]
42#[derive(Debug, Clone, Deserialize, Serialize)]
43pub struct DatabaseCacheConfig {
44    /// Sweep expired rows after this many writes. `0` turns the sweep off.
45    #[serde(default = "cache_db_sweep_every")]
46    pub sweep_every: u64,
47    /// The most expired rows one sweep deletes.
48    #[serde(default = "cache_db_sweep_batch")]
49    pub sweep_batch: u64,
50}
51
52#[cfg(feature = "with-db")]
53impl Default for DatabaseCacheConfig {
54    fn default() -> Self {
55        Self {
56            sweep_every: cache_db_sweep_every(),
57            sweep_batch: cache_db_sweep_batch(),
58        }
59    }
60}
61
62#[cfg(feature = "with-db")]
63fn cache_db_sweep_every() -> u64 {
64    100
65}
66
67#[cfg(feature = "with-db")]
68fn cache_db_sweep_batch() -> u64 {
69    1000
70}
71
72#[cfg(all(test, feature = "with-db"))]
73mod tests {
74    use super::*;
75
76    #[test]
77    fn database_cache_needs_nothing_but_its_kind() {
78        let CacheConfig::Database(cfg) = serde_yaml::from_str("kind: Database").unwrap() else {
79            panic!("expected the Database kind");
80        };
81        assert_eq!((cfg.sweep_every, cfg.sweep_batch), (100, 1000));
82
83        let CacheConfig::Database(cfg) =
84            serde_yaml::from_str("kind: Database\nsweep_every: 5\nsweep_batch: 7").unwrap()
85        else {
86            panic!("expected the Database kind");
87        };
88        assert_eq!((cfg.sweep_every, cfg.sweep_batch), (5, 7));
89    }
90}