Skip to main content

devpage_core/
cache.rs

1//! What server mode's cache keeps, and the port that chooses what it lets go.
2//! The cache itself — files on the PVC — is the binary's; deciding which
3//! entries to delete when it is past its limit is a pure function of them.
4
5use std::time::SystemTime;
6
7/// One version's copy in the cache.
8#[derive(Clone, Debug, PartialEq, Eq)]
9pub struct Entry {
10    /// The document's id.
11    pub document: String,
12    /// The version's number.
13    pub version: u64,
14    /// The bytes it takes on disk.
15    pub bytes: u64,
16    /// When it was last read.
17    pub read: SystemTime,
18}
19
20impl Entry {
21    /// The entry's key: its document and version.
22    pub fn key(&self) -> (String, u64) {
23        (self.document.clone(), self.version)
24    }
25}
26
27/// The eviction policy: given every entry, the cache's limit and its size,
28/// which entries to delete. It decides and never acts — the cache deletes
29/// them, skipping any being served.
30pub trait Eviction: Send + Sync {
31    /// The keys of the entries to delete from `entries` so the cache fits
32    /// `limit` bytes; empty when it already does.
33    fn choose(&self, entries: &[Entry], limit: u64) -> Vec<(String, u64)>;
34}
35
36/// The least recently read first, until the cache is at 90% of its limit, so
37/// a full cache doesn't evict on every read.
38pub struct Lru;
39
40impl Eviction for Lru {
41    fn choose(&self, entries: &[Entry], limit: u64) -> Vec<(String, u64)> {
42        let mut size: u64 = entries.iter().map(|e| e.bytes).sum();
43        if size <= limit {
44            return Vec::new();
45        }
46        let target = limit / 10 * 9;
47        let mut oldest: Vec<&Entry> = entries.iter().collect();
48        oldest.sort_by_key(|e| e.read);
49        let mut chosen = Vec::new();
50        for entry in oldest {
51            if size <= target {
52                break;
53            }
54            size -= entry.bytes;
55            chosen.push(entry.key());
56        }
57        chosen
58    }
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64    use std::time::Duration;
65
66    fn entry(document: &str, bytes: u64, age: u64) -> Entry {
67        Entry {
68            document: document.into(),
69            version: 1,
70            bytes,
71            read: SystemTime::UNIX_EPOCH + Duration::from_secs(1000 - age),
72        }
73    }
74
75    #[test]
76    fn under_the_limit_nothing_goes() {
77        let entries = [entry("a", 40, 1), entry("b", 50, 2)];
78        assert!(Lru.choose(&entries, 100).is_empty());
79    }
80
81    #[test]
82    fn past_the_limit_the_least_recently_read_go_until_it_is_at_ninety_percent() {
83        let entries = [
84            entry("new", 30, 1),
85            entry("old", 30, 9),
86            entry("mid", 30, 5),
87            entry("older", 30, 7),
88        ];
89        // 120 bytes against a limit of 100: down to 90 takes the oldest only.
90        assert_eq!(Lru.choose(&entries, 100), [("old".to_string(), 1)]);
91        // Against 60, down to 54: three go, oldest first.
92        assert_eq!(
93            Lru.choose(&entries, 60),
94            [
95                ("old".to_string(), 1),
96                ("older".to_string(), 1),
97                ("mid".to_string(), 1)
98            ]
99        );
100    }
101}