Skip to main content

geolith/conflation/
bridge.rs

1//! Overture GERS bridge file Parquet reader.
2//!
3//! Reads Overture GERS bridge Parquet files to build an in-memory index
4//! mapping OSM element IDs to GERS UUIDs. This enables deduplication of
5//! features that exist in both OSM and Overture datasets.
6
7use std::collections::HashMap;
8use std::path::Path;
9
10use arrow::array::{Array, StringArray};
11use parquet::arrow::ProjectionMask;
12use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
13
14use crate::error::GeolithError;
15
16/// Column names required from the GERS bridge Parquet file.
17const BRIDGE_COLUMNS: &[&str] = &["id", "record_id", "update_time", "dataset"];
18
19/// OSM element type from bridge file `record_id`.
20#[non_exhaustive]
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22pub enum OsmElementType {
23    /// OSM node (`n` prefix in `record_id`).
24    Node,
25    /// OSM way (`w` prefix in `record_id`).
26    Way,
27    /// OSM relation (`r` prefix in `record_id`).
28    Relation,
29}
30
31/// Parsed OSM record ID from a bridge file row.
32///
33/// The `record_id` column in GERS bridge files uses the format
34/// `{prefix}{id}@{version}` where prefix is `n` (node), `w` (way),
35/// or `r` (relation).
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct OsmRecordId {
38    /// The OSM element type (node, way, or relation).
39    pub element_type: OsmElementType,
40    /// The numeric OSM element ID.
41    pub id: u64,
42    /// The OSM element version.
43    pub version: u32,
44}
45
46/// In-memory index mapping OSM IDs to GERS UUIDs.
47///
48/// Loaded from an Overture GERS bridge Parquet file. Each entry maps
49/// an OSM element's numeric ID to its corresponding GERS UUID string.
50#[derive(Default)]
51pub struct BridgeIndex {
52    /// Mapping from OSM element ID → GERS UUID.
53    inner: HashMap<u64, String>,
54    /// The `update_time` from the bridge file (first non-null value).
55    update_time: Option<String>,
56}
57
58impl std::fmt::Debug for BridgeIndex {
59    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60        f.debug_struct("BridgeIndex")
61            .field("entries", &self.inner.len())
62            .field("update_time", &self.update_time)
63            .finish()
64    }
65}
66
67impl BridgeIndex {
68    /// Load a bridge index from a GERS Parquet file.
69    ///
70    /// Reads the Parquet file with column projection (only `id`, `record_id`,
71    /// `update_time`, `dataset` columns). Parses each row's `record_id` to
72    /// extract the numeric OSM ID and maps it to the GERS UUID from the `id`
73    /// column.
74    ///
75    /// # Arguments
76    ///
77    /// * `path` — Path to the GERS bridge Parquet file.
78    /// * `theme_filter` — Optional theme to filter entries by (matched against
79    ///   the `dataset` column). If `None`, all entries are loaded.
80    ///
81    /// # Errors
82    ///
83    /// Returns an error if the file cannot be opened, is not valid Parquet,
84    /// or is missing required columns (`id`, `record_id`).
85    pub fn load(path: &Path, theme_filter: Option<&str>) -> crate::error::Result<Self> {
86        let file = std::fs::File::open(path)?;
87        let builder = ParquetRecordBatchReaderBuilder::try_new(file)?;
88        let metadata = builder.metadata().clone();
89        let num_rows = metadata.file_metadata().num_rows() as usize;
90
91        // Build projection mask for only the columns we need.
92        // Use builder.parquet_schema() which returns &SchemaDescriptor.
93        let parquet_schema = builder.parquet_schema();
94        let leaf_indices: Vec<usize> = parquet_schema
95            .columns()
96            .iter()
97            .enumerate()
98            .filter_map(|(i, col)| BRIDGE_COLUMNS.contains(&col.name()).then_some(i))
99            .collect();
100        let mask = ProjectionMask::leaves(parquet_schema, leaf_indices);
101
102        let reader = builder
103            .with_projection(mask)
104            .with_batch_size(8192)
105            .build()?;
106
107        let mut inner = HashMap::with_capacity(num_rows);
108        let mut first_update_time: Option<String> = None;
109
110        for batch_result in reader {
111            let batch = batch_result?;
112            let schema = batch.schema();
113
114            // Find required column indices in the projected batch
115            let id_idx = schema.index_of("id").map_err(|_| {
116                GeolithError::SourceDiscovery("missing 'id' column in bridge file".into())
117            })?;
118            let record_id_idx = schema.index_of("record_id").map_err(|_| {
119                GeolithError::SourceDiscovery("missing 'record_id' column in bridge file".into())
120            })?;
121
122            let id_col = batch
123                .column(id_idx)
124                .as_any()
125                .downcast_ref::<StringArray>()
126                .ok_or_else(|| {
127                    GeolithError::SourceDiscovery("'id' column is not a string type".into())
128                })?;
129            let record_id_col = batch
130                .column(record_id_idx)
131                .as_any()
132                .downcast_ref::<StringArray>()
133                .ok_or_else(|| {
134                    GeolithError::SourceDiscovery("'record_id' column is not a string type".into())
135                })?;
136
137            // Optional: dataset column for theme filtering
138            let dataset_col = if theme_filter.is_some() {
139                schema
140                    .index_of("dataset")
141                    .ok()
142                    .and_then(|idx| batch.column(idx).as_any().downcast_ref::<StringArray>())
143            } else {
144                None
145            };
146
147            // Capture first update_time value for version validation
148            if first_update_time.is_none()
149                && let Some(ut_arr) = schema
150                    .index_of("update_time")
151                    .ok()
152                    .and_then(|idx| batch.column(idx).as_any().downcast_ref::<StringArray>())
153                && batch.num_rows() > 0
154                && !ut_arr.is_null(0)
155            {
156                first_update_time = Some(ut_arr.value(0).to_string());
157            }
158
159            for row in 0..batch.num_rows() {
160                if id_col.is_null(row) || record_id_col.is_null(row) {
161                    continue;
162                }
163
164                // Apply theme filter against dataset column
165                if let Some(filter) = theme_filter
166                    && let Some(ds_col) = dataset_col
167                    && (ds_col.is_null(row) || !ds_col.value(row).contains(filter))
168                {
169                    continue;
170                }
171
172                let record_id_str = record_id_col.value(row);
173                match parse_record_id(record_id_str) {
174                    Ok(parsed) => {
175                        let gers_uuid = id_col.value(row).to_string();
176                        inner.insert(parsed.id, gers_uuid);
177                    }
178                    Err(e) => {
179                        tracing::trace!(
180                            record_id = record_id_str,
181                            "skipping unparseable bridge record_id: {e}"
182                        );
183                    }
184                }
185            }
186        }
187
188        tracing::info!(entries = inner.len(), "loaded GERS bridge index");
189        Ok(Self {
190            inner,
191            update_time: first_update_time,
192        })
193    }
194
195    /// Check if the index contains a mapping for the given OSM ID.
196    #[must_use]
197    pub fn contains(&self, osm_id: u64) -> bool {
198        self.inner.contains_key(&osm_id)
199    }
200
201    /// Get the GERS UUID for an OSM ID, if present.
202    #[must_use]
203    pub fn get(&self, osm_id: u64) -> Option<&str> {
204        self.inner.get(&osm_id).map(String::as_str)
205    }
206
207    /// Get the number of entries in the index.
208    #[must_use]
209    pub fn len(&self) -> usize {
210        self.inner.len()
211    }
212
213    /// Check if the index is empty.
214    #[must_use]
215    pub fn is_empty(&self) -> bool {
216        self.inner.is_empty()
217    }
218
219    /// Get the bridge file's update timestamp (first non-null value).
220    #[must_use]
221    pub fn update_time(&self) -> Option<&str> {
222        self.update_time.as_deref()
223    }
224
225    /// Iterate over all `(osm_id, gers_uuid)` pairs in the index.
226    pub fn iter(&self) -> impl Iterator<Item = (u64, &str)> {
227        self.inner.iter().map(|(&k, v)| (k, v.as_str()))
228    }
229}
230
231#[cfg(test)]
232impl BridgeIndex {
233    /// Create a `BridgeIndex` from pre-built entries (test-only).
234    pub fn from_entries(entries: impl IntoIterator<Item = (u64, String)>) -> Self {
235        Self {
236            inner: entries.into_iter().collect(),
237            update_time: None,
238        }
239    }
240}
241
242/// Parse an OSM `record_id` string from a GERS bridge file.
243///
244/// # Format
245///
246/// `{prefix}{id}@{version}` where:
247/// - prefix: `n` (node), `w` (way), `r` (relation)
248/// - id: numeric OSM element ID
249/// - version: numeric OSM element version
250///
251/// # Errors
252///
253/// Returns [`GeolithError::SourceDiscovery`] if the string is empty,
254/// has an invalid prefix, is missing the `@` separator, or contains
255/// non-numeric values.
256pub fn parse_record_id(record_id: &str) -> crate::error::Result<OsmRecordId> {
257    if record_id.is_empty() {
258        return Err(GeolithError::SourceDiscovery("empty record_id".into()));
259    }
260
261    let prefix = record_id.as_bytes()[0];
262    let element_type = match prefix {
263        b'n' => OsmElementType::Node,
264        b'w' => OsmElementType::Way,
265        b'r' => OsmElementType::Relation,
266        _ => {
267            return Err(GeolithError::SourceDiscovery(format!(
268                "invalid record_id prefix '{}' in '{record_id}'",
269                prefix as char
270            )));
271        }
272    };
273
274    let rest = &record_id[1..];
275    let at_pos = rest.find('@').ok_or_else(|| {
276        GeolithError::SourceDiscovery(format!("missing '@' separator in record_id '{record_id}'"))
277    })?;
278
279    let id_str = &rest[..at_pos];
280    let version_str = &rest[at_pos + 1..];
281
282    let id: u64 = id_str.parse().map_err(|e| {
283        GeolithError::SourceDiscovery(format!(
284            "invalid numeric id in record_id '{record_id}': {e}"
285        ))
286    })?;
287
288    let version: u32 = version_str.parse().map_err(|e| {
289        GeolithError::SourceDiscovery(format!("invalid version in record_id '{record_id}': {e}"))
290    })?;
291
292    Ok(OsmRecordId {
293        element_type,
294        id,
295        version,
296    })
297}
298
299#[cfg(test)]
300mod tests {
301    use super::*;
302
303    // ── parse_record_id ──────────────────────────────────────────────
304
305    #[test]
306    fn parse_record_id_node() {
307        let parsed = parse_record_id("n123@1").unwrap();
308        assert_eq!(parsed.element_type, OsmElementType::Node);
309        assert_eq!(parsed.id, 123);
310        assert_eq!(parsed.version, 1);
311    }
312
313    #[test]
314    fn parse_record_id_way() {
315        let parsed = parse_record_id("w456789@2").unwrap();
316        assert_eq!(parsed.element_type, OsmElementType::Way);
317        assert_eq!(parsed.id, 456789);
318        assert_eq!(parsed.version, 2);
319    }
320
321    #[test]
322    fn parse_record_id_relation() {
323        let parsed = parse_record_id("r12345@3").unwrap();
324        assert_eq!(parsed.element_type, OsmElementType::Relation);
325        assert_eq!(parsed.id, 12345);
326        assert_eq!(parsed.version, 3);
327    }
328
329    #[test]
330    fn parse_record_id_large_values() {
331        let parsed = parse_record_id("w9999999999@999").unwrap();
332        assert_eq!(parsed.element_type, OsmElementType::Way);
333        assert_eq!(parsed.id, 9_999_999_999);
334        assert_eq!(parsed.version, 999);
335    }
336
337    #[test]
338    fn parse_record_id_empty_errors() {
339        assert!(parse_record_id("").is_err());
340    }
341
342    #[test]
343    fn parse_record_id_missing_at_errors() {
344        assert!(parse_record_id("w123").is_err());
345    }
346
347    #[test]
348    fn parse_record_id_invalid_prefix_errors() {
349        assert!(parse_record_id("x123@1").is_err());
350    }
351
352    #[test]
353    fn parse_record_id_non_numeric_id_errors() {
354        assert!(parse_record_id("wabc@1").is_err());
355    }
356
357    #[test]
358    fn parse_record_id_non_numeric_version_errors() {
359        assert!(parse_record_id("w123@abc").is_err());
360    }
361
362    // ── validate_bridge_version ──────────────────────────────────────
363
364    // ── BridgeIndex ──────────────────────────────────────────────────
365
366    #[test]
367    fn bridge_index_empty() {
368        let index = BridgeIndex::from_entries(std::iter::empty());
369        assert!(index.is_empty());
370        assert_eq!(index.len(), 0);
371        assert!(!index.contains(123));
372        assert!(index.get(123).is_none());
373        assert!(index.update_time().is_none());
374    }
375
376    #[test]
377    fn bridge_index_operations() {
378        let index = BridgeIndex::from_entries(vec![
379            (100, "uuid-100".to_string()),
380            (200, "uuid-200".to_string()),
381        ]);
382        assert_eq!(index.len(), 2);
383        assert!(!index.is_empty());
384        assert!(index.contains(100));
385        assert!(index.contains(200));
386        assert!(!index.contains(300));
387        assert_eq!(index.get(100), Some("uuid-100"));
388        assert_eq!(index.get(200), Some("uuid-200"));
389        assert_eq!(index.get(300), None);
390    }
391
392    // ── extract_date_prefix ──────────────────────────────────────────
393
394    type BridgeRow<'a> = (
395        Option<&'a str>,
396        Option<&'a str>,
397        Option<&'a str>,
398        Option<&'a str>,
399    );
400
401    fn write_bridge_parquet(path: &Path, rows: &[BridgeRow<'_>]) {
402        use arrow::array::StringArray;
403        use arrow::datatypes::{DataType, Field, Schema};
404        use arrow::record_batch::RecordBatch;
405        use parquet::arrow::ArrowWriter;
406        use std::sync::Arc;
407
408        let schema = Arc::new(Schema::new(vec![
409            Field::new("id", DataType::Utf8, true),
410            Field::new("record_id", DataType::Utf8, true),
411            Field::new("update_time", DataType::Utf8, true),
412            Field::new("dataset", DataType::Utf8, true),
413        ]));
414        let ids: Vec<Option<&str>> = rows.iter().map(|r| r.0).collect();
415        let recs: Vec<Option<&str>> = rows.iter().map(|r| r.1).collect();
416        let upds: Vec<Option<&str>> = rows.iter().map(|r| r.2).collect();
417        let dsts: Vec<Option<&str>> = rows.iter().map(|r| r.3).collect();
418        let batch = RecordBatch::try_new(
419            schema.clone(),
420            vec![
421                Arc::new(StringArray::from(ids)),
422                Arc::new(StringArray::from(recs)),
423                Arc::new(StringArray::from(upds)),
424                Arc::new(StringArray::from(dsts)),
425            ],
426        )
427        .expect("batch");
428        let file = std::fs::File::create(path).expect("create");
429        let mut writer = ArrowWriter::try_new(file, schema, None).expect("writer");
430        writer.write(&batch).expect("write");
431        writer.close().expect("close");
432    }
433
434    #[test]
435    fn load_bridge_from_parquet_no_filter() {
436        let dir = tempfile::tempdir().expect("tmp");
437        let path = dir.path().join("bridge.parquet");
438        write_bridge_parquet(
439            &path,
440            &[
441                (
442                    Some("u1"),
443                    Some("n100@1"),
444                    Some("2024-04-16T00:00:00Z"),
445                    Some("buildings"),
446                ),
447                (
448                    Some("u2"),
449                    Some("w200@2"),
450                    Some("2024-04-16T00:00:00Z"),
451                    Some("transportation"),
452                ),
453                (
454                    Some("u3"),
455                    Some("r300@3"),
456                    Some("2024-04-16T00:00:00Z"),
457                    Some("buildings"),
458                ),
459            ],
460        );
461        let idx = BridgeIndex::load(&path, None).expect("load");
462        assert_eq!(idx.len(), 3);
463        assert!(idx.contains(100));
464        assert!(idx.contains(200));
465        assert!(idx.contains(300));
466        assert_eq!(idx.get(100), Some("u1"));
467        let ut = idx.update_time().expect("update_time set");
468        assert!(ut.starts_with("2024-04-16"));
469    }
470
471    #[test]
472    fn load_bridge_with_theme_filter() {
473        let dir = tempfile::tempdir().expect("tmp");
474        let path = dir.path().join("bridge2.parquet");
475        write_bridge_parquet(
476            &path,
477            &[
478                (Some("a"), Some("n1@1"), None, Some("buildings")),
479                (Some("b"), Some("n2@1"), None, Some("transportation")),
480                (Some("c"), Some("n3@1"), None, Some("buildings")),
481            ],
482        );
483        let idx = BridgeIndex::load(&path, Some("buildings")).expect("load");
484        assert_eq!(idx.len(), 2);
485        assert!(idx.contains(1));
486        assert!(idx.contains(3));
487        assert!(!idx.contains(2));
488    }
489
490    #[test]
491    fn load_bridge_skips_invalid_record_ids() {
492        let dir = tempfile::tempdir().expect("tmp");
493        let path = dir.path().join("bridge3.parquet");
494        write_bridge_parquet(
495            &path,
496            &[
497                (Some("ok"), Some("n1@1"), None, None),
498                (Some("bad"), Some("not-a-record-id"), None, None),
499                (Some("alsobad"), Some(""), None, None),
500            ],
501        );
502        let idx = BridgeIndex::load(&path, None).expect("load");
503        assert_eq!(idx.len(), 1, "only valid record_id should be kept");
504    }
505
506    #[test]
507    fn load_bridge_skips_null_rows() {
508        let dir = tempfile::tempdir().expect("tmp");
509        let path = dir.path().join("bridge4.parquet");
510        write_bridge_parquet(
511            &path,
512            &[
513                (None, Some("n1@1"), None, None),
514                (Some("u"), None, None, None),
515                (Some("ok"), Some("n2@1"), None, None),
516            ],
517        );
518        let idx = BridgeIndex::load(&path, None).expect("load");
519        assert_eq!(idx.len(), 1);
520        assert!(idx.contains(2));
521    }
522
523    #[test]
524    fn load_bridge_nonexistent_file_errors() {
525        let err = BridgeIndex::load(Path::new("/nonexistent/bridge.parquet"), None).unwrap_err();
526        assert!(matches!(err, GeolithError::Io(_)));
527    }
528
529    #[test]
530    fn load_bridge_invalid_parquet_errors() {
531        let dir = tempfile::tempdir().expect("tmp");
532        let path = dir.path().join("not_parquet.parquet");
533        std::fs::write(&path, b"not parquet bytes").expect("write");
534        let err = BridgeIndex::load(&path, None).unwrap_err();
535        assert!(matches!(err, GeolithError::Parquet(_)));
536    }
537
538    #[test]
539    fn bridge_index_debug_format() {
540        let idx = BridgeIndex::from_entries(vec![(1, "u1".to_string())]);
541        let dbg = format!("{:?}", idx);
542        assert!(dbg.contains("BridgeIndex"));
543        assert!(dbg.contains("entries"));
544    }
545}