geolith 0.2.2

Shared library of the geolith builders: source readers, conflation, admin areas, tile encoding and the PMTiles and MBTiles writers
Documentation
//! Overture changelog Parquet reader for incremental processing.
//!
//! Reads Overture Maps changelog Parquet files to identify which GERS features
//! have changed between releases. This enables incremental tile generation by
//! only reprocessing tiles affected by changed features.

use std::collections::HashSet;
use std::path::Path;

use arrow::array::{Array, StringArray};
use parquet::arrow::ProjectionMask;
use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;

use crate::error::GeolithError;

/// Column names required from the Overture changelog Parquet file.
const CHANGELOG_COLUMNS: &[&str] = &["id", "change_type"];

/// Type of change in an Overture changelog entry.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ChangeType {
    /// Feature was added in this release.
    Added,
    /// Feature's data changed in this release.
    DataChanged,
    /// Feature was removed in this release.
    Removed,
    /// Feature is unchanged (present for completeness).
    Unchanged,
}

impl ChangeType {
    /// Returns true if this change type indicates the feature needs reprocessing.
    #[must_use]
    pub const fn needs_reprocessing(self) -> bool {
        matches!(
            self,
            ChangeType::Added | ChangeType::DataChanged | ChangeType::Removed
        )
    }
}

/// A single entry from an Overture changelog file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChangelogEntry {
    /// The GERS UUID of the changed feature.
    pub gers_id: String,
    /// The type of change.
    pub change_type: ChangeType,
}

/// Parse a change type string from a changelog Parquet file.
///
/// Returns `None` for unrecognized values.
fn parse_change_type(s: &str) -> Option<ChangeType> {
    match s {
        "added" => Some(ChangeType::Added),
        "data_changed" => Some(ChangeType::DataChanged),
        "removed" => Some(ChangeType::Removed),
        "unchanged" => Some(ChangeType::Unchanged),
        _ => None,
    }
}

/// Read an Overture changelog Parquet file and return the set of changed GERS IDs.
///
/// Filters for `added`, `data_changed`, and `removed` entries only.
/// `unchanged` entries are skipped.
///
/// # Errors
///
/// Returns an error if the file cannot be opened, is not valid Parquet,
/// or is missing required columns (`id`, `change_type`).
pub fn read_changelog(path: &Path) -> crate::error::Result<HashSet<String>> {
    let file = std::fs::File::open(path)?;
    let builder = ParquetRecordBatchReaderBuilder::try_new(file)?;
    let metadata = builder.metadata().clone();
    let num_rows = metadata.file_metadata().num_rows() as usize;

    // Build projection mask for only the columns we need.
    let parquet_schema = builder.parquet_schema();
    let leaf_indices: Vec<usize> = parquet_schema
        .columns()
        .iter()
        .enumerate()
        .filter_map(|(i, col)| CHANGELOG_COLUMNS.contains(&col.name()).then_some(i))
        .collect();
    let mask = ProjectionMask::leaves(parquet_schema, leaf_indices);

    let reader = builder
        .with_projection(mask)
        .with_batch_size(8192)
        .build()?;

    let mut changed_ids = HashSet::with_capacity(num_rows);

    for batch_result in reader {
        let batch = batch_result?;
        let schema = batch.schema();

        let id_idx = schema.index_of("id").map_err(|_| {
            GeolithError::SourceDiscovery("missing 'id' column in changelog file".into())
        })?;
        let change_type_idx = schema.index_of("change_type").map_err(|_| {
            GeolithError::SourceDiscovery("missing 'change_type' column in changelog file".into())
        })?;

        let id_col = batch
            .column(id_idx)
            .as_any()
            .downcast_ref::<StringArray>()
            .ok_or_else(|| {
                GeolithError::SourceDiscovery("'id' column is not a string type".into())
            })?;
        let change_type_col = batch
            .column(change_type_idx)
            .as_any()
            .downcast_ref::<StringArray>()
            .ok_or_else(|| {
                GeolithError::SourceDiscovery("'change_type' column is not a string type".into())
            })?;

        for row in 0..batch.num_rows() {
            if id_col.is_null(row) || change_type_col.is_null(row) {
                continue;
            }

            let change_type_str = change_type_col.value(row);
            match parse_change_type(change_type_str) {
                Some(ct) if ct.needs_reprocessing() => {
                    changed_ids.insert(id_col.value(row).to_string());
                }
                Some(_) => {
                    // Unchanged — skip
                }
                None => {
                    tracing::warn!(
                        change_type = change_type_str,
                        "skipping unknown change_type in changelog"
                    );
                }
            }
        }
    }

    tracing::info!(
        count = changed_ids.len(),
        "loaded changelog: changed GERS IDs"
    );
    Ok(changed_ids)
}

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

    // ── ChangeType::needs_reprocessing ──────────────────────────────

    #[test]
    fn needs_reprocessing_added() {
        assert!(ChangeType::Added.needs_reprocessing());
    }

    #[test]
    fn needs_reprocessing_data_changed() {
        assert!(ChangeType::DataChanged.needs_reprocessing());
    }

    #[test]
    fn needs_reprocessing_removed() {
        assert!(ChangeType::Removed.needs_reprocessing());
    }

    #[test]
    fn needs_reprocessing_unchanged_false() {
        assert!(!ChangeType::Unchanged.needs_reprocessing());
    }

    // ── parse_change_type ───────────────────────────────────────────

    #[test]
    fn parse_change_type_valid_values() {
        assert_eq!(parse_change_type("added"), Some(ChangeType::Added));
        assert_eq!(
            parse_change_type("data_changed"),
            Some(ChangeType::DataChanged)
        );
        assert_eq!(parse_change_type("removed"), Some(ChangeType::Removed));
        assert_eq!(parse_change_type("unchanged"), Some(ChangeType::Unchanged));
    }

    #[test]
    fn parse_change_type_unknown_returns_none() {
        assert_eq!(parse_change_type("unknown"), None);
        assert_eq!(parse_change_type(""), None);
        assert_eq!(parse_change_type("ADDED"), None);
        assert_eq!(parse_change_type("modified"), None);
    }

    // ── ChangelogEntry derives ──────────────────────────────────────

    // ── ChangeType derives ──────────────────────────────────────────

    // ── read_changelog tests use small in-memory Parquet fixtures ────────

    fn write_changelog_parquet(
        path: &std::path::Path,
        rows: &[(Option<&str>, Option<&str>)],
    ) -> std::io::Result<()> {
        use arrow::array::StringArray;
        use arrow::datatypes::{DataType, Field, Schema};
        use arrow::record_batch::RecordBatch;
        use parquet::arrow::ArrowWriter;
        use std::sync::Arc;

        let schema = Arc::new(Schema::new(vec![
            Field::new("id", DataType::Utf8, true),
            Field::new("change_type", DataType::Utf8, true),
        ]));
        let ids: Vec<Option<&str>> = rows.iter().map(|r| r.0).collect();
        let cts: Vec<Option<&str>> = rows.iter().map(|r| r.1).collect();
        let id_arr = StringArray::from(ids);
        let ct_arr = StringArray::from(cts);
        let batch =
            RecordBatch::try_new(schema.clone(), vec![Arc::new(id_arr), Arc::new(ct_arr)]).unwrap();

        let file = std::fs::File::create(path)?;
        let mut writer = ArrowWriter::try_new(file, schema, None).unwrap();
        writer.write(&batch).unwrap();
        writer.close().unwrap();
        Ok(())
    }

    #[test]
    fn read_changelog_filters_to_added_and_changed_only() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let path = dir.path().join("changelog.parquet");
        write_changelog_parquet(
            &path,
            &[
                (Some("a"), Some("added")),
                (Some("b"), Some("data_changed")),
                (Some("c"), Some("removed")),
                (Some("d"), Some("unchanged")),
            ],
        )
        .expect("write");
        let ids = read_changelog(&path).expect("read");
        assert_eq!(ids.len(), 3);
        assert!(ids.contains("a"));
        assert!(ids.contains("b"));
        assert!(ids.contains("c"));
        assert!(!ids.contains("d"));
    }

    #[test]
    fn read_changelog_skips_unknown_change_types() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let path = dir.path().join("changelog.parquet");
        write_changelog_parquet(
            &path,
            &[
                (Some("x"), Some("unknown_type")),
                (Some("y"), Some("added")),
            ],
        )
        .expect("write");
        let ids = read_changelog(&path).expect("read");
        assert_eq!(ids.len(), 1);
        assert!(ids.contains("y"));
    }

    #[test]
    fn read_changelog_skips_null_rows() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let path = dir.path().join("changelog.parquet");
        write_changelog_parquet(
            &path,
            &[
                (None, Some("added")),
                (Some("a"), None),
                (Some("b"), Some("added")),
            ],
        )
        .expect("write");
        let ids = read_changelog(&path).expect("read");
        assert_eq!(ids.len(), 1);
        assert!(ids.contains("b"));
    }

    #[test]
    fn read_changelog_empty_file() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let path = dir.path().join("changelog.parquet");
        write_changelog_parquet(&path, &[]).expect("write empty");
        let ids = read_changelog(&path).expect("read");
        assert!(ids.is_empty());
    }

    #[test]
    fn read_changelog_nonexistent_path_errors() {
        let err =
            read_changelog(std::path::Path::new("/nonexistent/changelog.parquet")).unwrap_err();
        assert!(matches!(err, GeolithError::Io(_)));
    }

    #[test]
    fn read_changelog_invalid_parquet_errors() {
        let dir = tempfile::tempdir().expect("tmpdir");
        let path = dir.path().join("not_parquet.parquet");
        std::fs::write(&path, b"this is not parquet").expect("write");
        let err = read_changelog(&path).unwrap_err();
        // Parquet parse failure surfaces as a Parquet error variant.
        assert!(matches!(err, GeolithError::Parquet(_)));
    }
}