Skip to main content

cosmic_applet_avestruz/
disk_cache.rs

1// SPDX-License-Identifier: MIT
2
3//! What was fetched from the web, kept on disk so that it is not fetched
4//! again at every start.
5//!
6//! A [`DiskCache`] is a directory of files, one for each thing kept,
7//! named by the hash of what it is kept as: its address, and which form
8//! of it this is. Nothing in a name says whose picture it is. What is
9//! kept, and how it is written, is its owner's to say (see
10//! [`crate::images`], which keeps avatars); this is where it is put, how
11//! long it counts as fresh, and what goes when there is too much.
12//!
13//! A file is fresh for a while after it was written. Past that it is
14//! still there, but stale: its owner asks the web again, and falls back
15//! on it if nobody answers. So what changed at the same address is seen
16//! within that while, and what is on disk still shows with no network.
17//!
18//! What is used is written anew as it goes stale, so a file that has
19//! grown old was not asked for in a long time. Those go at the start of a
20//! run (see [`DiskCache::sweep`]), and after them the oldest, for as long
21//! as the directory holds more than it may.
22//!
23//! | Limit | Value | Constant |
24//! |---|---|---|
25//! | Fresh for | 7 days | [`FRESH_FOR`] |
26//! | Kept for | 30 days | [`KEPT_FOR`] |
27//! | All of it | 64 MiB | [`MAX_BYTES`] |
28//!
29//! It is a cache: losing any of it costs a fetch. A file that cannot be
30//! written is not kept, one that cannot be read was not there, and
31//! neither is said to anyone but the journal.
32
33use std::fs;
34use std::io::Write;
35use std::path::{Path, PathBuf};
36use std::time::{Duration, SystemTime};
37
38use sha2::{Digest, Sha256};
39
40/// How long what is kept counts as what is there now.
41pub(crate) const FRESH_FOR: Duration = Duration::from_secs(7 * 24 * 60 * 60);
42
43/// How long what is kept stays without being written anew: what is
44/// older was not asked for since it went stale.
45pub(crate) const KEPT_FOR: Duration = Duration::from_secs(30 * 24 * 60 * 60);
46
47/// How many bytes the files kept may take, all together.
48pub(crate) const MAX_BYTES: u64 = 64 * 1024 * 1024;
49
50/// What a file that is being written ends in, until it is whole.
51const UNFINISHED: &str = "part";
52
53/// What was kept of something, and whether it still counts as what is
54/// there.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct Kept {
57    pub bytes: Vec<u8>,
58    pub fresh: bool,
59}
60
61/// A directory of things fetched, kept by what they are (see the
62/// [module](self)).
63#[derive(Debug, Clone)]
64pub struct DiskCache {
65    /// Where the files are. `None` keeps nothing: there is nowhere to.
66    directory: Option<PathBuf>,
67    fresh_for: Duration,
68    kept_for: Duration,
69    max_bytes: u64,
70}
71
72impl DiskCache {
73    /// The cache of avatars: under the user's cache directory, which is
74    /// what may be deleted at any time.
75    pub fn of_avatars() -> Self {
76        let directory = dirs::cache_dir().map(|cache| cache.join("cosmic-applet-avestruz").join("avatars"));
77        Self { directory, fresh_for: FRESH_FOR, kept_for: KEPT_FOR, max_bytes: MAX_BYTES }
78    }
79
80    /// A cache that keeps nothing.
81    pub fn nowhere() -> Self {
82        Self { directory: None, fresh_for: FRESH_FOR, kept_for: KEPT_FOR, max_bytes: MAX_BYTES }
83    }
84
85    /// A cache in `directory`, with limits of its own.
86    #[cfg(test)]
87    pub fn at(directory: PathBuf, fresh_for: Duration, kept_for: Duration, max_bytes: u64) -> Self {
88        Self { directory: Some(directory), fresh_for, kept_for, max_bytes }
89    }
90
91    /// The file `what` is kept in: its hash, so that any address makes a
92    /// name, and none can be read from one.
93    fn path(&self, what: &str) -> Option<PathBuf> {
94        let name: String = Sha256::digest(what.as_bytes()).iter().map(|byte| format!("{byte:02x}")).collect();
95        Some(self.directory.as_ref()?.join(name))
96    }
97
98    /// What is kept as `what`, if anything is, and whether it is fresh
99    /// at `now`. What says it was written after `now` is stale: a clock
100    /// was wrong, and there is no telling how old it is.
101    pub fn read(&self, what: &str, now: SystemTime) -> Option<Kept> {
102        let path = self.path(what)?;
103        let written = fs::metadata(&path).and_then(|file| file.modified()).ok()?;
104        let bytes = fs::read(&path).ok()?;
105        let fresh = now.duration_since(written).is_ok_and(|age| age < self.fresh_for);
106        Some(Kept { bytes, fresh })
107    }
108
109    /// Keep `bytes` as `what`, in place of what was kept as it: whole or
110    /// not at all, whoever else reads it meanwhile.
111    pub fn write(&self, what: &str, bytes: &[u8]) {
112        let Some(path) = self.path(what) else {
113            return;
114        };
115        let unfinished = path.with_extension(format!("{}-{UNFINISHED}", std::process::id()));
116        let written = (|| {
117            if let Some(directory) = path.parent() {
118                fs::create_dir_all(directory)?;
119            }
120            fs::File::create(&unfinished)?.write_all(bytes)?;
121            fs::rename(&unfinished, &path)
122        })();
123        if let Err(e) = written {
124            tracing::debug!("nothing kept in {}: {e}", path.display());
125            let _ = fs::remove_file(&unfinished);
126        }
127    }
128
129    /// Keep nothing as `what` any more: it is not there to be had.
130    pub fn forget(&self, what: &str) {
131        if let Some(path) = self.path(what) {
132            let _ = fs::remove_file(path);
133        }
134    }
135
136    /// Take out what was not asked for in a long time, as of `now`: what
137    /// was written longer ago than files are kept for, and what was left
138    /// half written. Then the oldest, until what stays is no more than
139    /// may be kept. Returns how many files went, and how many bytes stay.
140    pub fn sweep(&self, now: SystemTime) -> (usize, u64) {
141        let Some(files) = self.directory.as_deref().and_then(|directory| fs::read_dir(directory).ok()) else {
142            return (0, 0);
143        };
144        let mut gone = 0;
145        let mut remove = |path: &Path| {
146            if fs::remove_file(path).is_ok() {
147                gone += 1;
148            }
149        };
150        let mut kept: Vec<(SystemTime, u64, PathBuf)> = Vec::new();
151        for file in files.flatten() {
152            let (path, Ok(about)) = (file.path(), file.metadata()) else {
153                continue;
154            };
155            if !about.is_file() {
156                continue;
157            }
158            let written = about.modified().unwrap_or(SystemTime::UNIX_EPOCH);
159            let age = now.duration_since(written).unwrap_or_default();
160            // Left by a run that ended while it wrote: not while it may
161            // still be one that is being written.
162            let unfinished = path.extension().is_some_and(|ends| ends.to_string_lossy().ends_with(UNFINISHED));
163            match unfinished {
164                true if age > Duration::from_secs(60) => remove(&path),
165                true => {}
166                false if age > self.kept_for => remove(&path),
167                false => kept.push((written, about.len(), path)),
168            }
169        }
170        let mut bytes: u64 = kept.iter().map(|(_, size, _)| size).sum();
171        kept.sort();
172        for (_, size, path) in &kept {
173            if bytes <= self.max_bytes {
174                break;
175            }
176            remove(path);
177            bytes -= size;
178        }
179        (gone, bytes)
180    }
181}
182
183#[cfg(test)]
184mod tests {
185    use std::fs;
186    use std::path::PathBuf;
187    use std::time::{Duration, SystemTime};
188
189    use super::{DiskCache, Kept};
190
191    const DAY: Duration = Duration::from_secs(24 * 60 * 60);
192
193    /// An empty directory of this test's own, by `name`.
194    fn directory(name: &str) -> PathBuf {
195        let path = std::env::temp_dir().join(format!("avestruz-test-{}-cache-{name}", std::process::id()));
196        let _ = fs::remove_dir_all(&path);
197        path
198    }
199
200    /// A cache in a directory of its own: fresh for a week, kept for a
201    /// month, of `max_bytes` at the most.
202    fn cache(name: &str, max_bytes: u64) -> (DiskCache, PathBuf) {
203        let directory = directory(name);
204        (DiskCache::at(directory.clone(), 7 * DAY, 30 * DAY, max_bytes), directory)
205    }
206
207    /// The names of the files in `directory`.
208    fn names(directory: &PathBuf) -> Vec<String> {
209        let mut names: Vec<String> =
210            fs::read_dir(directory).unwrap().map(|file| file.unwrap().file_name().to_string_lossy().into_owned()).collect();
211        names.sort();
212        names
213    }
214
215    #[test]
216    fn what_was_kept_is_read_back_and_is_fresh_for_a_while() {
217        let (cache, directory) = cache("fresh", 1_000);
218        assert_eq!(cache.read("https://example.com/a.jpg", SystemTime::now()), None);
219
220        // Now is after it was written: a file says when by a clock that
221        // is never ahead of the one that is read here.
222        cache.write("https://example.com/a.jpg", b"a picture");
223        let now = SystemTime::now();
224        let fresh = Kept { bytes: b"a picture".to_vec(), fresh: true };
225        assert_eq!(cache.read("https://example.com/a.jpg", now), Some(fresh.clone()));
226        assert_eq!(cache.read("https://example.com/a.jpg", now + 6 * DAY), Some(fresh));
227        // Past that it is still there, and said to be stale.
228        let stale = Kept { bytes: b"a picture".to_vec(), fresh: false };
229        assert_eq!(cache.read("https://example.com/a.jpg", now + 8 * DAY), Some(stale.clone()));
230        // So is one a wrong clock wrote: there is no telling its age.
231        assert_eq!(cache.read("https://example.com/a.jpg", now - DAY), Some(stale));
232        // Another address, or another form of the same, is another file.
233        assert_eq!(cache.read("https://example.com/b.jpg", now), None);
234
235        // Written again, it is what was written last; forgotten, nothing.
236        cache.write("https://example.com/a.jpg", b"another");
237        assert_eq!(cache.read("https://example.com/a.jpg", now).map(|kept| kept.bytes), Some(b"another".to_vec()));
238        cache.forget("https://example.com/a.jpg");
239        assert_eq!(cache.read("https://example.com/a.jpg", now), None);
240        let _ = fs::remove_dir_all(directory);
241    }
242
243    #[test]
244    fn a_name_says_nothing_of_the_address_and_any_address_makes_one() {
245        let (cache, directory) = cache("names", 1_000);
246        let address = "https://example.com/../../etc/passwd?who=ana&size=64 px";
247        cache.write(address, b"x");
248        let names = names(&directory);
249        assert_eq!(names.len(), 1, "written whole, with nothing left beside it: {names:?}");
250        assert!(names[0].len() == 64 && names[0].chars().all(|c| c.is_ascii_hexdigit()), "{names:?}");
251        let _ = fs::remove_dir_all(directory);
252    }
253
254    #[test]
255    fn a_cache_with_nowhere_to_keep_anything_keeps_nothing() {
256        let cache = DiskCache::nowhere();
257        cache.write("https://example.com/a.jpg", b"a picture");
258        assert_eq!(cache.read("https://example.com/a.jpg", SystemTime::now()), None);
259        cache.forget("https://example.com/a.jpg");
260        assert_eq!(cache.sweep(SystemTime::now()), (0, 0));
261    }
262
263    #[test]
264    fn a_sweep_takes_what_grew_old_and_then_the_oldest_until_it_fits() {
265        let (cache, directory) = cache("sweep", 25);
266        let now = SystemTime::now();
267        let aged = |what: &str, days: u32| {
268            cache.write(what, b"ten bytes!");
269            let file = fs::File::options().write(true).open(cache.path(what).unwrap()).unwrap();
270            file.set_modified(now - days * DAY).unwrap();
271        };
272        aged("grown old", 31);
273        aged("oldest", 20);
274        aged("older", 10);
275        aged("newer", 2);
276        aged("newest", 0);
277        // Left half written by a run that is over, and by one that may
278        // not be.
279        let left = directory.join("0123.999-part");
280        fs::write(&left, b"half").unwrap();
281        fs::File::options().write(true).open(&left).unwrap().set_modified(now - DAY).unwrap();
282        fs::write(directory.join("4567.998-part"), b"half").unwrap();
283
284        // What grew old goes, and what was left behind; then the oldest,
285        // until two of ten bytes are what stays.
286        assert_eq!(cache.sweep(now), (4, 20));
287        let stays = |what: &str| cache.read(what, now).is_some();
288        assert!(stays("newest") && stays("newer"));
289        assert!(!stays("older") && !stays("oldest") && !stays("grown old"));
290        assert!(!left.exists() && directory.join("4567.998-part").exists());
291        // Nothing more goes the next time.
292        assert_eq!(cache.sweep(now), (0, 20));
293        let _ = fs::remove_dir_all(directory);
294    }
295}