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
//! What one tile build reads, writes and keeps.

use std::path::PathBuf;

use crate::layers::Layer;
use crate::tiles_error::TilesError;

/// How many features may lose a piece to a caught clipper panic before the
/// build fails: 100. A planet build reads billions of features, so
/// 100 is a handful of bad rings, not a lost region. A bad source (a layer
/// full of NaN vertices) stops the build early instead of dropping features
/// in bulk. There is no flag: a build that needs more has a source problem
/// to look at first.
pub const DEFAULT_MAX_GEOMETRY_FAILURES: u64 = 100;

/// Switches that reuse work an earlier run already did.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Reuse {
    /// Reuse the OSM node store of an earlier run when it exists.
    pub node_cache: bool,
    /// Resume from the sort chunks an interrupted run left in the temporary
    /// directory.
    pub resume: bool,
}

impl Reuse {
    /// Switches with the given values.
    #[must_use]
    pub const fn new(node_cache: bool, resume: bool) -> Self {
        Self { node_cache, resume }
    }
}

/// What one tile build reads, writes and keeps.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct TilesConfig {
    /// The Overture Maps directory (hive-partitioned Parquet).
    pub data: PathBuf,
    /// An OSM PBF; Overture-only builds leave it out.
    pub osm_pbf: Option<PathBuf>,
    /// The Natural Earth SQLite file.
    pub natural_earth: PathBuf,
    /// The water-polygons-split-3857 shapefile directory.
    pub water_polygons: PathBuf,
    /// The land-polygons-split-3857 shapefile directory.
    pub land_polygons: PathBuf,
    /// The Survey of India boundary file.
    pub india_boundary: Option<PathBuf>,
    /// The `PMTiles` file to write.
    pub output: PathBuf,
    /// `west,south,east,north`: only tiles inside it are built.
    pub bbox: Option<String>,
    /// The highest zoom level.
    pub max_zoom: u8,
    /// Worker threads; the machine's when `None`.
    pub threads: Option<usize>,
    /// Sort buffer per thread in MB; 0 picks it from the memory.
    pub chunk_size_mb: usize,
    /// Directory for sort chunks and scratch files.
    pub tmpdir: Option<PathBuf>,
    /// A file that keeps the OSM node coordinates between runs.
    pub node_store: Option<PathBuf>,
    /// Source of the buildings layer: `overture`, `osm` or `both`.
    pub buildings_source: String,
    /// Source of the division features of the places and boundaries layers.
    pub divisions_source: String,
    /// Source of the landcover layer.
    pub landcover_source: String,
    /// Source of the bathymetry layer.
    pub bathymetry_source: String,
    /// Source of the roads layer.
    pub roads_source: String,
    /// Source of the points-of-interest layer.
    pub pois_source: String,
    /// Source of the water layer.
    pub water_source: String,
    /// Source of the landuse layer.
    pub landuse_source: String,
    /// Reuse and resume switches.
    pub reuse: Reuse,
    /// The tile encoding: `mvt` or `mlt`.
    pub tile_format: String,
    /// A directory of GERS bridge files for OSM deduplication.
    pub bridge_dir: Option<PathBuf>,
    /// Do not deduplicate OSM against Overture.
    pub no_conflate: bool,
    /// GERS bridge files, besides the directory.
    pub bridge_files: Vec<PathBuf>,
    /// Delete each Overture source file once it is read.
    pub reclaim_source_after_read: bool,
    /// Build with `--reclaim-source-after-read` although the data folder holds
    /// no file of an Overture type the enabled layers read.
    pub allow_missing_types: bool,
    /// Give each sort chunk's disk space back as the merge reads it, and
    /// delete the chunk when it is read. The build then cannot resume from
    /// its chunks after the merge started.
    pub reclaim_chunks: bool,
    /// Estimate the disk the build needs and stop early when a volume is
    /// short. On by default.
    pub disk_check: bool,
    /// Most features that may lose a piece to a caught clipper panic before
    /// the build fails. See [`DEFAULT_MAX_GEOMETRY_FAILURES`].
    pub max_geometry_failures: u64,
}

impl TilesConfig {
    /// A config that reads `data` and the three base-map files and writes
    /// `output`, with the defaults of the command line.
    #[must_use]
    pub fn new(
        data: impl Into<PathBuf>,
        natural_earth: impl Into<PathBuf>,
        water_polygons: impl Into<PathBuf>,
        land_polygons: impl Into<PathBuf>,
        output: impl Into<PathBuf>,
    ) -> Self {
        Self {
            data: data.into(),
            osm_pbf: None,
            natural_earth: natural_earth.into(),
            water_polygons: water_polygons.into(),
            land_polygons: land_polygons.into(),
            india_boundary: None,
            output: output.into(),
            bbox: None,
            max_zoom: 15,
            threads: None,
            chunk_size_mb: 0,
            tmpdir: None,
            node_store: None,
            buildings_source: "both".to_owned(),
            divisions_source: "overture".to_owned(),
            landcover_source: "overture".to_owned(),
            bathymetry_source: "overture".to_owned(),
            roads_source: "both".to_owned(),
            pois_source: "both".to_owned(),
            water_source: "both".to_owned(),
            landuse_source: "both".to_owned(),
            reuse: Reuse::default(),
            tile_format: "mvt".to_owned(),
            bridge_dir: None,
            no_conflate: false,
            bridge_files: Vec::new(),
            reclaim_source_after_read: false,
            allow_missing_types: false,
            reclaim_chunks: false,
            disk_check: true,
            max_geometry_failures: DEFAULT_MAX_GEOMETRY_FAILURES,
        }
    }

    /// Check if India boundary fix is enabled.
    pub const fn has_india_boundary(&self) -> bool {
        self.india_boundary.is_some()
    }

    /// Check if a source should include OSM data.
    pub fn uses_osm(&self, source: &str) -> bool {
        matches!(source, "osm" | "both")
    }

    /// Check if a source should include Overture data.
    pub fn uses_overture(&self, source: &str) -> bool {
        matches!(source, "overture" | "both")
    }

    /// Whether Overture data should be included for a given layer.
    ///
    /// Layers without a dedicated source flag always include Overture data.
    pub fn overture_enabled(&self, layer: Layer) -> bool {
        use Layer;
        match layer {
            Layer::Buildings => self.uses_overture(&self.buildings_source),
            Layer::Roads => self.uses_overture(&self.roads_source),
            Layer::Pois => self.uses_overture(&self.pois_source),
            Layer::Places => self.uses_overture(&self.divisions_source),
            Layer::Boundaries => self.uses_overture(&self.divisions_source),
            Layer::Landcover => self.uses_overture(&self.landcover_source),
            Layer::Bathymetry => self.uses_overture(&self.bathymetry_source),
            Layer::Water => self.uses_overture(&self.water_source),
            Layer::Landuse => self.uses_overture(&self.landuse_source),
            Layer::Earth | Layer::Transit => true,
            _ => true,
        }
    }

    /// Whether OSM data should be included for a given layer.
    ///
    /// Returns `false` for all layers when `--osm-pbf` is not provided.
    /// Layers without a dedicated source flag always include OSM data
    /// when a PBF file is available.
    pub fn osm_enabled(&self, layer: Layer) -> bool {
        if self.osm_pbf.is_none() {
            return false;
        }
        use Layer;
        match layer {
            Layer::Buildings => self.uses_osm(&self.buildings_source),
            Layer::Roads => self.uses_osm(&self.roads_source),
            Layer::Pois => self.uses_osm(&self.pois_source),
            Layer::Water => self.uses_osm(&self.water_source),
            Layer::Landuse => self.uses_osm(&self.landuse_source),
            Layer::Places => true,
            _ => true,
        }
    }

    /// Compute the effective sort-buffer size in bytes per thread.
    ///
    /// When `chunk_size_mb` is 0 (auto), uses platform memory detection
    /// to pick `min(2 GB, total_RAM / (3 × threads))`.  Falls back to
    /// 512 MB if detection fails.
    pub fn effective_chunk_bytes(&self) -> usize {
        if self.chunk_size_mb > 0 {
            return self.chunk_size_mb * 1024 * 1024;
        }

        // 16 GB assumed when detection fails.
        let total_ram = detect_total_memory().unwrap_or(16 * 1024 * 1024 * 1024);
        let threads = self.threads.unwrap_or_else(|| {
            std::thread::available_parallelism()
                .map(|n| n.get())
                .unwrap_or(4)
        });

        const MAX_CHUNK: usize = 2 * 1024 * 1024 * 1024; // 2 GB
        const MIN_CHUNK: usize = 64 * 1024 * 1024; // 64 MB

        let per_thread = (total_ram as usize) / (3 * threads);
        per_thread.clamp(MIN_CHUNK, MAX_CHUNK)
    }

    /// Discover all GERS bridge Parquet files for OSM deduplication.
    ///
    /// Resolution order:
    /// 1. Explicit `--bridge-files` paths (always included)
    /// 2. `--bridge-dir` directory (recursively scanned for `.parquet` files)
    /// 3. Auto-discovery: `gers-bridge/` sibling of `--data` directory
    ///
    /// Returns an empty `Vec` if no bridge files are found. A directory that
    /// cannot be read is logged and skipped here; the build itself uses
    /// [`Self::try_discover_bridge_files`], which fails on it, because a
    /// skipped bridge file changes the archive (OSM features that Overture
    /// already has stay in).
    #[must_use]
    pub fn discover_bridge_files(&self) -> Vec<PathBuf> {
        self.try_discover_bridge_files().unwrap_or_else(|e| {
            tracing::warn!(error = %e, "failed to read the bridge directory");
            self.bridge_files.clone()
        })
    }

    /// Like [`Self::discover_bridge_files`], but a directory or entry that
    /// cannot be read is an error.
    ///
    /// # Errors
    ///
    /// [`TilesError::Io`] when the bridge directory or one of its entries
    /// cannot be read.
    pub fn try_discover_bridge_files(&self) -> Result<Vec<PathBuf>, TilesError> {
        let mut files = Vec::new();

        // 1. Explicit --bridge-files
        files.extend(self.bridge_files.iter().cloned());

        // 2. --bridge-dir or auto-discovered sibling
        let bridge_dir = self.bridge_dir.clone().or_else(|| {
            // Auto-discover: look for gers-bridge/ sibling of --data
            self.data.parent().map(|parent| parent.join("gers-bridge"))
        });

        if let Some(dir) = bridge_dir
            && dir.is_dir()
        {
            let mut found = Vec::new();
            Self::collect_parquet_files(&dir, &mut found)?;
            // `read_dir` order differs between APFS and ext4; later files win
            // on a duplicate GERS id, so the load order must not depend on it.
            found.sort();
            files.extend(found);
        }

        Ok(files)
    }

    /// Recursively collect all `.parquet` files from a directory.
    fn collect_parquet_files(
        dir: &std::path::Path,
        out: &mut Vec<PathBuf>,
    ) -> Result<(), TilesError> {
        for entry in std::fs::read_dir(dir)? {
            let path = entry?.path();
            if path.is_dir() {
                Self::collect_parquet_files(&path, out)?;
            } else if path.extension().is_some_and(|ext| ext == "parquet") {
                out.push(path);
            }
        }
        Ok(())
    }
}

/// Detect total physical memory in bytes.
///
/// Uses `sysctl` on macOS and `/proc/meminfo` on Linux.
/// Returns `None` if detection fails.
#[cfg(target_os = "macos")]
fn detect_total_memory() -> Option<u64> {
    let output = std::process::Command::new("sysctl")
        .args(["-n", "hw.memsize"])
        .output()
        .ok()?;
    String::from_utf8(output.stdout).ok()?.trim().parse().ok()
}

/// Detect total physical memory in bytes.
///
/// Uses `/proc/meminfo` on Linux.
/// Returns `None` if detection fails.
#[cfg(target_os = "linux")]
fn detect_total_memory() -> Option<u64> {
    let contents = std::fs::read_to_string("/proc/meminfo").ok()?;
    for line in contents.lines() {
        if let Some(rest) = line.strip_prefix("MemTotal:") {
            let kb: u64 = rest.trim().trim_end_matches(" kB").trim().parse().ok()?;
            return Some(kb * 1024);
        }
    }
    None
}

/// Fallback for unsupported platforms — always returns `None`.
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
fn detect_total_memory() -> Option<u64> {
    None
}