Skip to main content

geolith/source/
mod.rs

1//! Overture Maps Parquet data reading, filtering, and source routing.
2//!
3//! The source router discovers Parquet files in the Overture data directory,
4//! matches each to an output layer via the `ROUTES` table, and provides
5//! an iterator of `SourceFile`s for the pipeline to process.
6
7use std::path::{Path, PathBuf};
8
9use crate::layer::Layer;
10
11pub mod bbox_filter;
12pub mod geojson_reader;
13pub mod input;
14pub mod natural_earth;
15pub mod node_store;
16pub mod osm;
17pub mod osmium;
18pub mod reader;
19pub mod schema;
20pub mod shapefile_reader;
21
22use schema::OvertureType;
23
24/// A single Overture source file matched to an output layer.
25#[derive(Debug, Clone)]
26pub struct SourceFile {
27    /// Path to the Parquet file.
28    pub path: PathBuf,
29    /// The Overture theme/type of this file.
30    pub overture_type: OvertureType,
31    /// The output layer(s) this source maps to.
32    pub target_layers: &'static [Layer],
33}
34
35/// A route mapping an Overture type to output layer(s).
36struct Route {
37    /// Overture theme (directory name, e.g., "buildings").
38    theme: &'static str,
39    /// Overture type (directory name, e.g., "building").
40    otype: &'static str,
41    /// Output layer(s) this source contributes to.
42    layers: &'static [Layer],
43}
44
45/// Static dispatch table: Overture theme/type → protomaps output layer(s).
46///
47/// Each entry maps an Overture data type to one or more output layers.
48/// A single Overture type can contribute to multiple layers (e.g., divisions
49/// contribute to both `Boundaries` and `Places`).
50const ROUTES: &[Route] = &[
51    // Buildings
52    Route {
53        theme: "buildings",
54        otype: "building",
55        layers: &[Layer::Buildings],
56    },
57    Route {
58        theme: "buildings",
59        otype: "building_part",
60        layers: &[Layer::Buildings],
61    },
62    // Base theme
63    Route {
64        theme: "base",
65        otype: "land",
66        // Vegetation subtypes (forest, grass, scrub, sand...) are landuse, as
67        // in protomaps; only `subtype = land` stays earth.
68        layers: &[Layer::Earth, Layer::Landuse],
69    },
70    Route {
71        theme: "base",
72        otype: "water",
73        layers: &[Layer::Water],
74    },
75    Route {
76        theme: "base",
77        otype: "land_use",
78        layers: &[Layer::Landuse],
79    },
80    Route {
81        theme: "base",
82        otype: "land_cover",
83        layers: &[Layer::Landcover],
84    },
85    Route {
86        theme: "base",
87        otype: "bathymetry",
88        layers: &[Layer::Bathymetry],
89    },
90    Route {
91        theme: "base",
92        otype: "infrastructure",
93        layers: &[Layer::Transit],
94    },
95    // Divisions
96    Route {
97        theme: "divisions",
98        otype: "division",
99        layers: &[Layer::Places],
100    },
101    Route {
102        theme: "divisions",
103        otype: "division_boundary",
104        layers: &[Layer::Boundaries],
105    },
106    // Places
107    Route {
108        theme: "places",
109        otype: "place",
110        layers: &[Layer::Pois],
111    },
112    // Transportation
113    Route {
114        theme: "transportation",
115        otype: "segment",
116        layers: &[Layer::Roads],
117    },
118    // Addresses (geocoding pipeline — no tile output layers)
119    Route {
120        theme: "addresses",
121        otype: "address",
122        layers: &[],
123    },
124    // Admin polygons for geocoding enrichment — no tile output layers
125    Route {
126        theme: "divisions",
127        otype: "division_area",
128        layers: &[],
129    },
130];
131
132/// Discover all Overture Parquet files in a data directory.
133///
134/// Expects the standard Overture directory layout:
135/// ```text
136/// data/
137///   theme=buildings/
138///     type=building/
139///       part-00000.parquet
140///       ...
141///   theme=base/
142///     type=land/
143///       ...
144/// ```
145///
146/// Returns a list of `SourceFile`s matched to their output layers.
147/// Files that don't match any route are skipped with a warning.
148///
149/// # Errors
150///
151/// `GeolithError::SourceDiscovery` when `data_dir` is not a directory, and
152/// `GeolithError::Io` when a directory or one of its entries cannot be read.
153pub fn discover(data_dir: &Path) -> crate::error::Result<Vec<SourceFile>> {
154    let mut sources = Vec::new();
155
156    if !data_dir.is_dir() {
157        return Err(crate::error::GeolithError::SourceDiscovery(format!(
158            "Data directory does not exist: {}",
159            data_dir.display()
160        )));
161    }
162
163    // Scan theme directories
164    for theme_entry in std::fs::read_dir(data_dir)? {
165        let theme_entry = theme_entry?;
166        let theme_path = theme_entry.path();
167        if !theme_path.is_dir() {
168            continue;
169        }
170
171        let theme_name = theme_entry.file_name();
172        let theme_str = theme_name.to_string_lossy();
173        let Some(theme) = theme_str.strip_prefix("theme=") else {
174            tracing::debug!("Skipping non-theme directory: {theme_str}");
175            continue;
176        };
177
178        // Scan type directories within theme
179        for type_entry in std::fs::read_dir(&theme_path)? {
180            let type_entry = type_entry?;
181            let type_path = type_entry.path();
182            if !type_path.is_dir() {
183                continue;
184            }
185
186            let type_name = type_entry.file_name();
187            let type_str = type_name.to_string_lossy();
188            let Some(otype) = type_str.strip_prefix("type=") else {
189                tracing::debug!("Skipping non-type directory: {type_str}");
190                continue;
191            };
192
193            // Find matching route
194            let route = ROUTES.iter().find(|r| r.theme == theme && r.otype == otype);
195
196            let Some(route) = route else {
197                tracing::warn!("No route for theme={theme}/type={otype}, skipping");
198                continue;
199            };
200
201            let overture_type = OvertureType::new(route.theme, route.otype);
202
203            // Scan for Parquet files
204            for file_entry in std::fs::read_dir(&type_path)? {
205                let file_entry = file_entry?;
206                let file_path = file_entry.path();
207
208                if file_path.extension().is_some_and(|ext| ext == "parquet") {
209                    sources.push(SourceFile {
210                        path: file_path,
211                        overture_type,
212                        target_layers: route.layers,
213                    });
214                }
215            }
216        }
217    }
218
219    // Sort so discovery order is deterministic. `read_dir` yields entries in
220    // filesystem order, which differs between APFS and ext4/overlayfs; without
221    // this the emitted record order (and therefore build output) varies by
222    // platform.
223    sources.sort_by(|a, b| a.path.cmp(&b.path));
224
225    tracing::info!(
226        "Discovered {} Parquet files across {} routes",
227        sources.len(),
228        ROUTES.len()
229    );
230
231    Ok(sources)
232}
233
234/// The `theme/type` names of the Overture types a build reads that `found`
235/// holds no file for, in the order of the routing table.
236///
237/// A route is expected when any of its layers is enabled (`enabled`); a route
238/// with no tile layer (the geocoding types) never is. Nothing in `discover`
239/// says a type is absent: a data folder with no buildings builds a planet
240/// without buildings.
241#[must_use]
242pub fn missing_types(found: &[SourceFile], enabled: impl Fn(Layer) -> bool) -> Vec<String> {
243    ROUTES
244        .iter()
245        .filter(|route| route.layers.iter().any(|&layer| enabled(layer)))
246        .filter(|route| {
247            !found.iter().any(|f| {
248                f.overture_type.theme == route.theme && f.overture_type.otype == route.otype
249            })
250        })
251        .map(|route| format!("{}/{}", route.theme, route.otype))
252        .collect()
253}
254
255/// List the Parquet files of one Overture theme/type, sorted by path.
256///
257/// Unlike [`discover`], this reads a type that has no tile-layer route (such
258/// as `divisions/division_area`, used only for geocoding). A missing type
259/// directory yields an empty list.
260///
261/// # Errors
262///
263/// `GeolithError::Io` when the type directory or one of its entries cannot be
264/// read.
265pub fn overture_files(
266    data_dir: &Path,
267    otype: OvertureType,
268) -> crate::error::Result<Vec<std::path::PathBuf>> {
269    let dir = data_dir
270        .join(format!("theme={}", otype.theme))
271        .join(format!("type={}", otype.otype));
272    if !dir.is_dir() {
273        return Ok(Vec::new());
274    }
275    let mut files: Vec<std::path::PathBuf> = std::fs::read_dir(&dir)
276        .and_then(|entries| entries.map(|e| e.map(|e| e.path())).collect())?;
277    files.retain(|path| path.extension().is_some_and(|ext| ext == "parquet"));
278    // `read_dir` order is platform-dependent; sort for deterministic output.
279    files.sort();
280    Ok(files)
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286
287    #[test]
288    fn discover_nonexistent_dir_errors() {
289        let result = discover(Path::new("/tmp/nonexistent-geolith-test"));
290        assert!(result.is_err());
291    }
292
293    #[test]
294    fn discover_empty_dir_returns_empty() {
295        let tmp = tempfile::tempdir().unwrap();
296        let sources = discover(tmp.path()).unwrap();
297        assert!(sources.is_empty());
298    }
299
300    #[test]
301    fn discover_finds_parquet_files() {
302        let tmp = tempfile::tempdir().unwrap();
303
304        // Create Overture directory structure
305        let building_dir = tmp.path().join("theme=buildings").join("type=building");
306        std::fs::create_dir_all(&building_dir).unwrap();
307        std::fs::write(building_dir.join("part-00000.parquet"), b"fake").unwrap();
308        std::fs::write(building_dir.join("part-00001.parquet"), b"fake").unwrap();
309
310        // Non-matching directory (should be skipped)
311        let unknown_dir = tmp.path().join("theme=unknown").join("type=stuff");
312        std::fs::create_dir_all(&unknown_dir).unwrap();
313        std::fs::write(unknown_dir.join("data.parquet"), b"fake").unwrap();
314
315        let sources = discover(tmp.path()).unwrap();
316        assert_eq!(sources.len(), 2);
317        assert!(sources.iter().all(|s| s.overture_type.theme == "buildings"));
318        assert!(
319            sources
320                .iter()
321                .all(|s| s.target_layers == [Layer::Buildings])
322        );
323    }
324
325    fn file(theme: &'static str, otype: &'static str) -> SourceFile {
326        let route = ROUTES
327            .iter()
328            .find(|r| r.theme == theme && r.otype == otype)
329            .expect("a route");
330        SourceFile {
331            path: PathBuf::from(format!("{theme}/{otype}/part-0.parquet")),
332            overture_type: OvertureType::new(route.theme, route.otype),
333            target_layers: route.layers,
334        }
335    }
336
337    /// The types a build reads but the folder lacks, in the order of the
338    /// routing table. A route with no tile layer (the geocoding types) is never
339    /// expected, and a route is expected when any of its layers is enabled.
340    #[test]
341    fn missing_types_names_each_expected_type_without_a_file() {
342        let found = [file("buildings", "building"), file("base", "water")];
343        let all = |_: Layer| true;
344        let missing = missing_types(&found, all);
345        assert!(!missing.contains(&"buildings/building".to_owned()));
346        assert!(!missing.contains(&"base/water".to_owned()));
347        for expected in [
348            "transportation/segment",
349            "base/land",
350            "base/land_use",
351            "base/land_cover",
352            "base/bathymetry",
353            "base/infrastructure",
354            "divisions/division",
355            "divisions/division_boundary",
356            "places/place",
357            "buildings/building_part",
358        ] {
359            assert!(
360                missing.contains(&expected.to_owned()),
361                "{expected} in {missing:?}"
362            );
363        }
364        assert!(
365            !missing
366                .iter()
367                .any(|m| m.starts_with("addresses/") || m == "divisions/division_area"),
368            "geocoding-only types are not tile inputs: {missing:?}"
369        );
370    }
371
372    #[test]
373    fn a_type_only_disabled_layers_read_is_not_missing() {
374        // Buildings off: neither building nor building_part is expected.
375        let none = missing_types(&[], |layer| layer != Layer::Buildings);
376        assert!(!none.contains(&"buildings/building".to_owned()));
377        assert!(!none.contains(&"buildings/building_part".to_owned()));
378        assert!(none.contains(&"transportation/segment".to_owned()));
379        // base/land feeds Earth and Landuse: expected while either is on.
380        let earth_only = missing_types(&[], |layer| layer == Layer::Earth);
381        assert_eq!(earth_only, vec!["base/land".to_owned()]);
382        let nothing = missing_types(&[], |_| false);
383        assert!(nothing.is_empty());
384    }
385}