1use std::fs;
34use std::io::Write;
35use std::path::{Path, PathBuf};
36use std::time::{Duration, SystemTime};
37
38use sha2::{Digest, Sha256};
39
40pub(crate) const FRESH_FOR: Duration = Duration::from_secs(7 * 24 * 60 * 60);
42
43pub(crate) const KEPT_FOR: Duration = Duration::from_secs(30 * 24 * 60 * 60);
46
47pub(crate) const MAX_BYTES: u64 = 64 * 1024 * 1024;
49
50const UNFINISHED: &str = "part";
52
53#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct Kept {
57 pub bytes: Vec<u8>,
58 pub fresh: bool,
59}
60
61#[derive(Debug, Clone)]
64pub struct DiskCache {
65 directory: Option<PathBuf>,
67 fresh_for: Duration,
68 kept_for: Duration,
69 max_bytes: u64,
70}
71
72impl DiskCache {
73 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 pub fn nowhere() -> Self {
82 Self { directory: None, fresh_for: FRESH_FOR, kept_for: KEPT_FOR, max_bytes: MAX_BYTES }
83 }
84
85 #[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 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 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 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 pub fn forget(&self, what: &str) {
131 if let Some(path) = self.path(what) {
132 let _ = fs::remove_file(path);
133 }
134 }
135
136 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 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 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 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 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 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 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 assert_eq!(cache.read("https://example.com/a.jpg", now - DAY), Some(stale));
232 assert_eq!(cache.read("https://example.com/b.jpg", now), None);
234
235 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 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 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 assert_eq!(cache.sweep(now), (0, 20));
293 let _ = fs::remove_dir_all(directory);
294 }
295}