geolith 0.1.6

Shared library of the geolith builders: source readers, conflation, admin areas, tile encoding and the PMTiles and MBTiles writers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
//! Overture GERS bridge file Parquet reader.
//!
//! Reads Overture GERS bridge Parquet files to build an in-memory index
//! mapping OSM element IDs to GERS UUIDs. This enables deduplication of
//! features that exist in both OSM and Overture datasets.

use std::collections::HashMap;
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 GERS bridge Parquet file.
const BRIDGE_COLUMNS: &[&str] = &["id", "record_id", "update_time", "dataset"];

/// OSM element type from bridge file `record_id`.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum OsmElementType {
    /// OSM node (`n` prefix in `record_id`).
    Node,
    /// OSM way (`w` prefix in `record_id`).
    Way,
    /// OSM relation (`r` prefix in `record_id`).
    Relation,
}

/// Parsed OSM record ID from a bridge file row.
///
/// The `record_id` column in GERS bridge files uses the format
/// `{prefix}{id}@{version}` where prefix is `n` (node), `w` (way),
/// or `r` (relation).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OsmRecordId {
    /// The OSM element type (node, way, or relation).
    pub element_type: OsmElementType,
    /// The numeric OSM element ID.
    pub id: u64,
    /// The OSM element version.
    pub version: u32,
}

/// In-memory index mapping OSM IDs to GERS UUIDs.
///
/// Loaded from an Overture GERS bridge Parquet file. Each entry maps
/// an OSM element's numeric ID to its corresponding GERS UUID string.
#[derive(Default)]
pub struct BridgeIndex {
    /// Mapping from OSM element ID → GERS UUID.
    inner: HashMap<u64, String>,
    /// The `update_time` from the bridge file (first non-null value).
    update_time: Option<String>,
}

impl std::fmt::Debug for BridgeIndex {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BridgeIndex")
            .field("entries", &self.inner.len())
            .field("update_time", &self.update_time)
            .finish()
    }
}

impl BridgeIndex {
    /// Load a bridge index from a GERS Parquet file.
    ///
    /// Reads the Parquet file with column projection (only `id`, `record_id`,
    /// `update_time`, `dataset` columns). Parses each row's `record_id` to
    /// extract the numeric OSM ID and maps it to the GERS UUID from the `id`
    /// column.
    ///
    /// # Arguments
    ///
    /// * `path` — Path to the GERS bridge Parquet file.
    /// * `theme_filter` — Optional theme to filter entries by (matched against
    ///   the `dataset` column). If `None`, all entries are loaded.
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be opened, is not valid Parquet,
    /// or is missing required columns (`id`, `record_id`).
    pub fn load(path: &Path, theme_filter: Option<&str>) -> crate::error::Result<Self> {
        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.
        // Use builder.parquet_schema() which returns &SchemaDescriptor.
        let parquet_schema = builder.parquet_schema();
        let leaf_indices: Vec<usize> = parquet_schema
            .columns()
            .iter()
            .enumerate()
            .filter_map(|(i, col)| BRIDGE_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 inner = HashMap::with_capacity(num_rows);
        let mut first_update_time: Option<String> = None;

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

            // Find required column indices in the projected batch
            let id_idx = schema.index_of("id").map_err(|_| {
                GeolithError::SourceDiscovery("missing 'id' column in bridge file".into())
            })?;
            let record_id_idx = schema.index_of("record_id").map_err(|_| {
                GeolithError::SourceDiscovery("missing 'record_id' column in bridge 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 record_id_col = batch
                .column(record_id_idx)
                .as_any()
                .downcast_ref::<StringArray>()
                .ok_or_else(|| {
                    GeolithError::SourceDiscovery("'record_id' column is not a string type".into())
                })?;

            // Optional: dataset column for theme filtering
            let dataset_col = if theme_filter.is_some() {
                schema
                    .index_of("dataset")
                    .ok()
                    .and_then(|idx| batch.column(idx).as_any().downcast_ref::<StringArray>())
            } else {
                None
            };

            // Capture first update_time value for version validation
            if first_update_time.is_none()
                && let Some(ut_arr) = schema
                    .index_of("update_time")
                    .ok()
                    .and_then(|idx| batch.column(idx).as_any().downcast_ref::<StringArray>())
                && batch.num_rows() > 0
                && !ut_arr.is_null(0)
            {
                first_update_time = Some(ut_arr.value(0).to_string());
            }

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

                // Apply theme filter against dataset column
                if let Some(filter) = theme_filter
                    && let Some(ds_col) = dataset_col
                    && (ds_col.is_null(row) || !ds_col.value(row).contains(filter))
                {
                    continue;
                }

                let record_id_str = record_id_col.value(row);
                match parse_record_id(record_id_str) {
                    Ok(parsed) => {
                        let gers_uuid = id_col.value(row).to_string();
                        inner.insert(parsed.id, gers_uuid);
                    }
                    Err(e) => {
                        tracing::trace!(
                            record_id = record_id_str,
                            "skipping unparseable bridge record_id: {e}"
                        );
                    }
                }
            }
        }

        tracing::info!(entries = inner.len(), "loaded GERS bridge index");
        Ok(Self {
            inner,
            update_time: first_update_time,
        })
    }

    /// Check if the index contains a mapping for the given OSM ID.
    #[must_use]
    pub fn contains(&self, osm_id: u64) -> bool {
        self.inner.contains_key(&osm_id)
    }

    /// Get the GERS UUID for an OSM ID, if present.
    #[must_use]
    pub fn get(&self, osm_id: u64) -> Option<&str> {
        self.inner.get(&osm_id).map(String::as_str)
    }

    /// Get the number of entries in the index.
    #[must_use]
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Check if the index is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Get the bridge file's update timestamp (first non-null value).
    #[must_use]
    pub fn update_time(&self) -> Option<&str> {
        self.update_time.as_deref()
    }

    /// Iterate over all `(osm_id, gers_uuid)` pairs in the index.
    pub fn iter(&self) -> impl Iterator<Item = (u64, &str)> {
        self.inner.iter().map(|(&k, v)| (k, v.as_str()))
    }
}

#[cfg(test)]
impl BridgeIndex {
    /// Create a `BridgeIndex` from pre-built entries (test-only).
    pub fn from_entries(entries: impl IntoIterator<Item = (u64, String)>) -> Self {
        Self {
            inner: entries.into_iter().collect(),
            update_time: None,
        }
    }
}

/// Parse an OSM `record_id` string from a GERS bridge file.
///
/// # Format
///
/// `{prefix}{id}@{version}` where:
/// - prefix: `n` (node), `w` (way), `r` (relation)
/// - id: numeric OSM element ID
/// - version: numeric OSM element version
///
/// # Errors
///
/// Returns [`GeolithError::SourceDiscovery`] if the string is empty,
/// has an invalid prefix, is missing the `@` separator, or contains
/// non-numeric values.
pub fn parse_record_id(record_id: &str) -> crate::error::Result<OsmRecordId> {
    if record_id.is_empty() {
        return Err(GeolithError::SourceDiscovery("empty record_id".into()));
    }

    let prefix = record_id.as_bytes()[0];
    let element_type = match prefix {
        b'n' => OsmElementType::Node,
        b'w' => OsmElementType::Way,
        b'r' => OsmElementType::Relation,
        _ => {
            return Err(GeolithError::SourceDiscovery(format!(
                "invalid record_id prefix '{}' in '{record_id}'",
                prefix as char
            )));
        }
    };

    let rest = &record_id[1..];
    let at_pos = rest.find('@').ok_or_else(|| {
        GeolithError::SourceDiscovery(format!("missing '@' separator in record_id '{record_id}'"))
    })?;

    let id_str = &rest[..at_pos];
    let version_str = &rest[at_pos + 1..];

    let id: u64 = id_str.parse().map_err(|e| {
        GeolithError::SourceDiscovery(format!(
            "invalid numeric id in record_id '{record_id}': {e}"
        ))
    })?;

    let version: u32 = version_str.parse().map_err(|e| {
        GeolithError::SourceDiscovery(format!("invalid version in record_id '{record_id}': {e}"))
    })?;

    Ok(OsmRecordId {
        element_type,
        id,
        version,
    })
}

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

    // ── parse_record_id ──────────────────────────────────────────────

    #[test]
    fn parse_record_id_node() {
        let parsed = parse_record_id("n123@1").unwrap();
        assert_eq!(parsed.element_type, OsmElementType::Node);
        assert_eq!(parsed.id, 123);
        assert_eq!(parsed.version, 1);
    }

    #[test]
    fn parse_record_id_way() {
        let parsed = parse_record_id("w456789@2").unwrap();
        assert_eq!(parsed.element_type, OsmElementType::Way);
        assert_eq!(parsed.id, 456789);
        assert_eq!(parsed.version, 2);
    }

    #[test]
    fn parse_record_id_relation() {
        let parsed = parse_record_id("r12345@3").unwrap();
        assert_eq!(parsed.element_type, OsmElementType::Relation);
        assert_eq!(parsed.id, 12345);
        assert_eq!(parsed.version, 3);
    }

    #[test]
    fn parse_record_id_large_values() {
        let parsed = parse_record_id("w9999999999@999").unwrap();
        assert_eq!(parsed.element_type, OsmElementType::Way);
        assert_eq!(parsed.id, 9_999_999_999);
        assert_eq!(parsed.version, 999);
    }

    #[test]
    fn parse_record_id_empty_errors() {
        assert!(parse_record_id("").is_err());
    }

    #[test]
    fn parse_record_id_missing_at_errors() {
        assert!(parse_record_id("w123").is_err());
    }

    #[test]
    fn parse_record_id_invalid_prefix_errors() {
        assert!(parse_record_id("x123@1").is_err());
    }

    #[test]
    fn parse_record_id_non_numeric_id_errors() {
        assert!(parse_record_id("wabc@1").is_err());
    }

    #[test]
    fn parse_record_id_non_numeric_version_errors() {
        assert!(parse_record_id("w123@abc").is_err());
    }

    // ── validate_bridge_version ──────────────────────────────────────

    // ── BridgeIndex ──────────────────────────────────────────────────

    #[test]
    fn bridge_index_empty() {
        let index = BridgeIndex::from_entries(std::iter::empty());
        assert!(index.is_empty());
        assert_eq!(index.len(), 0);
        assert!(!index.contains(123));
        assert!(index.get(123).is_none());
        assert!(index.update_time().is_none());
    }

    #[test]
    fn bridge_index_operations() {
        let index = BridgeIndex::from_entries(vec![
            (100, "uuid-100".to_string()),
            (200, "uuid-200".to_string()),
        ]);
        assert_eq!(index.len(), 2);
        assert!(!index.is_empty());
        assert!(index.contains(100));
        assert!(index.contains(200));
        assert!(!index.contains(300));
        assert_eq!(index.get(100), Some("uuid-100"));
        assert_eq!(index.get(200), Some("uuid-200"));
        assert_eq!(index.get(300), None);
    }

    // ── extract_date_prefix ──────────────────────────────────────────

    type BridgeRow<'a> = (
        Option<&'a str>,
        Option<&'a str>,
        Option<&'a str>,
        Option<&'a str>,
    );

    fn write_bridge_parquet(path: &Path, rows: &[BridgeRow<'_>]) {
        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("record_id", DataType::Utf8, true),
            Field::new("update_time", DataType::Utf8, true),
            Field::new("dataset", DataType::Utf8, true),
        ]));
        let ids: Vec<Option<&str>> = rows.iter().map(|r| r.0).collect();
        let recs: Vec<Option<&str>> = rows.iter().map(|r| r.1).collect();
        let upds: Vec<Option<&str>> = rows.iter().map(|r| r.2).collect();
        let dsts: Vec<Option<&str>> = rows.iter().map(|r| r.3).collect();
        let batch = RecordBatch::try_new(
            schema.clone(),
            vec![
                Arc::new(StringArray::from(ids)),
                Arc::new(StringArray::from(recs)),
                Arc::new(StringArray::from(upds)),
                Arc::new(StringArray::from(dsts)),
            ],
        )
        .expect("batch");
        let file = std::fs::File::create(path).expect("create");
        let mut writer = ArrowWriter::try_new(file, schema, None).expect("writer");
        writer.write(&batch).expect("write");
        writer.close().expect("close");
    }

    #[test]
    fn load_bridge_from_parquet_no_filter() {
        let dir = tempfile::tempdir().expect("tmp");
        let path = dir.path().join("bridge.parquet");
        write_bridge_parquet(
            &path,
            &[
                (
                    Some("u1"),
                    Some("n100@1"),
                    Some("2024-04-16T00:00:00Z"),
                    Some("buildings"),
                ),
                (
                    Some("u2"),
                    Some("w200@2"),
                    Some("2024-04-16T00:00:00Z"),
                    Some("transportation"),
                ),
                (
                    Some("u3"),
                    Some("r300@3"),
                    Some("2024-04-16T00:00:00Z"),
                    Some("buildings"),
                ),
            ],
        );
        let idx = BridgeIndex::load(&path, None).expect("load");
        assert_eq!(idx.len(), 3);
        assert!(idx.contains(100));
        assert!(idx.contains(200));
        assert!(idx.contains(300));
        assert_eq!(idx.get(100), Some("u1"));
        let ut = idx.update_time().expect("update_time set");
        assert!(ut.starts_with("2024-04-16"));
    }

    #[test]
    fn load_bridge_with_theme_filter() {
        let dir = tempfile::tempdir().expect("tmp");
        let path = dir.path().join("bridge2.parquet");
        write_bridge_parquet(
            &path,
            &[
                (Some("a"), Some("n1@1"), None, Some("buildings")),
                (Some("b"), Some("n2@1"), None, Some("transportation")),
                (Some("c"), Some("n3@1"), None, Some("buildings")),
            ],
        );
        let idx = BridgeIndex::load(&path, Some("buildings")).expect("load");
        assert_eq!(idx.len(), 2);
        assert!(idx.contains(1));
        assert!(idx.contains(3));
        assert!(!idx.contains(2));
    }

    #[test]
    fn load_bridge_skips_invalid_record_ids() {
        let dir = tempfile::tempdir().expect("tmp");
        let path = dir.path().join("bridge3.parquet");
        write_bridge_parquet(
            &path,
            &[
                (Some("ok"), Some("n1@1"), None, None),
                (Some("bad"), Some("not-a-record-id"), None, None),
                (Some("alsobad"), Some(""), None, None),
            ],
        );
        let idx = BridgeIndex::load(&path, None).expect("load");
        assert_eq!(idx.len(), 1, "only valid record_id should be kept");
    }

    #[test]
    fn load_bridge_skips_null_rows() {
        let dir = tempfile::tempdir().expect("tmp");
        let path = dir.path().join("bridge4.parquet");
        write_bridge_parquet(
            &path,
            &[
                (None, Some("n1@1"), None, None),
                (Some("u"), None, None, None),
                (Some("ok"), Some("n2@1"), None, None),
            ],
        );
        let idx = BridgeIndex::load(&path, None).expect("load");
        assert_eq!(idx.len(), 1);
        assert!(idx.contains(2));
    }

    #[test]
    fn load_bridge_nonexistent_file_errors() {
        let err = BridgeIndex::load(Path::new("/nonexistent/bridge.parquet"), None).unwrap_err();
        assert!(matches!(err, GeolithError::Io(_)));
    }

    #[test]
    fn load_bridge_invalid_parquet_errors() {
        let dir = tempfile::tempdir().expect("tmp");
        let path = dir.path().join("not_parquet.parquet");
        std::fs::write(&path, b"not parquet bytes").expect("write");
        let err = BridgeIndex::load(&path, None).unwrap_err();
        assert!(matches!(err, GeolithError::Parquet(_)));
    }

    #[test]
    fn bridge_index_debug_format() {
        let idx = BridgeIndex::from_entries(vec![(1, "u1".to_string())]);
        let dbg = format!("{:?}", idx);
        assert!(dbg.contains("BridgeIndex"));
        assert!(dbg.contains("entries"));
    }
}