BlueGit

ict rusty-teams

Files

rusty-teams / crates / store / src / image_files.rs

image_files.rs

Initial commit
metis Daniel Däschle · pushed by metis · 7 weeks ago
06e0ae51 History
image_files.rs 7.2 KiB Download Raw
1use std::collections::HashMap;
2use std::fs;
3use std::path::{Path, PathBuf};
4use std::sync::Mutex;
5use std::time::SystemTime;
6
7use crate::error::{Error, Result};
8
9const FNV_OFFSET: u128 = 0x6c62272e07bb014262b821756295c58d;
10const FNV_PRIME: u128 = 0x0000000001000000000000000000013b;
11const TEMP_EXTENSION: &str = "part";
12
13struct Entry {
14 path: PathBuf,
15 size: u64,
16 last_used: SystemTime,
17}
18
19/// Image files in one directory, evicted least recently used first once the total exceeds the cap.
20pub struct ImageFileCache {
21 directory: PathBuf,
22 max_total_bytes: u64,
23 entries: Mutex<HashMap<String, Entry>>,
24}
25
26impl ImageFileCache {
27 /// Indexes the files already in `directory`, so the cache survives restarts.
28 pub fn open(directory: &Path, max_total_bytes: u64) -> Result<Self> {
29 fs::create_dir_all(directory)?;
30 let mut entries = HashMap::new();
31 for file in fs::read_dir(directory)?.flatten() {
32 let path = file.path();
33 let Some(name) = path
34 .file_stem()
35 .and_then(|stem| stem.to_str())
36 .map(str::to_owned)
37 else {
38 continue;
39 };
40 if path
41 .extension()
42 .is_some_and(|extension| extension == TEMP_EXTENSION)
43 {
44 let _ = fs::remove_file(&path);
45 continue;
46 }
47 let Ok(metadata) = file.metadata() else {
48 continue;
49 };
50 entries.insert(
51 name,
52 Entry {
53 size: metadata.len(),
54 last_used: metadata.modified().unwrap_or(SystemTime::UNIX_EPOCH),
55 path,
56 },
57 );
58 }
59 Ok(ImageFileCache {
60 directory: directory.to_owned(),
61 max_total_bytes,
62 entries: Mutex::new(entries),
63 })
64 }
65
66 /// Marks the file as used.
67 pub fn path(&self, key: &str) -> Option<PathBuf> {
68 let mut entries = self.entries.lock().ok()?;
69 let entry = entries.get_mut(&file_stem(key))?;
70 if !entry.path.exists() {
71 entries.remove(&file_stem(key));
72 return None;
73 }
74 entry.last_used = SystemTime::now();
75 touch(&entry.path, entry.last_used);
76 Some(entry.path.clone())
77 }
78
79 pub fn contains(&self, key: &str) -> bool {
80 self.entries
81 .lock()
82 .is_ok_and(|entries| entries.contains_key(&file_stem(key)))
83 }
84
85 /// `extension` without the dot, e.g. `png`.
86 pub fn put(&self, key: &str, bytes: &[u8], extension: &str) -> Result<PathBuf> {
87 let stem = file_stem(key);
88 let path = self.directory.join(format!("{stem}.{extension}"));
89 let temporary = self.directory.join(format!("{stem}.{TEMP_EXTENSION}"));
90 fs::write(&temporary, bytes)?;
91 fs::rename(&temporary, &path)?;
92 let mut entries = self.entries.lock().map_err(|_| Error::Poisoned)?;
93 if let Some(previous) = entries.get(&stem).filter(|entry| entry.path != path) {
94 let _ = fs::remove_file(&previous.path);
95 }
96 entries.insert(
97 stem.clone(),
98 Entry {
99 path: path.clone(),
100 size: bytes.len() as u64,
101 last_used: SystemTime::now(),
102 },
103 );
104 self.evict(&mut entries, &stem);
105 Ok(path)
106 }
107
108 pub fn total_bytes(&self) -> u64 {
109 self.entries
110 .lock()
111 .map_or(0, |entries| entries.values().map(|entry| entry.size).sum())
112 }
113
114 fn evict(&self, entries: &mut HashMap<String, Entry>, keep: &str) {
115 let mut total: u64 = entries.values().map(|entry| entry.size).sum();
116 if total <= self.max_total_bytes {
117 return;
118 }
119 let mut oldest: Vec<(String, SystemTime, u64)> = entries
120 .iter()
121 .filter(|(stem, _)| stem.as_str() != keep)
122 .map(|(stem, entry)| (stem.clone(), entry.last_used, entry.size))
123 .collect();
124 oldest.sort_by_key(|(stem, last_used, _)| (*last_used, stem.clone()));
125 for (stem, _, size) in oldest {
126 if total <= self.max_total_bytes {
127 break;
128 }
129 if let Some(entry) = entries.remove(&stem) {
130 let _ = fs::remove_file(entry.path);
131 }
132 total -= size;
133 }
134 }
135}
136
137fn touch(path: &Path, time: SystemTime) {
138 if let Ok(file) = fs::OpenOptions::new().write(true).open(path) {
139 let _ = file.set_modified(time);
140 }
141}
142
143fn file_stem(key: &str) -> String {
144 let hash = key.bytes().fold(FNV_OFFSET, |hash, byte| {
145 (hash ^ u128::from(byte)).wrapping_mul(FNV_PRIME)
146 });
147 format!("{hash:032x}")
148}
149
150#[cfg(test)]
151mod tests {
152 use std::time::Duration;
153
154 use super::*;
155
156 #[test]
157 fn put_then_path_returns_the_same_file() {
158 let directory = tempfile::tempdir().unwrap();
159 let cache = ImageFileCache::open(directory.path(), 1000).unwrap();
160 assert!(cache.path("k").is_none());
161 let path = cache.put("k", b"abc", "png").unwrap();
162 assert_eq!(fs::read(&path).unwrap(), b"abc");
163 assert_eq!(cache.path("k"), Some(path));
164 assert!(cache.contains("k"));
165 }
166
167 #[test]
168 fn least_recently_used_files_go_first() {
169 let directory = tempfile::tempdir().unwrap();
170 let cache = ImageFileCache::open(directory.path(), 25).unwrap();
171 let first = cache.put("a", &[0; 10], "png").unwrap();
172 std::thread::sleep(Duration::from_millis(5));
173 cache.put("b", &[0; 10], "png").unwrap();
174 std::thread::sleep(Duration::from_millis(5));
175 assert!(cache.path("a").is_some());
176 std::thread::sleep(Duration::from_millis(5));
177 cache.put("c", &[0; 10], "png").unwrap();
178 assert!(cache.contains("a") && cache.contains("c"));
179 assert!(!cache.contains("b"));
180 assert!(first.exists());
181 assert_eq!(cache.total_bytes(), 20);
182 }
183
184 #[test]
185 fn an_oversized_new_file_is_kept_and_everything_else_evicted() {
186 let directory = tempfile::tempdir().unwrap();
187 let cache = ImageFileCache::open(directory.path(), 10).unwrap();
188 cache.put("a", &[0; 5], "png").unwrap();
189 cache.put("big", &[0; 50], "png").unwrap();
190 assert!(cache.contains("big") && !cache.contains("a"));
191 }
192
193 #[test]
194 fn reopening_indexes_existing_files_and_drops_partial_writes() {
195 let directory = tempfile::tempdir().unwrap();
196 let cache = ImageFileCache::open(directory.path(), 100).unwrap();
197 let path = cache.put("k", b"abc", "jpg").unwrap();
198 fs::write(directory.path().join("x.part"), b"zz").unwrap();
199 drop(cache);
200 let reopened = ImageFileCache::open(directory.path(), 100).unwrap();
201 assert_eq!(reopened.path("k"), Some(path));
202 assert_eq!(reopened.total_bytes(), 3);
203 assert!(!directory.path().join("x.part").exists());
204 }
205
206 #[test]
207 fn replacing_a_key_with_another_extension_removes_the_old_file() {
208 let directory = tempfile::tempdir().unwrap();
209 let cache = ImageFileCache::open(directory.path(), 100).unwrap();
210 let old = cache.put("k", b"a", "png").unwrap();
211 let new = cache.put("k", b"b", "jpg").unwrap();
212 assert!(!old.exists() && new.exists());
213 }
214}