1use 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
30const DEFAULT_TTL: Duration = Duration::from_secs(24 * 3600);
32
33pub const DEFAULT_MAX_SIZE: u64 = 250 * 1024 * 1024;
35pub 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
49pub fn max_size() -> u64 {
51 MAX_SIZE.load(Ordering::Relaxed)
52}
53
54pub fn set_max_size(bytes: u64) {
56 MAX_SIZE.store(bytes.max(1), Ordering::Relaxed);
57 prune_in_background();
58}
59
60#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
62pub struct Pruned {
63 pub removed: usize,
65 pub size: u64,
67}
68
69pub 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
79fn 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); 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
129fn 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
137fn 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
158pub 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
171pub fn dir() -> Option<PathBuf> {
173 DIR.read().ok().and_then(|d| d.clone())
174}
175
176pub fn set_dir(dir: Option<PathBuf>) {
178 if let Ok(mut d) = DIR.write() {
179 *d = dir;
180 }
181}
182
183pub 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
191fn 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
204fn 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
223pub(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 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
247fn 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
267pub(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 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(); 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}