Skip to main content

adler_core/
cache.rs

1//! Cross-run result cache.
2//!
3//! Re-running a scan minutes apart should not re-hit every site. The cache
4//! persists `Found` / `NotFound` verdicts keyed by `(site name, username)`
5//! and guarded by:
6//!
7//! - a **TTL**: entries older than the configured age are ignored (and
8//!   pruned on load), and
9//! - a **site signature**: a deterministic hash of the site's URL template
10//!   and signal list. If the site definition changes, its old cache entries
11//!   no longer match and are treated as misses.
12//!
13//! `Uncertain` outcomes are intentionally never cached — they're transient
14//! (rate limits, network blips) and caching them would freeze a temporary
15//! failure for the whole TTL window.
16//!
17//! Access pattern is bulk: [`Cache::load`] once at scan start, in-memory
18//! [`Cache::get`] / [`Cache::put`] during the scan, [`Cache::save`] once at
19//! the end. There are no concurrent disk writes, so a plain JSON file with
20//! an atomic temp-then-rename save is enough — no embedded database needed.
21
22use std::collections::HashMap;
23use std::path::{Path, PathBuf};
24use std::time::{Duration, SystemTime, UNIX_EPOCH};
25
26use serde::{Deserialize, Serialize};
27
28use crate::check::{CheckOutcome, MatchKind};
29use crate::error::Result;
30use crate::site::Site;
31use crate::username::Username;
32
33const CACHE_VERSION: u32 = 1;
34const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
35const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
36
37/// In-memory cache backed by a JSON file.
38#[derive(Debug)]
39pub struct Cache {
40    path: PathBuf,
41    ttl: Duration,
42    entries: HashMap<(String, String), Entry>,
43    dirty: bool,
44}
45
46#[derive(Debug, Clone)]
47struct Entry {
48    signature: u64,
49    stored_at: u64,
50    outcome: CheckOutcome,
51}
52
53#[derive(Serialize, Deserialize)]
54struct StoredEntry {
55    site: String,
56    username: String,
57    signature: u64,
58    stored_at: u64,
59    outcome: CheckOutcome,
60}
61
62#[derive(Serialize, Deserialize)]
63struct CacheFile {
64    version: u32,
65    entries: Vec<StoredEntry>,
66}
67
68impl Cache {
69    /// Load a cache from `path`, dropping entries older than `ttl`.
70    ///
71    /// Infallible: a missing, unreadable, or corrupt file yields an empty
72    /// cache (a warning is logged). The cache should never be the reason a
73    /// scan fails.
74    pub fn load(path: PathBuf, ttl: Duration) -> Self {
75        let mut cache = Self {
76            path,
77            ttl,
78            entries: HashMap::new(),
79            dirty: false,
80        };
81        let bytes = match std::fs::read(&cache.path) {
82            Ok(b) => b,
83            Err(err) if err.kind() == std::io::ErrorKind::NotFound => return cache,
84            Err(err) => {
85                tracing::warn!(error = %err, path = %cache.path.display(), "cache read failed");
86                return cache;
87            }
88        };
89        let parsed: CacheFile = match serde_json::from_slice(&bytes) {
90            Ok(f) => f,
91            Err(err) => {
92                tracing::warn!(error = %err, "cache file corrupt; starting empty");
93                return cache;
94            }
95        };
96        if parsed.version != CACHE_VERSION {
97            tracing::info!(
98                found = parsed.version,
99                expected = CACHE_VERSION,
100                "cache version mismatch; starting empty"
101            );
102            return cache;
103        }
104        let now = now_unix();
105        let ttl_secs = ttl.as_secs();
106        for stored in parsed.entries {
107            if now.saturating_sub(stored.stored_at) > ttl_secs {
108                cache.dirty = true; // expired entry pruned; persist the smaller file
109                continue;
110            }
111            cache.entries.insert(
112                (stored.site, stored.username),
113                Entry {
114                    signature: stored.signature,
115                    stored_at: stored.stored_at,
116                    outcome: stored.outcome,
117                },
118            );
119        }
120        cache
121    }
122
123    /// Look up a cached outcome for `site` + `username`.
124    ///
125    /// Returns `None` on a miss, a TTL expiry, or a site-signature mismatch
126    /// (the site definition changed since the entry was stored).
127    pub fn get(&self, site: &Site, username: &Username) -> Option<CheckOutcome> {
128        let key = (site.name.clone(), username.as_str().to_owned());
129        let entry = self.entries.get(&key)?;
130        if entry.signature != signature(site) {
131            return None;
132        }
133        if now_unix().saturating_sub(entry.stored_at) > self.ttl.as_secs() {
134            return None;
135        }
136        Some(entry.outcome.clone())
137    }
138
139    /// Store an outcome. `Uncertain` outcomes are ignored (not cached).
140    pub fn put(&mut self, site: &Site, username: &Username, outcome: CheckOutcome) {
141        if matches!(outcome.kind, MatchKind::Uncertain) {
142            return;
143        }
144        let key = (site.name.clone(), username.as_str().to_owned());
145        self.entries.insert(
146            key,
147            Entry {
148                signature: signature(site),
149                stored_at: now_unix(),
150                outcome,
151            },
152        );
153        self.dirty = true;
154    }
155
156    /// Persist the cache to disk if anything changed since load. Writes
157    /// atomically (temp file + rename) and creates parent directories.
158    pub fn save(&self) -> Result<()> {
159        if !self.dirty {
160            return Ok(());
161        }
162        if let Some(parent) = self.path.parent() {
163            std::fs::create_dir_all(parent)?;
164        }
165        let mut entries: Vec<StoredEntry> = self
166            .entries
167            .iter()
168            .map(|((site, username), entry)| StoredEntry {
169                site: site.clone(),
170                username: username.clone(),
171                signature: entry.signature,
172                stored_at: entry.stored_at,
173                outcome: entry.outcome.clone(),
174            })
175            .collect();
176        entries.sort_by(|a, b| {
177            a.site
178                .cmp(&b.site)
179                .then_with(|| a.username.cmp(&b.username))
180        });
181        let file = CacheFile {
182            version: CACHE_VERSION,
183            entries,
184        };
185        let json = serde_json::to_string_pretty(&file)?;
186        let tmp = self.path.with_extension("json.tmp");
187        std::fs::write(&tmp, json)?;
188        std::fs::rename(&tmp, &self.path)?;
189        Ok(())
190    }
191
192    /// Number of live entries.
193    pub fn len(&self) -> usize {
194        self.entries.len()
195    }
196
197    /// True if the cache has no entries.
198    pub fn is_empty(&self) -> bool {
199        self.entries.is_empty()
200    }
201
202    /// Delete the cache file at `path`. A missing file is not an error.
203    pub fn clear(path: &Path) -> Result<()> {
204        match std::fs::remove_file(path) {
205            Ok(()) => Ok(()),
206            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
207            Err(err) => Err(err.into()),
208        }
209    }
210
211    /// Default cache file location: `$XDG_CACHE_HOME/adler/cache.json`,
212    /// falling back to `$HOME/.cache/adler/cache.json`, then a relative
213    /// path if neither env var is set.
214    pub fn default_path() -> PathBuf {
215        if let Some(xdg) = std::env::var_os("XDG_CACHE_HOME") {
216            return PathBuf::from(xdg).join("adler").join("cache.json");
217        }
218        if let Some(home) = std::env::var_os("HOME") {
219            return PathBuf::from(home)
220                .join(".cache")
221                .join("adler")
222                .join("cache.json");
223        }
224        PathBuf::from("adler-cache.json")
225    }
226}
227
228/// Deterministic FNV-1a hash of a site's URL template and signal list.
229///
230/// Must be stable across processes, so we cannot use the std `DefaultHasher`
231/// (it's randomly seeded). FNV-1a over the serialized signals + URL is
232/// deterministic and collision-resistant enough for cache invalidation.
233fn signature(site: &Site) -> u64 {
234    let signals = serde_json::to_string(&site.signals).unwrap_or_default();
235    let mut hash = FNV_OFFSET;
236    for byte in site.url.as_str().bytes().chain(signals.bytes()) {
237        hash ^= u64::from(byte);
238        hash = hash.wrapping_mul(FNV_PRIME);
239    }
240    hash
241}
242
243fn now_unix() -> u64 {
244    SystemTime::now()
245        .duration_since(UNIX_EPOCH)
246        .map_or(0, |d| d.as_secs())
247}
248
249#[cfg(test)]
250mod tests {
251    use super::*;
252    use crate::site::{Signal, UrlTemplate};
253
254    fn site(name: &str) -> Site {
255        Site {
256            name: name.into(),
257            url: UrlTemplate::new("https://example.com/{username}").unwrap(),
258            signals: vec![Signal::StatusFound { codes: vec![200] }],
259            known_present: None,
260            known_absent: None,
261            extract: Vec::new(),
262            tags: Vec::new(),
263            request_headers: std::collections::BTreeMap::new(),
264            regex_check: None,
265            engine: None,
266            strip_bad_char: None,
267            request_method: crate::site::HttpMethod::Get,
268            request_body: None,
269            protection: Vec::new(),
270            disabled: false,
271            disabled_reason: None,
272            source: None,
273            popularity: None,
274            access: crate::AccessPolicy::default(),
275        }
276    }
277
278    fn outcome(kind: MatchKind) -> CheckOutcome {
279        CheckOutcome {
280            site: "Example".into(),
281            url: "https://example.com/alice".into(),
282            kind,
283            reason: None,
284            elapsed_ms: 5,
285            enrichment: std::collections::BTreeMap::new(),
286            evidence: Vec::new(),
287            transport: None,
288            escalations: 0,
289        }
290    }
291
292    fn tmp_path(tag: &str) -> PathBuf {
293        let mut p = std::env::temp_dir();
294        p.push(format!(
295            "adler-cache-test-{tag}-{}.json",
296            std::process::id()
297        ));
298        p
299    }
300
301    fn empty_cache(ttl: Duration) -> Cache {
302        Cache {
303            path: tmp_path("mem"),
304            ttl,
305            entries: HashMap::new(),
306            dirty: false,
307        }
308    }
309
310    #[test]
311    fn put_then_get_round_trips() {
312        let mut cache = empty_cache(Duration::from_secs(3600));
313        let s = site("Example");
314        let user = Username::new("alice").unwrap();
315        cache.put(&s, &user, outcome(MatchKind::Found));
316        let got = cache.get(&s, &user).unwrap();
317        assert_eq!(got.kind, MatchKind::Found);
318    }
319
320    #[test]
321    fn uncertain_is_not_cached() {
322        let mut cache = empty_cache(Duration::from_secs(3600));
323        let s = site("Example");
324        let user = Username::new("alice").unwrap();
325        cache.put(&s, &user, outcome(MatchKind::Uncertain));
326        assert!(cache.get(&s, &user).is_none());
327        assert!(cache.is_empty());
328    }
329
330    #[test]
331    fn get_misses_on_different_username() {
332        let mut cache = empty_cache(Duration::from_secs(3600));
333        let s = site("Example");
334        cache.put(
335            &s,
336            &Username::new("alice").unwrap(),
337            outcome(MatchKind::Found),
338        );
339        assert!(cache.get(&s, &Username::new("bob").unwrap()).is_none());
340    }
341
342    #[test]
343    fn get_misses_when_signature_changes() {
344        let mut cache = empty_cache(Duration::from_secs(3600));
345        let s = site("Example");
346        let user = Username::new("alice").unwrap();
347        cache.put(&s, &user, outcome(MatchKind::Found));
348
349        // Same name, different signals → different signature → miss.
350        let mut changed = site("Example");
351        changed.signals = vec![Signal::StatusNotFound { codes: vec![404] }];
352        assert!(cache.get(&changed, &user).is_none());
353    }
354
355    #[test]
356    fn get_misses_on_expired_entry() {
357        let mut cache = empty_cache(Duration::from_secs(0));
358        let s = site("Example");
359        let user = Username::new("alice").unwrap();
360        // stored_at = now, ttl = 0 → already expired (now - stored_at > 0 is
361        // false at the same second, so force an old timestamp).
362        cache.entries.insert(
363            ("Example".into(), "alice".into()),
364            Entry {
365                signature: signature(&s),
366                stored_at: now_unix().saturating_sub(10),
367                outcome: outcome(MatchKind::Found),
368            },
369        );
370        assert!(cache.get(&s, &user).is_none());
371    }
372
373    #[test]
374    fn save_and_load_round_trip() {
375        let path = tmp_path("roundtrip");
376        let _ = std::fs::remove_file(&path);
377        let s = site("Example");
378        let user = Username::new("alice").unwrap();
379        {
380            let mut cache = Cache::load(path.clone(), Duration::from_secs(3600));
381            cache.put(&s, &user, outcome(MatchKind::Found));
382            cache.save().unwrap();
383        }
384        let reloaded = Cache::load(path.clone(), Duration::from_secs(3600));
385        let got = reloaded.get(&s, &user).unwrap();
386        assert_eq!(got.kind, MatchKind::Found);
387        let _ = std::fs::remove_file(&path);
388    }
389
390    #[test]
391    fn load_drops_expired_entries() {
392        let path = tmp_path("expiry");
393        // Write a cache file by hand with a stored_at two hours in the past.
394        let file = CacheFile {
395            version: CACHE_VERSION,
396            entries: vec![StoredEntry {
397                site: "Example".into(),
398                username: "alice".into(),
399                signature: signature(&site("Example")),
400                stored_at: now_unix().saturating_sub(7200),
401                outcome: outcome(MatchKind::Found),
402            }],
403        };
404        std::fs::write(&path, serde_json::to_string(&file).unwrap()).unwrap();
405        // TTL of 1 hour → the 2-hour-old entry is pruned.
406        let reloaded = Cache::load(path.clone(), Duration::from_secs(3600));
407        assert!(reloaded.is_empty());
408        let _ = std::fs::remove_file(&path);
409    }
410
411    #[test]
412    fn corrupt_file_yields_empty_cache() {
413        let path = tmp_path("corrupt");
414        std::fs::write(&path, b"this is not json {{{").unwrap();
415        let cache = Cache::load(path.clone(), Duration::from_secs(3600));
416        assert!(cache.is_empty());
417        let _ = std::fs::remove_file(&path);
418    }
419
420    #[test]
421    fn clear_removes_file_and_tolerates_missing() {
422        let path = tmp_path("clear");
423        std::fs::write(&path, b"{}").unwrap();
424        Cache::clear(&path).unwrap();
425        assert!(!path.exists());
426        // Second clear on a missing file is fine.
427        Cache::clear(&path).unwrap();
428    }
429
430    #[test]
431    fn signature_is_deterministic() {
432        let s = site("Example");
433        assert_eq!(signature(&s), signature(&s));
434    }
435}