Skip to main content

transitous_core/
cache.rs

1//! A cache of responses on disk, shared by every process on the machine, so
2//! that repeated calls do not reach Transitous. Stop searches keep for 15
3//! minutes, connections, departures and trips for a minute, because their
4//! realtime data changes.
5//!
6//! The cache is best effort: an entry that cannot be read or written is a
7//! miss.
8
9use std::path::PathBuf;
10use std::time::Duration;
11
12use jiff::Timestamp;
13use serde::{Deserialize, Serialize};
14
15use crate::usage::Endpoint;
16
17/// How long the answers of an endpoint keep.
18pub fn ttl(endpoint: Endpoint) -> Duration {
19    match endpoint {
20        Endpoint::Geocode | Endpoint::ReverseGeocode => Duration::from_secs(15 * 60),
21        Endpoint::Plan | Endpoint::Stoptimes | Endpoint::Trip => Duration::from_secs(60),
22    }
23}
24
25/// Entries older than this are removed.
26const MAX_AGE: Duration = Duration::from_secs(60 * 60);
27
28#[derive(Debug, Serialize, Deserialize)]
29struct Entry {
30    key: String,
31    stored: Timestamp,
32    body: String,
33}
34
35#[derive(Debug, Clone)]
36pub struct Cache {
37    dir: Option<PathBuf>,
38}
39
40impl Cache {
41    /// A cache in `dir`, or none.
42    pub fn new(dir: Option<PathBuf>) -> Self {
43        Self { dir }
44    }
45
46    /// The body stored for `key` within `ttl` before `now`.
47    pub fn get(&self, key: &str, ttl: Duration, now: Timestamp) -> Option<Vec<u8>> {
48        let path = self.path(key)?;
49        let text = std::fs::read_to_string(path).ok()?;
50        let entry: Entry = serde_json::from_str(&text).ok()?;
51        let age = now.as_second() - entry.stored.as_second();
52        let fresh = (0..i64::try_from(ttl.as_secs()).unwrap_or(i64::MAX)).contains(&age);
53        (entry.key == key && fresh).then(|| entry.body.into_bytes())
54    }
55
56    /// Stores `body` for `key`, and removes old entries.
57    pub fn put(&self, key: &str, body: &[u8], now: Timestamp) {
58        let (Some(dir), Some(path)) = (&self.dir, self.path(key)) else {
59            return;
60        };
61        let Ok(body) = String::from_utf8(body.to_vec()) else {
62            return;
63        };
64        let entry = Entry {
65            key: key.to_owned(),
66            stored: now,
67            body,
68        };
69        // Plain data does not fail to serialize; an empty file would only be
70        // a miss.
71        let text = serde_json::to_vec(&entry).unwrap_or_default();
72        let _ = std::fs::create_dir_all(dir);
73        let temporary = path.with_extension(format!("{}.tmp", std::process::id()));
74        let stored =
75            std::fs::write(&temporary, text).and_then(|()| std::fs::rename(&temporary, &path));
76        if stored.is_err() {
77            let _ = std::fs::remove_file(&temporary);
78        }
79        self.prune();
80    }
81
82    fn path(&self, key: &str) -> Option<PathBuf> {
83        Some(self.dir.as_ref()?.join(format!("{:016x}.json", fnv1a(key))))
84    }
85
86    /// Removes the entries last written more than [`MAX_AGE`] ago.
87    fn prune(&self) {
88        let Some(entries) = self
89            .dir
90            .as_ref()
91            .and_then(|dir| std::fs::read_dir(dir).ok())
92        else {
93            return;
94        };
95        for entry in entries.flatten() {
96            let old = entry
97                .metadata()
98                .and_then(|meta| meta.modified())
99                .ok()
100                .and_then(|modified| modified.elapsed().ok())
101                .is_some_and(|age| age > MAX_AGE);
102            if old {
103                let _ = std::fs::remove_file(entry.path());
104            }
105        }
106    }
107}
108
109/// The 64-bit FNV-1a hash: stable across versions and platforms, unlike the
110/// hasher of the standard library.
111fn fnv1a(text: &str) -> u64 {
112    text.bytes().fold(0xcbf2_9ce4_8422_2325, |hash, byte| {
113        (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
114    })
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120
121    fn at(second: i64) -> Timestamp {
122        Timestamp::from_second(1_800_000_000 + second).unwrap()
123    }
124
125    #[test]
126    fn keeps_answers_for_their_time() {
127        let dir = tempfile::tempdir().unwrap();
128        let cache = Cache::new(Some(dir.path().join("cache")));
129        let ttl = Duration::from_secs(60);
130        assert_eq!(cache.get("a", ttl, at(0)), None);
131        cache.put("a", b"{}", at(0));
132        assert_eq!(cache.get("a", ttl, at(59)).as_deref(), Some(&b"{}"[..]));
133        assert_eq!(cache.get("a", ttl, at(60)), None);
134        assert_eq!(cache.get("a", ttl, at(-1)), None);
135        assert_eq!(cache.get("b", ttl, at(1)), None);
136    }
137
138    #[test]
139    fn ignores_entries_of_another_key() {
140        let dir = tempfile::tempdir().unwrap();
141        let cache = Cache::new(Some(dir.path().to_owned()));
142        cache.put("a", b"1", at(0));
143        let theirs = cache.path("a").unwrap();
144        std::fs::rename(&theirs, cache.path("b").unwrap()).unwrap();
145        assert_eq!(cache.get("b", Duration::from_secs(60), at(1)), None);
146    }
147
148    #[test]
149    fn skips_bodies_that_are_not_text() {
150        let dir = tempfile::tempdir().unwrap();
151        let cache = Cache::new(Some(dir.path().to_owned()));
152        cache.put("a", &[0xff, 0xfe], at(0));
153        assert_eq!(cache.get("a", Duration::from_secs(60), at(1)), None);
154    }
155
156    #[test]
157    fn removes_old_entries() {
158        let dir = tempfile::tempdir().unwrap();
159        let old = dir.path().join("old.json");
160        std::fs::write(&old, "{}").unwrap();
161        let file = std::fs::File::options().write(true).open(&old).unwrap();
162        file.set_modified(std::time::SystemTime::now() - 2 * MAX_AGE)
163            .unwrap();
164        let cache = Cache::new(Some(dir.path().to_owned()));
165        cache.put("a", b"1", at(0));
166        assert!(!old.exists());
167        assert!(cache.path("a").unwrap().exists());
168    }
169
170    #[test]
171    fn without_a_directory_nothing_is_kept() {
172        let cache = Cache::new(None);
173        cache.put("a", b"1", at(0));
174        assert_eq!(cache.get("a", Duration::from_secs(60), at(1)), None);
175    }
176
177    #[test]
178    fn a_cache_it_cannot_write_is_a_miss() {
179        let dir = tempfile::tempdir().unwrap();
180        let blocker = dir.path().join("file");
181        std::fs::write(&blocker, "").unwrap();
182        let cache = Cache::new(Some(blocker.join("cache")));
183        cache.put("a", b"1", at(0));
184        assert_eq!(cache.get("a", Duration::from_secs(60), at(1)), None);
185    }
186
187    #[test]
188    fn stop_searches_keep_longer() {
189        assert_eq!(ttl(Endpoint::Geocode), Duration::from_secs(900));
190        assert_eq!(ttl(Endpoint::ReverseGeocode), Duration::from_secs(900));
191        assert_eq!(ttl(Endpoint::Plan), Duration::from_secs(60));
192    }
193
194    #[test]
195    fn hashes_stably() {
196        assert_eq!(fnv1a(""), 0xcbf2_9ce4_8422_2325);
197        assert_eq!(fnv1a("a"), 0xaf63_dc4c_8601_ec8c);
198    }
199}