geolith 0.2.1

Shared library of the geolith builders: source readers, conflation, admin areas, tile encoding and the PMTiles and MBTiles writers
Documentation
//! Guarded geometry operations: one bad feature must not stop a build, and
//! must not vanish without a trace.
//!
//! The boolean-operation clipper (`geo` over `i_overlay`) can panic on an
//! invalid ring, for example one with a NaN vertex. [`catch`] runs such an
//! operation under `catch_unwind` and gives back `None` when it panics, so
//! the caller drops that piece. This works only when the binary unwinds: the
//! release profile must not set `panic = "abort"` (`geolith/tests/release_profile.rs`
//! checks the manifest).
//!
//! A caught panic is never silent:
//!
//! - the feature that was being processed is counted once, however many
//!   pieces failed ([`failed_features`]);
//! - the first failures are logged with the feature id, the layer and the
//!   operation ([`first_failures`]); later ones are counted only;
//! - the build compares the count with its limit ([`exceeded`]) and fails
//!   when the limit is passed, so a bad source cannot lose features in bulk
//!   without an error.
//!
//! The counters are process wide. A build calls [`begin_build`] first; the
//! count it reports is the count since then.

use std::cell::RefCell;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};

/// How many failures are kept and logged one by one.
const KEPT_FAILURES: usize = 20;

/// Features that had at least one caught panic, since the process started.
static FAILED_FEATURES: AtomicU64 = AtomicU64::new(0);
/// The value of [`FAILED_FEATURES`] when the current build began.
static BASELINE: AtomicU64 = AtomicU64::new(0);
/// The most failed features the current build may have.
static ALLOWED: AtomicU64 = AtomicU64::new(u64::MAX);
/// The first failures of the current build.
static FIRST: Mutex<Vec<Failure>> = Mutex::new(Vec::new());

/// One caught panic.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Failure {
    /// Id of the feature being processed (0 outside a [`FeatureScope`]).
    pub feature_id: u64,
    /// Name of the layer of that feature (empty outside a scope).
    pub layer: &'static str,
    /// The guarded operation.
    pub op: &'static str,
    /// The panic message.
    pub message: String,
}

impl std::fmt::Display for Failure {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "feature {} in layer {:?}, {}: {}",
            self.feature_id, self.layer, self.op, self.message
        )
    }
}

/// The count passed the limit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Exceeded {
    /// Failed features in this build.
    pub count: u64,
    /// The limit.
    pub allowed: u64,
}

struct Context {
    feature_id: u64,
    layer: &'static str,
    failed: bool,
}

thread_local! {
    static CONTEXT: RefCell<Option<Context>> = const { RefCell::new(None) };
}

/// The feature being processed on this thread. Dropping it counts the
/// feature when a guarded operation failed inside it.
#[must_use = "the feature is counted when the scope is dropped"]
pub struct FeatureScope(());

/// Start a scope for the feature `feature_id` of `layer` on this thread.
pub fn enter(feature_id: u64, layer: &'static str) -> FeatureScope {
    CONTEXT.with(|c| {
        *c.borrow_mut() = Some(Context {
            feature_id,
            layer,
            failed: false,
        });
    });
    FeatureScope(())
}

impl Drop for FeatureScope {
    fn drop(&mut self) {
        let failed = CONTEXT
            .with(|c| c.borrow_mut().take())
            .is_some_and(|ctx| ctx.failed);
        if failed {
            FAILED_FEATURES.fetch_add(1, Ordering::Relaxed);
        }
    }
}

/// Run `work`; when it panics, record the failure and return `None`.
///
/// `op` names the operation in the log.
pub fn catch<T>(op: &'static str, work: impl FnOnce() -> T) -> Option<T> {
    match catch_unwind(AssertUnwindSafe(work)) {
        Ok(value) => Some(value),
        Err(payload) => {
            record(op, message_of(payload.as_ref()));
            None
        }
    }
}

/// The text of a panic payload.
#[must_use]
pub fn message_of(payload: &(dyn std::any::Any + Send)) -> String {
    payload
        .downcast_ref::<String>()
        .map(String::as_str)
        .or_else(|| payload.downcast_ref::<&str>().copied())
        .unwrap_or("unknown panic")
        .to_owned()
}

fn record(op: &'static str, message: String) {
    let (feature_id, layer, in_scope) = CONTEXT.with(|c| {
        let mut slot = c.borrow_mut();
        match slot.as_mut() {
            Some(ctx) => {
                ctx.failed = true;
                (ctx.feature_id, ctx.layer, true)
            }
            None => (0, "", false),
        }
    });
    if !in_scope {
        // No scope will count this one: count it now.
        FAILED_FEATURES.fetch_add(1, Ordering::Relaxed);
    }
    let failure = Failure {
        feature_id,
        layer,
        op,
        message,
    };
    let mut first = FIRST
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    if first.len() < KEPT_FAILURES {
        tracing::warn!("geometry panic caught, piece skipped: {failure}");
        first.push(failure);
    } else {
        tracing::debug!("geometry panic caught, piece skipped: {failure}");
    }
}

/// Features with a caught panic since the process started.
#[must_use]
pub fn failed_features() -> u64 {
    FAILED_FEATURES.load(Ordering::Relaxed)
}

/// Start counting for a build that may have `allowed` failed features.
pub fn begin_build(allowed: u64) {
    BASELINE.store(FAILED_FEATURES.load(Ordering::Relaxed), Ordering::Relaxed);
    ALLOWED.store(allowed, Ordering::Relaxed);
    FIRST
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .clear();
}

/// Failed features since [`begin_build`].
#[must_use]
pub fn build_failures() -> u64 {
    FAILED_FEATURES
        .load(Ordering::Relaxed)
        .saturating_sub(BASELINE.load(Ordering::Relaxed))
}

/// The limit set by [`begin_build`].
#[must_use]
pub fn allowed() -> u64 {
    ALLOWED.load(Ordering::Relaxed)
}

/// `Some` when the build has more failed features than it may have.
#[must_use]
pub fn exceeded() -> Option<Exceeded> {
    let count = build_failures();
    let allowed = allowed();
    (count > allowed).then_some(Exceeded { count, allowed })
}

/// The first failures since [`begin_build`], oldest first.
#[must_use]
pub fn first_failures() -> Vec<Failure> {
    FIRST
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .clone()
}

/// The counters are process wide: a unit test that reads them, or that makes
/// a guarded operation panic, takes this lock for its whole run.
#[cfg(test)]
pub(crate) fn test_lock() -> std::sync::MutexGuard<'static, ()> {
    static LOCK: Mutex<()> = Mutex::new(());
    LOCK.lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
}

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

    use super::test_lock as serial;

    #[test]
    fn a_panic_gives_none_and_a_value_gives_some() {
        let _lock = serial();
        assert_eq!(catch("fine", || 7), Some(7));
        assert_eq!(catch("boom", || -> u8 { panic!("bad ring") }), None);
    }

    #[test]
    fn a_feature_counts_once_however_many_pieces_fail() {
        let _lock = serial();
        begin_build(10);
        let scope = enter(42, "earth");
        for _ in 0..5 {
            assert_eq!(catch("clip", || -> u8 { panic!("bad ring") }), None);
        }
        assert_eq!(build_failures(), 0, "counted when the scope ends");
        drop(scope);
        assert_eq!(build_failures(), 1);
        let first = first_failures();
        assert_eq!(first.len(), 5);
        assert_eq!(first[0].feature_id, 42);
        assert_eq!(first[0].layer, "earth");
        assert_eq!(first[0].op, "clip");
        assert_eq!(first[0].message, "bad ring");
    }

    #[test]
    fn a_scope_without_a_failure_counts_nothing() {
        let _lock = serial();
        begin_build(10);
        drop(enter(1, "water"));
        assert_eq!(build_failures(), 0);
    }

    #[test]
    fn a_failure_outside_a_scope_is_counted_at_once_with_no_feature() {
        let _lock = serial();
        begin_build(10);
        assert_eq!(catch("clip", || -> u8 { panic!("x") }), None);
        assert_eq!(build_failures(), 1);
        assert_eq!(first_failures()[0].feature_id, 0);
    }

    #[test]
    fn the_limit_is_passed_only_above_the_allowed_count() {
        let _lock = serial();
        begin_build(2);
        for id in 0..2 {
            let scope = enter(id, "earth");
            let _ = catch("clip", || -> u8 { panic!("x") });
            drop(scope);
        }
        assert_eq!(exceeded(), None, "two of two allowed");
        let scope = enter(9, "earth");
        let _ = catch("clip", || -> u8 { panic!("x") });
        drop(scope);
        assert_eq!(
            exceeded(),
            Some(Exceeded {
                count: 3,
                allowed: 2
            })
        );
    }

    #[test]
    fn begin_build_forgets_the_earlier_build() {
        let _lock = serial();
        begin_build(0);
        let _ = catch("clip", || -> u8 { panic!("x") });
        assert_eq!(build_failures(), 1);
        begin_build(0);
        assert_eq!(build_failures(), 0);
        assert!(first_failures().is_empty());
    }

    #[test]
    fn only_the_first_failures_are_kept() {
        let _lock = serial();
        begin_build(u64::MAX);
        for _ in 0..(KEPT_FAILURES + 5) {
            let _ = catch("clip", || -> u8 { panic!("x") });
        }
        assert_eq!(first_failures().len(), KEPT_FAILURES);
        assert_eq!(build_failures(), (KEPT_FAILURES + 5) as u64);
    }
}