1use std::ffi::OsString;
4use std::fs;
5use std::io::ErrorKind;
6use std::path::{Path, PathBuf};
7use std::sync::atomic::{AtomicU64, Ordering};
8
9use serde::{Deserialize, Serialize};
10
11use crate::NetError;
12
13#[derive(Debug, Clone)]
21pub struct Cache {
22 dir: PathBuf,
23}
24
25#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27pub struct CacheEntry {
28 pub url: String,
30 pub fetched_at_s: u64,
32 #[serde(skip)]
34 pub body: Vec<u8>,
35}
36
37impl Cache {
38 pub fn new(dir: impl Into<PathBuf>) -> Self {
40 Self { dir: dir.into() }
41 }
42
43 pub fn dir(&self) -> &Path {
45 &self.dir
46 }
47
48 pub fn platform_dir() -> Option<PathBuf> {
67 platform_dir_from(std::env::consts::OS, |name| std::env::var_os(name))
68 }
69
70 fn paths(&self, url: &str) -> (PathBuf, PathBuf) {
71 let key = format!("{:016x}", fnv1a64(url.as_bytes()));
72 (
73 self.dir.join(format!("{key}.json")),
74 self.dir.join(format!("{key}.bin")),
75 )
76 }
77
78 pub fn get(&self, url: &str) -> Result<Option<CacheEntry>, NetError> {
84 let (meta_path, body_path) = self.paths(url);
85 let Some(meta) = read_optional(&meta_path)? else {
86 return Ok(None);
87 };
88 let mut entry: CacheEntry =
89 serde_json::from_slice(&meta).map_err(|e| NetError::CorruptEntry {
90 path: meta_path.clone(),
91 reason: e.to_string(),
92 })?;
93 if entry.url != url {
94 return Ok(None);
96 }
97 let Some(body) = read_optional(&body_path)? else {
98 return Ok(None);
99 };
100 entry.body = body;
101 Ok(Some(entry))
102 }
103
104 pub fn put(&self, url: &str, body: &[u8], fetched_at_s: u64) -> Result<(), NetError> {
109 fs::create_dir_all(&self.dir).map_err(|source| NetError::Cache {
110 path: self.dir.clone(),
111 source,
112 })?;
113 let (meta_path, body_path) = self.paths(url);
114 let meta = CacheEntry {
115 url: url.to_owned(),
116 fetched_at_s,
117 body: Vec::new(),
118 };
119 let meta = serde_json::to_vec(&meta).map_err(|e| NetError::CorruptEntry {
120 path: meta_path.clone(),
121 reason: e.to_string(),
122 })?;
123 write_atomic(&body_path, body)?;
124 write_atomic(&meta_path, &meta)
125 }
126}
127
128fn platform_dir_from(os: &str, var: impl Fn(&str) -> Option<OsString>) -> Option<PathBuf> {
131 let set = |name: &str| {
132 var(name)
133 .filter(|value| !value.is_empty())
134 .map(PathBuf::from)
135 };
136 if let Some(dir) = set("HPR_CACHE_DIR") {
137 return Some(dir);
138 }
139 match os {
140 "macos" => set("HOME").map(|home| {
141 home.join("Library")
142 .join("Caches")
143 .join("co.fusionspace.hpr")
144 }),
145 "windows" => {
146 set("LOCALAPPDATA").map(|local| local.join("FusionSpace").join("hpr").join("cache"))
147 }
148 _ => set("XDG_CACHE_HOME")
149 .filter(|dir| dir.is_absolute())
150 .or_else(|| set("HOME").map(|home| home.join(".cache")))
151 .map(|cache| cache.join("fusionspace-hpr")),
152 }
153}
154
155fn read_optional(path: &Path) -> Result<Option<Vec<u8>>, NetError> {
156 match fs::read(path) {
157 Ok(bytes) => Ok(Some(bytes)),
158 Err(e) if e.kind() == ErrorKind::NotFound => Ok(None),
159 Err(source) => Err(NetError::Cache {
160 path: path.to_owned(),
161 source,
162 }),
163 }
164}
165
166fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), NetError> {
167 static NEXT: AtomicU64 = AtomicU64::new(0);
169 let n = NEXT.fetch_add(1, Ordering::Relaxed);
170 let tmp = path.with_extension(format!("{}.{n}.tmp", std::process::id()));
171 let err = |source| NetError::Cache {
172 path: path.to_owned(),
173 source,
174 };
175 fs::write(&tmp, bytes).map_err(err)?;
176 fs::rename(&tmp, path).map_err(err)
177}
178
179fn fnv1a64(bytes: &[u8]) -> u64 {
181 bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, &b| {
182 (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3)
183 })
184}
185
186#[cfg(test)]
187mod tests {
188 use super::*;
189
190 #[test]
191 fn fnv1a64_matches_published_vectors() {
192 assert_eq!(fnv1a64(b""), 0xcbf2_9ce4_8422_2325);
194 assert_eq!(fnv1a64(b"a"), 0xaf63_dc4c_8601_ec8c);
195 assert_eq!(fnv1a64(b"foobar"), 0x8594_4171_f739_67e8);
196 }
197
198 #[test]
199 fn a_stored_body_reads_back() {
200 let dir = tempfile::tempdir().unwrap();
201 let cache = Cache::new(dir.path().join("sub"));
202 assert_eq!(cache.get("https://example.test/a").unwrap(), None);
203 cache.put("https://example.test/a", b"abc", 42).unwrap();
204 let entry = cache.get("https://example.test/a").unwrap().unwrap();
205 assert_eq!(entry.body, b"abc");
206 assert_eq!(entry.fetched_at_s, 42);
207 assert_eq!(cache.get("https://example.test/b").unwrap(), None);
208 }
209
210 #[test]
211 fn another_urls_entry_in_the_slot_reads_as_a_miss() {
212 let dir = tempfile::tempdir().unwrap();
213 let cache = Cache::new(dir.path());
214 cache.put("https://example.test/a", b"abc", 1).unwrap();
215 let (meta_a, body_a) = cache.paths("https://example.test/a");
217 let (meta_b, body_b) = cache.paths("https://example.test/b");
218 fs::rename(meta_a, meta_b).unwrap();
219 fs::rename(body_a, body_b).unwrap();
220 assert_eq!(cache.get("https://example.test/b").unwrap(), None);
221 }
222
223 fn dir_with(os: &str, vars: &[(&str, &str)]) -> Option<PathBuf> {
225 platform_dir_from(os, |name| {
226 vars.iter()
227 .find(|(key, _)| *key == name)
228 .map(|(_, value)| OsString::from(value))
229 })
230 }
231
232 #[test]
233 fn platform_dirs_follow_each_systems_convention() {
234 let home = [("HOME", "/home/u")];
235 assert_eq!(
236 dir_with("macos", &[("HOME", "/Users/u")]),
237 Some(PathBuf::from("/Users/u/Library/Caches/co.fusionspace.hpr"))
238 );
239 assert_eq!(
240 dir_with("windows", &[("LOCALAPPDATA", "C:/Users/u/AppData/Local")]),
241 Some(PathBuf::from(
242 "C:/Users/u/AppData/Local/FusionSpace/hpr/cache"
243 ))
244 );
245 assert_eq!(
246 dir_with("linux", &home),
247 Some(PathBuf::from("/home/u/.cache/fusionspace-hpr"))
248 );
249 #[cfg(unix)]
252 assert_eq!(
253 dir_with(
254 "freebsd",
255 &[("HOME", "/home/u"), ("XDG_CACHE_HOME", "/var/cache/u")]
256 ),
257 Some(PathBuf::from("/var/cache/u/fusionspace-hpr"))
258 );
259 }
260
261 #[test]
264 fn platform_dirs_are_fusionspace_hprs_not_hpr_sims() {
265 let vars = [
266 ("HOME", "/home/u"),
267 ("LOCALAPPDATA", "C:/L"),
268 ("XDG_CACHE_HOME", "/x"),
269 ];
270 for os in ["macos", "windows", "linux", "freebsd"] {
271 let dir = dir_with(os, &vars).unwrap();
272 let text = dir.to_string_lossy().replace('\\', "/");
273 assert!(!text.contains("hpr-sim"), "{os}: {text}");
274 assert!(
275 text.ends_with("/co.fusionspace.hpr")
276 || text.ends_with("/FusionSpace/hpr/cache")
277 || text.ends_with("/fusionspace-hpr"),
278 "{os}: {text}"
279 );
280 }
281 }
282
283 #[test]
284 fn platform_dir_skips_what_the_conventions_skip() {
285 for xdg in ["relative/cache", ""] {
287 assert_eq!(
288 dir_with("linux", &[("HOME", "/home/u"), ("XDG_CACHE_HOME", xdg)]),
289 Some(PathBuf::from("/home/u/.cache/fusionspace-hpr"))
290 );
291 }
292 assert_eq!(dir_with("windows", &[("HOME", "/home/u")]), None);
294 assert_eq!(dir_with("macos", &[("HOME", "")]), None);
295 assert_eq!(dir_with("linux", &[]), None);
296 }
297
298 #[test]
299 fn hpr_cache_dir_overrides_every_platform() {
300 for os in ["macos", "windows", "linux"] {
301 let vars = [
302 ("HPR_CACHE_DIR", "/tmp/hpr"),
303 ("HOME", "/home/u"),
304 ("LOCALAPPDATA", "C:/L"),
305 ("XDG_CACHE_HOME", "/x"),
306 ];
307 assert_eq!(dir_with(os, &vars), Some(PathBuf::from("/tmp/hpr")));
308 }
309 assert_eq!(
311 dir_with("linux", &[("HPR_CACHE_DIR", ""), ("HOME", "/home/u")]),
312 Some(PathBuf::from("/home/u/.cache/fusionspace-hpr"))
313 );
314 }
315
316 #[test]
317 fn corrupt_metadata_is_an_error_not_a_miss() {
318 let dir = tempfile::tempdir().unwrap();
319 let cache = Cache::new(dir.path());
320 cache.put("u", b"x", 1).unwrap();
321 fs::write(cache.paths("u").0, b"{not json").unwrap();
322 assert!(matches!(cache.get("u"), Err(NetError::CorruptEntry { .. })));
323 }
324}