geolith-tiles-builder 0.4.2

Builds tiles from OpenStreetMap and Overture Maps: protomaps-schema vector PMTiles, Terrain-RGB, raster archives and 3D Tiles from Gaussian splats
Documentation
//! Resumable on-disk tile cache.
//!
//! Every downloaded tile lands here before archive packing, so an
//! interrupted planet run resumes by skipping tiles already on disk.
//! Writes go through a temp-file rename, keeping the cache crash-safe.

use std::fs;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

use geolith::error::{GeolithError, Result};
use geolith::geometry::mercator::TileCoord;

/// Distinguishes concurrent temp files written by this process.
static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);

/// On-disk cache of fetched tiles, keyed by `z/x/y`.
#[derive(Debug, Clone)]
pub struct TileCache {
    root: PathBuf,
}

impl TileCache {
    /// Open (creating if needed) a cache rooted at `root`.
    ///
    /// # Errors
    ///
    /// Returns an error when the root directory cannot be created.
    pub fn open(root: &Path) -> Result<Self> {
        fs::create_dir_all(root)?;
        Ok(Self {
            root: root.to_owned(),
        })
    }

    fn tile_path(&self, tile: TileCoord) -> PathBuf {
        self.root
            .join(tile.z.to_string())
            .join(tile.x.to_string())
            .join(format!("{}.bin", tile.y))
    }

    fn miss_path(&self, tile: TileCoord) -> PathBuf {
        self.tile_path(tile).with_extension("miss")
    }

    /// The cached bytes for `tile`, when present.
    #[must_use]
    pub fn tile(&self, tile: TileCoord) -> Option<Vec<u8>> {
        fs::read(self.tile_path(tile)).ok()
    }

    /// Whether `tile` was previously recorded as absent upstream.
    #[must_use]
    pub fn is_missing(&self, tile: TileCoord) -> bool {
        self.miss_path(tile).exists()
    }

    /// Store the bytes for `tile`.
    ///
    /// # Errors
    ///
    /// Returns an error when the tile file cannot be written.
    pub fn put(&self, tile: TileCoord, bytes: &[u8]) -> Result<()> {
        self.write_atomic(&self.tile_path(tile), bytes)
    }

    /// Record that the upstream has no tile at this coordinate.
    ///
    /// # Errors
    ///
    /// Returns an error when the marker cannot be written.
    pub fn mark_missing(&self, tile: TileCoord) -> Result<()> {
        self.write_atomic(&self.miss_path(tile), &[])
    }

    fn write_atomic(&self, path: &Path, bytes: &[u8]) -> Result<()> {
        let Some(parent) = path.parent() else {
            return Err(GeolithError::RasterSource(format!(
                "cache path {} has no parent directory",
                path.display()
            )));
        };
        fs::create_dir_all(parent)?;

        // The temp name must be unique per write, not per destination: `.bin`
        // and `.miss` for one coordinate share a stem, so a shared temp path
        // lets two writers rename the same file and one observes ENOENT.
        let stem = path
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or("tile");
        let unique = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
        let tmp = parent.join(format!(".{stem}.{}.{unique}.tmp", std::process::id()));

        crate::fsio::write_file(&tmp, bytes)?;
        fs::rename(&tmp, path).map_err(|e| {
            GeolithError::from(e).context(format!("moving {} to {}", tmp.display(), path.display()))
        })?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn cache() -> (tempfile::TempDir, TileCache) {
        let dir = tempfile::tempdir().expect("tempdir");
        let cache = TileCache::open(dir.path()).expect("open cache");
        (dir, cache)
    }

    #[test]
    fn a_path_without_a_parent_is_an_error() {
        let (_dir, cache) = cache();
        assert!(cache.write_atomic(Path::new(""), b"x").is_err());
    }

    #[test]
    fn roundtrips_tile_bytes() {
        let (_dir, cache) = cache();
        let tile = TileCoord { z: 3, x: 5, y: 2 };
        assert!(cache.tile(tile).is_none());
        cache.put(tile, b"jpegbytes").expect("put");
        assert_eq!(cache.tile(tile).as_deref(), Some(b"jpegbytes".as_slice()));
    }

    #[test]
    fn distinguishes_missing_marker_from_uncached() {
        let (_dir, cache) = cache();
        let tile = TileCoord { z: 4, x: 1, y: 9 };
        assert!(!cache.is_missing(tile));
        cache.mark_missing(tile).expect("mark");
        assert!(cache.is_missing(tile));
        assert!(cache.tile(tile).is_none(), "a miss marker is not tile data");
    }

    #[test]
    fn survives_reopen_for_resume() {
        let (dir, cache) = cache();
        let tile = TileCoord { z: 2, x: 3, y: 1 };
        cache.put(tile, b"persisted").expect("put");
        drop(cache);
        let reopened = TileCache::open(dir.path()).expect("reopen");
        assert_eq!(
            reopened.tile(tile).as_deref(),
            Some(b"persisted".as_slice())
        );
    }

    #[test]
    fn concurrent_writes_to_one_coordinate_never_corrupt_it() {
        let (_dir, cache) = cache();
        let payload = vec![0xAB_u8; 64 * 1024];

        for round in 0..40 {
            let tile = TileCoord {
                z: 6,
                x: round,
                y: 3,
            };
            std::thread::scope(|scope| {
                let c1 = &cache;
                let c2 = &cache;
                let p = &payload;
                scope.spawn(move || c1.put(tile, p).expect("put"));
                scope.spawn(move || c2.mark_missing(tile).expect("mark"));
            });

            if let Some(bytes) = cache.tile(tile) {
                assert_eq!(
                    bytes.len(),
                    payload.len(),
                    "round {round}: a cached tile must be whole, never truncated by a \
                     colliding temp file"
                );
            }
        }
    }

    #[test]
    fn leaves_no_tmp_files_behind() {
        let (dir, cache) = cache();
        cache
            .put(TileCoord { z: 1, x: 0, y: 0 }, b"x")
            .expect("put");
        cache
            .mark_missing(TileCoord { z: 1, x: 1, y: 0 })
            .expect("mark");
        let mut stack = vec![dir.path().to_owned()];
        while let Some(d) = stack.pop() {
            for entry in fs::read_dir(&d).expect("read_dir") {
                let entry = entry.expect("entry");
                let path = entry.path();
                if path.is_dir() {
                    stack.push(path);
                } else {
                    let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
                    assert!(
                        !name.ends_with(".tmp"),
                        "atomic writes must not leave temp files: {}",
                        path.display()
                    );
                }
            }
        }
    }
}