geolith 0.2.1

Shared library of the geolith builders: source readers, conflation, admin areas, tile encoding and the PMTiles and MBTiles writers
Documentation
//! Typed error types for geolith library modules.
//!
//! Library code (source/, sort/, output/) uses [`GeolithError`] with `thiserror`.
//! Each builder crate has its own error enum that wraps [`GeolithError`] with
//! `#[from]`, so `?` carries a library error up to the command. [`report`]
//! prints an error with its whole chain of causes.

use thiserror::Error;

/// Errors produced by geolith library modules.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum GeolithError {
    /// I/O error during file operations.
    #[error("i/o error: {0}")]
    Io(#[from] std::io::Error),

    /// Parquet file read error.
    #[error("parquet error: {0}")]
    Parquet(#[from] parquet::errors::ParquetError),

    /// A Survey of India file (`--india-boundary`, `--india-outline`) is
    /// refused; the message names the file and the fix.
    #[error(transparent)]
    IndiaFile(#[from] crate::source::india_file::IndiaFileError),

    /// A Parquet file has no usable geometry column: it is missing or it
    /// is not a `Binary` column of WKB.
    #[error("parquet geometry column: {0}")]
    ParquetGeometry(String),

    /// A Parquet file holds too many geometries that are not valid WKB, or
    /// no valid one at all.
    #[error("{bad} geometries are not valid WKB ({rule}); the first, at row {first_row}: {first}")]
    BadWkb {
        /// How many geometries failed in the file so far.
        bad: u64,
        /// Why this stops the read: the limit passed, or no valid geometry.
        rule: String,
        /// Row (within its record batch) of the first failure.
        first_row: usize,
        /// The decoder's message for the first failure.
        first: String,
    },

    /// Arrow batch read error.
    #[error("arrow error: {0}")]
    Arrow(#[from] arrow::error::ArrowError),
    /// SQLite database error (Natural Earth).
    #[error("sqlite error: {0}")]
    Sqlite(#[from] rusqlite::Error),

    /// Serialization/deserialization error (postcard).
    #[error("serialization error: {0}")]
    Serialization(#[from] postcard::Error),

    /// JSON serialization error (`serde_json`).
    #[error("json error: {0}")]
    Json(#[from] serde_json::Error),

    /// LZ4 frame compression error.
    #[error("lz4 compression error: {0}")]
    Lz4(#[from] lz4_flex::frame::Error),

    /// OSM PBF reader error (osmpbf crate).
    #[error("osm pbf read error: {0}")]
    OsmPbfRead(#[from] osmpbf::Error),

    /// `GeoJSON` read/parse error.
    #[error("geojson error: {0}")]
    GeoJson(String),

    /// Shapefile read error.
    #[error("shapefile error: {0}")]
    Shapefile(String),

    /// OSM PBF processing error (string context).
    #[error("osm pbf error: {0}")]
    OsmPbf(String),

    /// Bounding box format error.
    #[error("invalid bbox format: {0}")]
    BboxParse(String),

    /// Source file discovery error.
    #[error("source discovery error: {0}")]
    SourceDiscovery(String),

    /// Osmium extract error.
    #[error("osmium extract error: {0}")]
    Osmium(String),

    /// COLMAP photogrammetry error.
    #[error("colmap photogrammetry error: {0}")]
    Colmap(String),

    /// Brush 3D Gaussian Splatting training error.
    #[error("brush training error: {0}")]
    Brush(String),

    /// ffmpeg frame extraction error.
    #[error("ffmpeg frame extraction error: {0}")]
    Ffmpeg(String),

    /// Node coordinate store error.
    #[error("node store error: {0}")]
    NodeStore(String),

    /// `PMTiles` output error.
    #[error("pmtiles write error: {0}")]
    PmtilesWrite(String),

    /// `GeoTIFF` DEM read error.
    #[error("geotiff error: {0}")]
    GeoTiff(String),

    /// Coordinate reference system error (unsupported or malformed CRS).
    #[error("crs error: {0}")]
    Crs(String),

    /// PLY splat read/parse error.
    #[error("ply error: {0}")]
    Ply(String),

    /// Gaussian splat tiling / 3D Tiles emit error.
    #[error("splat tiling error: {0}")]
    SplatTiles(String),

    /// Raster tile source error (bad template, fetch failure, bad response).
    #[error("raster source error: {0}")]
    RasterSource(String),

    /// Another error, with a note on what was being done when it happened.
    #[error("{context}")]
    Context {
        /// What the caller was doing, for example `failed to read <path>`.
        context: String,
        /// The error that stopped it.
        #[source]
        source: Box<GeolithError>,
    },
}

impl GeolithError {
    /// Wrap this error with a note on what was being done.
    #[must_use]
    pub fn context(self, context: impl Into<String>) -> Self {
        Self::Context {
            context: context.into(),
            source: Box::new(self),
        }
    }
}

/// Convenience alias for library results.
pub type Result<T> = std::result::Result<T, GeolithError>;

/// An error and its chain of causes on one line: `outer: inner: innermost`.
///
/// A cause whose text the line already holds is left out, because several
/// variants print their source in their own message.
#[must_use]
pub fn report(error: &(dyn std::error::Error + 'static)) -> String {
    let mut line = error.to_string();
    let mut next = error.source();
    while let Some(cause) = next {
        let text = cause.to_string();
        if !text.is_empty() && !line.contains(&text) {
            line.push_str(": ");
            line.push_str(&text);
        }
        next = cause.source();
    }
    line
}

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

    #[test]
    fn report_joins_the_chain_of_causes() {
        let error = GeolithError::from(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "no such file",
        ))
        .context("failed to read /data/in.pbf");
        assert_eq!(
            report(&error),
            "failed to read /data/in.pbf: i/o error: no such file"
        );
    }
}