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
//! Download a tile pyramid and pack it into a raster `PMTiles` archive.

use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::thread::sleep;
use std::time::Duration;

use geolith::error::{GeolithError, Result};
use geolith::geometry::mercator::TileCoord;
use geolith::output::hilbert::tile_to_pmtiles_id;
use geolith::output::writer::{Compression, PmtilesWriter, TileType};
use rayon::prelude::*;

use crate::raster::cache::TileCache;
use crate::raster::fetch::{FetchOutcome, TileFetcher, fetch_with_retry};
use crate::raster::pyramid::PyramidSpec;
use crate::raster::template::UrlTemplate;

/// Options for one raster archive build.
#[derive(Debug, Clone)]
pub struct RasterBuildOptions {
    /// Tile URL template with `{z}`/`{x}`/`{y}` placeholders.
    pub template: UrlTemplate,
    /// Pyramid coverage (zooms, optional bbox, hybrid switch zoom).
    pub pyramid: PyramidSpec,
    /// Raster payload type recorded in the archive header.
    pub tile_type: TileType,
    /// Concurrent download workers.
    pub concurrency: usize,
    /// Delay injected after every request on each worker.
    pub request_delay: Duration,
    /// Attempts per tile before the build fails.
    pub attempts: u32,
    /// Resumable download cache directory.
    pub cache_dir: PathBuf,
    /// Layer name recorded in archive metadata.
    pub name: String,
    /// Attribution recorded in archive metadata.
    pub attribution: Option<String>,
}

/// Summary of a completed raster build.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RasterBuildStats {
    /// Tiles fetched from the network this run.
    pub downloaded: u64,
    /// Tiles served from the resume cache.
    pub cached: u64,
    /// Coordinates the upstream had no tile for.
    pub missing: u64,
    /// Tiles written into the archive.
    pub tiles_written: u64,
    /// Unique tile blobs after content deduplication.
    pub unique_tiles: usize,
}

/// Download every pyramid tile (resuming from `cache_dir`) and pack the
/// archive at `output`.
///
/// # Errors
///
/// Returns an error when a tile still fails after all retry attempts, or
/// when the cache or archive cannot be written.
pub fn build_raster_archive(
    fetcher: &dyn TileFetcher,
    options: &RasterBuildOptions,
    output: &Path,
) -> Result<RasterBuildStats> {
    let cache = TileCache::open(&options.cache_dir)?;
    let tiles = options.pyramid.tiles();

    let downloaded = AtomicU64::new(0);
    let cached = AtomicU64::new(0);

    let pool = rayon::ThreadPoolBuilder::new()
        .num_threads(options.concurrency.max(1))
        .build()
        .map_err(|e| GeolithError::RasterSource(format!("download pool: {e}")))?;

    pool.install(|| {
        tiles.par_iter().try_for_each(|&tile| -> Result<()> {
            if cache.tile(tile).is_some() || cache.is_missing(tile) {
                cached.fetch_add(1, Ordering::Relaxed);
                return Ok(());
            }
            let url = options.template.expand(tile);
            match fetch_with_retry(fetcher, &url, options.attempts)? {
                FetchOutcome::Tile(bytes) => cache.put(tile, &bytes)?,
                FetchOutcome::Missing => cache.mark_missing(tile)?,
            }
            downloaded.fetch_add(1, Ordering::Relaxed);
            if !options.request_delay.is_zero() {
                sleep(options.request_delay);
            }
            Ok(())
        })
    })?;

    let mut writer = PmtilesWriter::create(
        output,
        Compression::None,
        options.tile_type,
        options.pyramid.min_zoom,
        options.pyramid.max_zoom,
    )?;
    let bounds = options.pyramid.covered_bounds();
    writer.set_bounds(bounds.0, bounds.1, bounds.2, bounds.3);

    let mut ordered: Vec<(u64, TileCoord)> = tiles
        .iter()
        .map(|&tile| (tile_to_pmtiles_id(tile), tile))
        .collect();
    ordered.sort_unstable_by_key(|(id, _)| *id);

    let mut missing = 0_u64;
    for (tile_id, tile) in &ordered {
        match cache.tile(*tile) {
            Some(bytes) => {
                writer.write_tile(*tile_id, &bytes)?;
            }
            None => missing += 1,
        }
    }

    let stats = RasterBuildStats {
        downloaded: downloaded.into_inner(),
        cached: cached.into_inner(),
        missing,
        tiles_written: writer.tiles_written(),
        unique_tiles: writer.unique_tiles(),
    };

    let metadata = raster_metadata(options);
    writer.finalize(serde_json::to_string(&metadata)?.as_bytes())?;
    Ok(stats)
}

fn raster_metadata(options: &RasterBuildOptions) -> serde_json::Value {
    let format = match options.tile_type {
        TileType::Png => "png",
        TileType::Webp => "webp",
        TileType::Avif => "avif",
        _ => "jpeg",
    };
    let mut metadata = serde_json::json!({
        "name": options.name,
        "format": format,
        "type": "baselayer",
        "minzoom": options.pyramid.min_zoom.to_string(),
        "maxzoom": options.pyramid.max_zoom.to_string(),
    });
    metadata["attribution"] = serde_json::Value::String(geolith::attribution::with_credit(
        options.attribution.as_deref().unwrap_or_default(),
    ));
    if let Some((min_lon, min_lat, max_lon, max_lat)) = options.pyramid.bbox {
        metadata["geolith:bbox"] =
            serde_json::Value::String(format!("{min_lon},{min_lat},{max_lon},{max_lat}"));
        metadata["geolith:bbox_min_zoom"] =
            serde_json::Value::String(options.pyramid.bbox_min_zoom.to_string());
    }
    metadata
}

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

    struct StubFetcher;

    impl TileFetcher for StubFetcher {
        fn fetch(&self, url: &str) -> Result<FetchOutcome> {
            if url.contains("/2/") {
                return Ok(FetchOutcome::Missing);
            }
            Ok(FetchOutcome::Tile(format!("payload:{url}").into_bytes()))
        }
    }

    fn options(dir: &Path) -> RasterBuildOptions {
        RasterBuildOptions {
            template: UrlTemplate::parse("https://t.example/{z}/{x}/{y}.jpg").expect("template"),
            pyramid: PyramidSpec {
                min_zoom: 0,
                max_zoom: 1,
                bbox: None,
                bbox_min_zoom: 0,
            },
            tile_type: TileType::Jpeg,
            concurrency: 2,
            request_delay: Duration::ZERO,
            attempts: 2,
            cache_dir: dir.join("cache"),
            name: "test-raster".into(),
            attribution: Some("© Test".into()),
        }
    }

    #[test]
    fn downloads_and_packs_the_pyramid() {
        let dir = tempfile::tempdir().expect("tempdir");
        let output = dir.path().join("out.pmtiles");
        let stats =
            build_raster_archive(&StubFetcher, &options(dir.path()), &output).expect("build");
        assert_eq!(stats.downloaded, 5);
        assert_eq!(stats.cached, 0);
        assert_eq!(stats.missing, 0);
        assert_eq!(stats.tiles_written, 5);
        assert!(output.exists());
    }

    #[test]
    fn second_run_resumes_entirely_from_cache() {
        let dir = tempfile::tempdir().expect("tempdir");
        let opts = options(dir.path());
        let output = dir.path().join("out.pmtiles");
        build_raster_archive(&StubFetcher, &opts, &output).expect("first build");
        let stats = build_raster_archive(&StubFetcher, &opts, &output).expect("second build");
        assert_eq!(stats.downloaded, 0, "no re-downloads on resume");
        assert_eq!(stats.cached, 5);
        assert_eq!(stats.tiles_written, 5);
    }

    #[test]
    fn missing_tiles_are_recorded_and_skipped() {
        let dir = tempfile::tempdir().expect("tempdir");
        let mut opts = options(dir.path());
        opts.pyramid.max_zoom = 2;
        let output = dir.path().join("out.pmtiles");
        let stats = build_raster_archive(&StubFetcher, &opts, &output).expect("build");
        assert_eq!(stats.missing, 16, "all z2 tiles are upstream-missing");
        assert_eq!(stats.tiles_written, 5);
        let stats2 = build_raster_archive(&StubFetcher, &opts, &output).expect("rebuild");
        assert_eq!(stats2.cached, 21, "miss markers also resume");
        assert_eq!(stats2.downloaded, 0);
    }

    #[test]
    fn tiles_are_written_in_pmtiles_id_order() {
        let dir = tempfile::tempdir().expect("tempdir");
        let output = dir.path().join("out.pmtiles");
        build_raster_archive(&StubFetcher, &options(dir.path()), &output).expect("build");
        let bytes = std::fs::read(&output).expect("archive bytes");
        assert_eq!(&bytes[0..7], b"PMTiles", "valid magic");
    }

    #[test]
    fn hybrid_archive_declares_world_bounds_not_just_the_bbox() {
        let dir = tempfile::tempdir().expect("tempdir");
        let mut opts = options(dir.path());
        opts.pyramid = PyramidSpec {
            min_zoom: 0,
            max_zoom: 2,
            bbox: Some((68.0, 6.5, 97.5, 37.2)),
            bbox_min_zoom: 2,
        };
        let output = dir.path().join("hybrid.pmtiles");
        build_raster_archive(&StubFetcher, &opts, &output).expect("build");

        let (min_lon, min_lat, max_lon, max_lat) = read_bounds(&output);
        assert!(
            min_lon <= -179.0 && max_lon >= 179.0,
            "z0/z1 hold planet tiles, so the archive must not claim bbox-only \
             coverage: got lon {min_lon}..{max_lon}"
        );
        assert!(
            min_lat < -80.0 && max_lat > 80.0,
            "lat {min_lat}..{max_lat}"
        );
    }

    #[test]
    fn bbox_only_archive_declares_the_bbox() {
        let dir = tempfile::tempdir().expect("tempdir");
        let mut opts = options(dir.path());
        opts.pyramid = PyramidSpec {
            min_zoom: 1,
            max_zoom: 2,
            bbox: Some((68.0, 6.5, 97.5, 37.2)),
            bbox_min_zoom: 0,
        };
        let output = dir.path().join("bbox-only.pmtiles");
        build_raster_archive(&StubFetcher, &opts, &output).expect("build");

        let (min_lon, min_lat, max_lon, max_lat) = read_bounds(&output);
        assert!((min_lon - 68.0).abs() < 0.01, "min_lon {min_lon}");
        assert!((max_lon - 97.5).abs() < 0.01, "max_lon {max_lon}");
        assert!((min_lat - 6.5).abs() < 0.01, "min_lat {min_lat}");
        assert!((max_lat - 37.2).abs() < 0.01, "max_lat {max_lat}");
    }

    /// Decode the four bounds fields from the `PMTiles` v3 header, which stores
    /// them as signed E7 micro-degrees starting at byte 102.
    fn read_bounds(path: &Path) -> (f64, f64, f64, f64) {
        let bytes = std::fs::read(path).expect("archive bytes");
        let at = |offset: usize| -> f64 {
            let raw = i32::from_le_bytes(
                bytes[offset..offset + 4]
                    .try_into()
                    .expect("4 bytes for an E7 field"),
            );
            f64::from(raw) / 1e7
        };
        (at(102), at(106), at(110), at(114))
    }

    #[test]
    fn a_raster_archive_without_attribution_carries_the_credit_alone() {
        let dir = tempfile::tempdir().expect("tempdir");
        let mut raster = options(dir.path());
        raster.attribution = None;
        assert_eq!(raster_metadata(&raster)["attribution"], "© geolith");
    }

    #[test]
    fn metadata_names_format_and_attribution() {
        let dir = tempfile::tempdir().expect("tempdir");
        let metadata = raster_metadata(&options(dir.path()));
        assert_eq!(metadata["format"], "jpeg");
        assert_eq!(metadata["attribution"], "© Test | © geolith");
        assert_eq!(metadata["minzoom"], "0");
    }

    #[test]
    fn metadata_describes_the_pyramid_shape() {
        let dir = tempfile::tempdir().expect("tempdir");
        let mut opts = options(dir.path());
        opts.pyramid = PyramidSpec {
            min_zoom: 0,
            max_zoom: 12,
            bbox: Some((68.0, 6.5, 97.5, 37.2)),
            bbox_min_zoom: 9,
        };
        let metadata = raster_metadata(&opts);

        assert_eq!(
            metadata["geolith:bbox"], "68,6.5,97.5,37.2",
            "consumers cannot tell which zooms are clipped without the bbox"
        );
        assert_eq!(metadata["geolith:bbox_min_zoom"], "9");
    }

    #[test]
    fn metadata_omits_pyramid_shape_when_unclipped() {
        let dir = tempfile::tempdir().expect("tempdir");
        let metadata = raster_metadata(&options(dir.path()));
        assert!(
            metadata.get("geolith:bbox").is_none(),
            "a planet pyramid has no clipped region to describe"
        );
        assert!(metadata.get("geolith:bbox_min_zoom").is_none());
    }
}