Skip to main content

basemapper_core/
cache.rs

1//! A disk cache for map tiles, so repeated renders of an area do not fetch
2//! the same tiles again (tile usage policies such as OpenStreetMap's ask
3//! clients to cache).
4//!
5//! Tiles are kept for as long as the server's `Cache-Control: max-age` or
6//! `Expires` allows (a day when it says nothing), and never when it sends
7//! `no-store` or `no-cache`. Tiles fetched with an `Authorization` header
8//! and tiles from the local machine are not cached.
9//!
10//! The cache lives in `BASEMAPPER_CACHE_DIR` when that is set (`off`
11//! disables it), else in the platform cache directory (`%LOCALAPPDATA%`,
12//! `~/Library/Caches`, `$XDG_CACHE_HOME` or `~/.cache`), under `basemapper`
13//! (the R package uses `tools::R_user_dir("basemapper", "cache")`, as CRAN
14//! asks). [`set_dir`] changes it at run time.
15//!
16//! The cache is kept small: expired tiles are deleted, and past its size
17//! limit (250 MB, or `BASEMAPPER_CACHE_MAX_SIZE` in MB; [`set_max_size`])
18//! the least recently used tiles go first. This clean-up runs in the
19//! background, on the first tile stored in a session and every
20//! [`PRUNE_EVERY`] tiles after.
21
22use once_cell::sync::Lazy;
23use std::path::{Path, PathBuf};
24use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
25use std::sync::RwLock;
26use std::time::{Duration, SystemTime, UNIX_EPOCH};
27
28static DIR: Lazy<RwLock<Option<PathBuf>>> = Lazy::new(|| RwLock::new(initial_dir()));
29
30/// Kept this long when the server gives no caching headers.
31const DEFAULT_TTL: Duration = Duration::from_secs(24 * 3600);
32
33/// The size limit when `BASEMAPPER_CACHE_MAX_SIZE` is not set: 250 MB.
34pub const DEFAULT_MAX_SIZE: u64 = 250 * 1024 * 1024;
35/// Clean up after this many stored tiles (and on the first in a session).
36pub const PRUNE_EVERY: u64 = 200;
37static MAX_SIZE: Lazy<AtomicU64> = Lazy::new(|| AtomicU64::new(initial_max_size()));
38static STORED: AtomicU64 = AtomicU64::new(0);
39static PRUNING: AtomicBool = AtomicBool::new(false);
40
41fn initial_max_size() -> u64 {
42    std::env::var("BASEMAPPER_CACHE_MAX_SIZE")
43        .ok()
44        .and_then(|v| v.trim().parse::<f64>().ok())
45        .filter(|mb| *mb > 0.0)
46        .map_or(DEFAULT_MAX_SIZE, |mb| (mb * 1024.0 * 1024.0) as u64)
47}
48
49/// The cache's size limit in bytes.
50pub fn max_size() -> u64 {
51    MAX_SIZE.load(Ordering::Relaxed)
52}
53
54/// Set the cache's size limit in bytes, and trim the cache to it.
55pub fn set_max_size(bytes: u64) {
56    MAX_SIZE.store(bytes.max(1), Ordering::Relaxed);
57    prune_in_background();
58}
59
60/// What a clean-up did.
61#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
62pub struct Pruned {
63    /// Tiles deleted (expired, or to keep under the size limit).
64    pub removed: usize,
65    /// The bytes the cache holds afterwards.
66    pub size: u64,
67}
68
69/// Delete expired tiles, then the least recently used ones until the cache
70/// is under 80% of its size limit (so clean-ups are not needed on every
71/// store). Unfinished writes older than an hour go too.
72pub fn prune() -> std::io::Result<Pruned> {
73    match dir() {
74        Some(d) => prune_in(&d, max_size()),
75        None => Ok(Pruned::default()),
76    }
77}
78
79/// [`prune`] for the cache in `dir`, to `limit` bytes.
80fn prune_in(dir: &Path, limit: u64) -> std::io::Result<Pruned> {
81    let tiles = dir.join("tiles");
82    if !tiles.exists() {
83        return Ok(Pruned::default());
84    }
85    let (now_s, now_t) = (now(), SystemTime::now());
86    let mut kept: Vec<(SystemTime, u64, PathBuf)> = Vec::new();
87    let mut out = Pruned::default();
88    for sub in std::fs::read_dir(&tiles)?.flatten() {
89        let Ok(entries) = std::fs::read_dir(sub.path()) else { continue };
90        for e in entries.flatten() {
91            let path = e.path();
92            let Ok(meta) = e.metadata() else { continue };
93            let modified = meta.modified().unwrap_or(now_t);
94            let unfinished = path.extension().is_some_and(|x| x.to_string_lossy().starts_with("tmp"));
95            let stale = now_t.duration_since(modified).is_ok_and(|age| age > Duration::from_secs(3600));
96            if unfinished {
97                if stale && std::fs::remove_file(&path).is_ok() {
98                    out.removed += 1;
99                }
100                continue;
101            }
102            if expires_at(&path).is_some_and(|t| t <= now_s) {
103                if std::fs::remove_file(&path).is_ok() {
104                    out.removed += 1;
105                }
106                continue;
107            }
108            kept.push((modified, meta.len(), path));
109        }
110    }
111    let mut size: u64 = kept.iter().map(|k| k.1).sum();
112    if size > limit {
113        kept.sort_by_key(|k| k.0); // least recently used first
114        let target = limit / 10 * 8;
115        for (_, len, path) in &kept {
116            if size <= target {
117                break;
118            }
119            if std::fs::remove_file(path).is_ok() {
120                size -= len;
121                out.removed += 1;
122            }
123        }
124    }
125    out.size = size;
126    Ok(out)
127}
128
129/// When a cached tile expires, from its first eight bytes.
130fn expires_at(path: &Path) -> Option<u64> {
131    use std::io::Read;
132    let mut head = [0u8; 8];
133    std::fs::File::open(path).ok()?.read_exact(&mut head).ok()?;
134    Some(u64::from_le_bytes(head))
135}
136
137/// [`prune`] on a background thread, unless one is already running.
138fn prune_in_background() {
139    if PRUNING.swap(true, Ordering::AcqRel) {
140        return;
141    }
142    std::thread::spawn(|| {
143        if let Err(e) = prune() {
144            log::debug!("tile cache: clean-up failed: {e}");
145        }
146        PRUNING.store(false, Ordering::Release);
147    });
148}
149
150fn initial_dir() -> Option<PathBuf> {
151    match std::env::var_os("BASEMAPPER_CACHE_DIR") {
152        Some(v) if v.is_empty() || v.eq_ignore_ascii_case("off") => None,
153        Some(v) => Some(PathBuf::from(v)),
154        None => default_dir(),
155    }
156}
157
158/// The platform cache directory for basemapper.
159pub fn default_dir() -> Option<PathBuf> {
160    let var = |k: &str| std::env::var_os(k).filter(|v| !v.is_empty()).map(PathBuf::from);
161    let base = if cfg!(windows) {
162        var("LOCALAPPDATA")
163    } else if cfg!(target_os = "macos") {
164        var("HOME").map(|h| h.join("Library").join("Caches"))
165    } else {
166        var("XDG_CACHE_HOME").or_else(|| var("HOME").map(|h| h.join(".cache")))
167    };
168    base.map(|b| b.join("basemapper"))
169}
170
171/// The cache directory, or `None` when caching is off.
172pub fn dir() -> Option<PathBuf> {
173    DIR.read().ok().and_then(|d| d.clone())
174}
175
176/// Move the cache to `dir`, or turn it off with `None`.
177pub fn set_dir(dir: Option<PathBuf>) {
178    if let Ok(mut d) = DIR.write() {
179        *d = dir;
180    }
181}
182
183/// Delete every cached tile. Only the cache's own `tiles` folder is removed.
184pub fn clear() -> std::io::Result<()> {
185    match dir() {
186        Some(d) if d.join("tiles").exists() => std::fs::remove_dir_all(d.join("tiles")),
187        _ => Ok(()),
188    }
189}
190
191/// Two FNV-1a passes with different seeds: a stable 128-bit file name.
192fn key(url: &str) -> String {
193    let fnv = |seed: u64| {
194        url.bytes().fold(seed, |h, b| (h ^ b as u64).wrapping_mul(0x100_0000_01b3))
195    };
196    format!("{:016x}{:016x}", fnv(0xcbf2_9ce4_8422_2325), fnv(0x6c62_272e_07bb_0142))
197}
198
199fn path_in(dir: &Path, url: &str) -> PathBuf {
200    let k = key(url);
201    dir.join("tiles").join(&k[..2]).join(k)
202}
203
204/// Whether tiles from `url` may be cached: remote http(s) only.
205fn cacheable(url: &str) -> bool {
206    let Ok(u) = reqwest::Url::parse(url) else { return false };
207    if !matches!(u.scheme(), "http" | "https") {
208        return false;
209    }
210    match u.host_str() {
211        Some(h) => match h.trim_start_matches('[').trim_end_matches(']').parse::<std::net::IpAddr>() {
212            Ok(ip) => !ip.is_loopback(),
213            Err(_) => !h.eq_ignore_ascii_case("localhost"),
214        },
215        None => false,
216    }
217}
218
219fn now() -> u64 {
220    SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs())
221}
222
223/// A cached, unexpired tile.
224pub(crate) fn get(url: &str) -> Option<Vec<u8>> {
225    let dir = dir()?;
226    if !cacheable(url) {
227        return None;
228    }
229    read_entry(&path_in(&dir, url))
230}
231
232fn read_entry(path: &Path) -> Option<Vec<u8>> {
233    let mut bytes = std::fs::read(path).ok()?;
234    let expires = u64::from_le_bytes(bytes.get(..8)?.try_into().ok()?);
235    if expires <= now() {
236        let _ = std::fs::remove_file(path);
237        return None;
238    }
239    bytes.drain(..8);
240    // Mark the tile as just used, for least-recently-used clean-up.
241    if let Ok(f) = std::fs::OpenOptions::new().write(true).open(path) {
242        let _ = f.set_modified(SystemTime::now());
243    }
244    Some(bytes)
245}
246
247/// How long the server lets a response be cached; `None` for not at all.
248fn ttl(headers: &reqwest::header::HeaderMap) -> Option<Duration> {
249    use reqwest::header::{CACHE_CONTROL, EXPIRES};
250    if let Some(cc) = headers.get(CACHE_CONTROL).and_then(|v| v.to_str().ok()) {
251        let cc = cc.to_ascii_lowercase();
252        let directives: Vec<&str> = cc.split(',').map(str::trim).collect();
253        if directives.iter().any(|d| matches!(*d, "no-store" | "no-cache" | "private")) {
254            return None;
255        }
256        if let Some(age) = directives.iter().find_map(|d| d.strip_prefix("max-age=")) {
257            return age.trim_matches('"').parse::<u64>().ok().filter(|&s| s > 0).map(Duration::from_secs);
258        }
259    }
260    if let Some(expires) = headers.get(EXPIRES).and_then(|v| v.to_str().ok()) {
261        let at = httpdate::parse_http_date(expires).ok()?;
262        return at.duration_since(SystemTime::now()).ok().filter(|d| !d.is_zero());
263    }
264    Some(DEFAULT_TTL)
265}
266
267/// Store a fetched tile, if the server allows caching it.
268pub(crate) fn put(url: &str, headers: &reqwest::header::HeaderMap, body: &[u8]) {
269    let (Some(dir), Some(ttl)) = (dir(), ttl(headers)) else { return };
270    if !cacheable(url) {
271        return;
272    }
273    if let Err(e) = write_entry(&path_in(&dir, url), now() + ttl.as_secs(), body) {
274        log::debug!("tile cache: could not write {url}: {e}");
275        return;
276    }
277    if STORED.fetch_add(1, Ordering::Relaxed) % PRUNE_EVERY == 0 {
278        prune_in_background();
279    }
280}
281
282fn write_entry(path: &Path, expires: u64, body: &[u8]) -> std::io::Result<()> {
283    std::fs::create_dir_all(path.parent().expect("cache path has a parent"))?;
284    let mut data = Vec::with_capacity(body.len() + 8);
285    data.extend_from_slice(&expires.to_le_bytes());
286    data.extend_from_slice(body);
287    // Write then rename, so a concurrent reader never sees half a tile.
288    let tmp = path.with_extension(format!("tmp{}", std::process::id()));
289    std::fs::write(&tmp, &data)?;
290    std::fs::rename(&tmp, path)
291}
292
293#[cfg(test)]
294mod tests {
295    use super::*;
296    use reqwest::header::{HeaderMap, HeaderValue, CACHE_CONTROL, EXPIRES};
297
298    fn headers(pairs: &[(reqwest::header::HeaderName, &str)]) -> HeaderMap {
299        let mut h = HeaderMap::new();
300        for (k, v) in pairs {
301            h.insert(k.clone(), HeaderValue::from_str(v).unwrap());
302        }
303        h
304    }
305
306    #[test]
307    fn ttl_follows_the_server() {
308        assert_eq!(ttl(&headers(&[])), Some(DEFAULT_TTL));
309        assert_eq!(ttl(&headers(&[(CACHE_CONTROL, "public, max-age=604800")])), Some(Duration::from_secs(604800)));
310        assert_eq!(ttl(&headers(&[(CACHE_CONTROL, "max-age=0")])), None);
311        assert_eq!(ttl(&headers(&[(CACHE_CONTROL, "no-store")])), None);
312        assert_eq!(ttl(&headers(&[(CACHE_CONTROL, "No-Cache, max-age=60")])), None);
313        assert_eq!(ttl(&headers(&[(EXPIRES, "Thu, 01 Jan 1970 00:00:00 GMT")])), None);
314        let later = httpdate::fmt_http_date(SystemTime::now() + Duration::from_secs(7200));
315        let t = ttl(&headers(&[(EXPIRES, &later)])).unwrap();
316        assert!(t > Duration::from_secs(7000) && t <= Duration::from_secs(7200), "{t:?}");
317    }
318
319    #[test]
320    fn only_remote_http_is_cached() {
321        assert!(cacheable("https://tile.openstreetmap.org/1/0/0.png"));
322        assert!(!cacheable("http://127.0.0.1:8080/1/0/0.png"));
323        assert!(!cacheable("http://localhost/1/0/0.png"));
324        assert!(!cacheable("http://[::1]/t.png"));
325        assert!(!cacheable("file:///tmp/t.png"));
326        assert!(!cacheable("pmtiles://https://x/a.pmtiles"));
327    }
328
329    #[test]
330    fn prune_deletes_expired_then_least_recently_used_tiles() {
331        let dir = std::env::temp_dir().join(format!("basemapper-prune-test-{}", std::process::id()));
332        let _ = std::fs::remove_dir_all(&dir);
333        let old = SystemTime::now() - Duration::from_secs(600);
334        let entry = |name: &str, expires: u64, used: SystemTime| {
335            let p = path_in(&dir, name);
336            write_entry(&p, expires, &[0u8; 1000]).unwrap();
337            std::fs::OpenOptions::new().write(true).open(&p).unwrap().set_modified(used).unwrap();
338            p
339        };
340        let expired = entry("https://a/expired", now() - 1, SystemTime::now());
341        let lru = entry("https://a/least-recent", now() + 60, old);
342        let fresh = entry("https://a/fresh", now() + 60, SystemTime::now());
343        let fresh2 = entry("https://a/fresh2", now() + 60, SystemTime::now());
344
345        let r = prune_in(&dir, 2_600).unwrap(); // room for two of the three live tiles
346
347        assert!(!expired.exists(), "expired tiles are deleted");
348        assert!(!lru.exists(), "the least recently used tile goes first");
349        assert!(fresh.exists() && fresh2.exists());
350        assert_eq!(r, Pruned { removed: 2, size: 2016 });
351        std::fs::remove_dir_all(&dir).unwrap();
352    }
353
354    #[test]
355    fn entries_round_trip_and_expire() {
356        let dir = std::env::temp_dir().join(format!("basemapper-cache-test-{}", std::process::id()));
357        let p = path_in(&dir, "https://a/1/0/0.png");
358        assert_ne!(p, path_in(&dir, "https://a/1/0/1.png"));
359        write_entry(&p, now() + 60, b"tile").unwrap();
360        assert_eq!(read_entry(&p).as_deref(), Some(&b"tile"[..]));
361        write_entry(&p, now() - 1, b"old").unwrap();
362        assert_eq!(read_entry(&p), None);
363        assert!(!p.exists(), "expired entries are removed");
364        std::fs::remove_dir_all(&dir).unwrap();
365    }
366}