Skip to main content

geolith_tiles_builder/raster/
cache.rs

1//! Resumable on-disk tile cache.
2//!
3//! Every downloaded tile lands here before archive packing, so an
4//! interrupted planet run resumes by skipping tiles already on disk.
5//! Writes go through a temp-file rename, keeping the cache crash-safe.
6
7use std::fs;
8use std::path::{Path, PathBuf};
9use std::sync::atomic::{AtomicU64, Ordering};
10
11use geolith::error::{GeolithError, Result};
12use geolith::geometry::mercator::TileCoord;
13
14/// Distinguishes concurrent temp files written by this process.
15static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
16
17/// On-disk cache of fetched tiles, keyed by `z/x/y`.
18#[derive(Debug, Clone)]
19pub struct TileCache {
20    root: PathBuf,
21}
22
23impl TileCache {
24    /// Open (creating if needed) a cache rooted at `root`.
25    ///
26    /// # Errors
27    ///
28    /// Returns an error when the root directory cannot be created.
29    pub fn open(root: &Path) -> Result<Self> {
30        fs::create_dir_all(root)?;
31        Ok(Self {
32            root: root.to_owned(),
33        })
34    }
35
36    fn tile_path(&self, tile: TileCoord) -> PathBuf {
37        self.root
38            .join(tile.z.to_string())
39            .join(tile.x.to_string())
40            .join(format!("{}.bin", tile.y))
41    }
42
43    fn miss_path(&self, tile: TileCoord) -> PathBuf {
44        self.tile_path(tile).with_extension("miss")
45    }
46
47    /// The cached bytes for `tile`, when present.
48    #[must_use]
49    pub fn tile(&self, tile: TileCoord) -> Option<Vec<u8>> {
50        fs::read(self.tile_path(tile)).ok()
51    }
52
53    /// Whether `tile` was previously recorded as absent upstream.
54    #[must_use]
55    pub fn is_missing(&self, tile: TileCoord) -> bool {
56        self.miss_path(tile).exists()
57    }
58
59    /// Store the bytes for `tile`.
60    ///
61    /// # Errors
62    ///
63    /// Returns an error when the tile file cannot be written.
64    pub fn put(&self, tile: TileCoord, bytes: &[u8]) -> Result<()> {
65        self.write_atomic(&self.tile_path(tile), bytes)
66    }
67
68    /// Record that the upstream has no tile at this coordinate.
69    ///
70    /// # Errors
71    ///
72    /// Returns an error when the marker cannot be written.
73    pub fn mark_missing(&self, tile: TileCoord) -> Result<()> {
74        self.write_atomic(&self.miss_path(tile), &[])
75    }
76
77    fn write_atomic(&self, path: &Path, bytes: &[u8]) -> Result<()> {
78        let Some(parent) = path.parent() else {
79            return Err(GeolithError::RasterSource(format!(
80                "cache path {} has no parent directory",
81                path.display()
82            )));
83        };
84        fs::create_dir_all(parent)?;
85
86        // The temp name must be unique per write, not per destination: `.bin`
87        // and `.miss` for one coordinate share a stem, so a shared temp path
88        // lets two writers rename the same file and one observes ENOENT.
89        let stem = path
90            .file_name()
91            .and_then(|name| name.to_str())
92            .unwrap_or("tile");
93        let unique = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
94        let tmp = parent.join(format!(".{stem}.{}.{unique}.tmp", std::process::id()));
95
96        fs::write(&tmp, bytes)?;
97        fs::rename(&tmp, path)?;
98        Ok(())
99    }
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105
106    fn cache() -> (tempfile::TempDir, TileCache) {
107        let dir = tempfile::tempdir().expect("tempdir");
108        let cache = TileCache::open(dir.path()).expect("open cache");
109        (dir, cache)
110    }
111
112    #[test]
113    fn a_path_without_a_parent_is_an_error() {
114        let (_dir, cache) = cache();
115        assert!(cache.write_atomic(Path::new(""), b"x").is_err());
116    }
117
118    #[test]
119    fn roundtrips_tile_bytes() {
120        let (_dir, cache) = cache();
121        let tile = TileCoord { z: 3, x: 5, y: 2 };
122        assert!(cache.tile(tile).is_none());
123        cache.put(tile, b"jpegbytes").expect("put");
124        assert_eq!(cache.tile(tile).as_deref(), Some(b"jpegbytes".as_slice()));
125    }
126
127    #[test]
128    fn distinguishes_missing_marker_from_uncached() {
129        let (_dir, cache) = cache();
130        let tile = TileCoord { z: 4, x: 1, y: 9 };
131        assert!(!cache.is_missing(tile));
132        cache.mark_missing(tile).expect("mark");
133        assert!(cache.is_missing(tile));
134        assert!(cache.tile(tile).is_none(), "a miss marker is not tile data");
135    }
136
137    #[test]
138    fn survives_reopen_for_resume() {
139        let (dir, cache) = cache();
140        let tile = TileCoord { z: 2, x: 3, y: 1 };
141        cache.put(tile, b"persisted").expect("put");
142        drop(cache);
143        let reopened = TileCache::open(dir.path()).expect("reopen");
144        assert_eq!(
145            reopened.tile(tile).as_deref(),
146            Some(b"persisted".as_slice())
147        );
148    }
149
150    #[test]
151    fn concurrent_writes_to_one_coordinate_never_corrupt_it() {
152        let (_dir, cache) = cache();
153        let payload = vec![0xAB_u8; 64 * 1024];
154
155        for round in 0..40 {
156            let tile = TileCoord {
157                z: 6,
158                x: round,
159                y: 3,
160            };
161            std::thread::scope(|scope| {
162                let c1 = &cache;
163                let c2 = &cache;
164                let p = &payload;
165                scope.spawn(move || c1.put(tile, p).expect("put"));
166                scope.spawn(move || c2.mark_missing(tile).expect("mark"));
167            });
168
169            if let Some(bytes) = cache.tile(tile) {
170                assert_eq!(
171                    bytes.len(),
172                    payload.len(),
173                    "round {round}: a cached tile must be whole, never truncated by a \
174                     colliding temp file"
175                );
176            }
177        }
178    }
179
180    #[test]
181    fn leaves_no_tmp_files_behind() {
182        let (dir, cache) = cache();
183        cache
184            .put(TileCoord { z: 1, x: 0, y: 0 }, b"x")
185            .expect("put");
186        cache
187            .mark_missing(TileCoord { z: 1, x: 1, y: 0 })
188            .expect("mark");
189        let mut stack = vec![dir.path().to_owned()];
190        while let Some(d) = stack.pop() {
191            for entry in fs::read_dir(&d).expect("read_dir") {
192                let entry = entry.expect("entry");
193                let path = entry.path();
194                if path.is_dir() {
195                    stack.push(path);
196                } else {
197                    let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
198                    assert!(
199                        !name.ends_with(".tmp"),
200                        "atomic writes must not leave temp files: {}",
201                        path.display()
202                    );
203                }
204            }
205        }
206    }
207}