use std::fs::File;
use std::io::BufWriter;
use std::path::{Path, PathBuf};
use crate::error::{Result, SearchError};
use crate::admin::{AdminHierarchyIndex, load_admin_index};
use crate::dedup::{OvertureSpill, bucket_count, is_deduped};
use crate::division::{DivisionIndex, division_record};
use crate::importance::Wikipedia;
use crate::options::{PgIndexFlavor, SearchOptions};
use crate::osm::{
SettlementIndex, address_twin, fill_locality, is_notable, may_be_record, osm_record_with,
};
use crate::output::buildings::OvertureBuildingsWriter;
use crate::output::glx::{DEFAULT_SORT_BYTES, GlxWriter};
use crate::output::pelias::PeliasWriter;
use crate::output::pg_copy::PgCopyWriter;
use crate::output::photon::PhotonWriter;
use crate::overture::{overture_address_record, overture_place_record};
use crate::place_importance::PlaceSignalIndex;
use crate::record::GeocodingRecord;
use geolith::source::bbox_filter::Bbox;
use geolith::source::reader::read_parquet_file_with_source_id;
#[must_use]
pub fn default_geocoding_output(output: &Path, format: &str) -> PathBuf {
let stem = output
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("geocoding");
let ext = match format {
"photon" | "pelias" => "ndjson",
"glx" => "glx",
_ => "tsv",
};
let filename = format!("{stem}.{ext}");
output
.parent()
.unwrap_or_else(|| Path::new("."))
.join(filename)
}
pub fn run(options: &SearchOptions) -> Result<()> {
if !matches!(
options.format.as_str(),
"glx" | "pg-copy" | "photon" | "pelias"
) {
return Err(SearchError::UnknownFormat {
format: options.format.clone(),
});
}
tracing::info!(
format = %options.format,
"starting geocoding pipeline"
);
let bbox = options
.bbox
.as_deref()
.map(Bbox::parse)
.transpose()
.map_err(SearchError::InvalidBbox)?;
let admin_scratch = options.tmpdir.clone().unwrap_or_else(std::env::temp_dir);
std::fs::create_dir_all(&admin_scratch).map_err(|source| SearchError::CreateTmpDir {
path: admin_scratch.clone(),
source,
})?;
let area = bbox
.as_ref()
.map(|b| [b.min_lon, b.min_lat, b.max_lon, b.max_lat]);
if options.india_outline.is_none() && geolith::admin::soi_area::touches_soi_land(area) {
return Err(SearchError::IndiaOutlineRequired);
}
let india = options
.india_outline
.as_deref()
.map(crate::india::IndiaOutline::load)
.transpose()?;
let admin_index = load_admin_index(
options.data.as_path(),
bbox.as_ref(),
Some(&admin_scratch),
india.as_ref(),
)?;
let part_count = admin_index.len();
tracing::info!(parts = part_count, "admin hierarchy index ready");
let out_path = options.output.clone();
tracing::info!(path = %out_path.display(), "writing geocoding output");
if options.format == "pg-copy" {
ddl_table_name(&out_path)?;
}
let file = File::create(&out_path).map_err(|source| SearchError::CreateOutput {
path: out_path.clone(),
source,
})?;
let writer = BufWriter::new(file);
let sources = geolith::source::discover(options.data.as_path())?;
let geocoding_sources: Vec<_> = sources
.iter()
.filter(|s| {
matches!(
(s.overture_type.theme, s.overture_type.otype),
("places", "place") | ("addresses", "address")
)
})
.collect();
tracing::info!(
files = geocoding_sources.len(),
"overture places/addresses files discovered"
);
let division_sources: Vec<_> = sources
.iter()
.filter(|s| (s.overture_type.theme, s.overture_type.otype) == ("divisions", "division"))
.collect();
tracing::info!(
files = division_sources.len(),
"overture division point files discovered"
);
match options.format.as_str() {
"glx" => {
let scratch = options
.tmpdir
.clone()
.unwrap_or_else(std::env::temp_dir)
.join(format!("geolith-glx-{}", std::process::id()));
let mut w = GlxWriter::new(writer, &scratch, DEFAULT_SORT_BYTES).map_err(|source| {
SearchError::CreateScratch {
path: scratch.clone(),
source,
}
})?;
emit_records(
options,
&geocoding_sources,
&division_sources,
bbox.as_ref(),
&admin_index,
|record| w.write_record(record),
)?;
let count = w.count();
let runs = w.runs();
let stats = w.finish().map_err(SearchError::WriteGlx)?;
add_credit(&out_path, options.india_outline.is_some())?;
if let Err(e) = std::fs::remove_dir(&scratch) {
tracing::warn!(path = %scratch.display(), error = %e, "could not remove glx scratch directory");
}
tracing::info!(
count,
runs,
terms = stats.terms,
bytes = stats.file_bytes,
"glx file written"
);
}
"photon" => {
let mut w = PhotonWriter::new(writer);
emit_records(
options,
&geocoding_sources,
&division_sources,
bbox.as_ref(),
&admin_index,
|record| w.write_record(record),
)?;
w.flush()?;
tracing::info!(count = w.count(), "photon records written");
}
"pelias" => {
let mut w = PeliasWriter::new(writer, "pelias");
emit_records(
options,
&geocoding_sources,
&division_sources,
bbox.as_ref(),
&admin_index,
|record| w.write_record(record),
)?;
w.flush()?;
tracing::info!(count = w.count(), "pelias records written");
write_pelias_buildings(&sources, bbox.as_ref(), &out_path)?;
}
"pg-copy" => {
let mut w = PgCopyWriter::new(writer).map_err(SearchError::InitPgCopy)?;
emit_records(
options,
&geocoding_sources,
&division_sources,
bbox.as_ref(),
&admin_index,
|record| w.write_record(record),
)?;
w.flush()?;
tracing::info!(count = w.count(), "pg-copy records written");
write_pg_ddl(&out_path, options.pg_index_flavor)?;
}
other => {
return Err(SearchError::UnknownFormat {
format: other.to_owned(),
});
}
}
let bad_points = crate::record::bad_points();
if bad_points > 0 {
tracing::warn!(
records = bad_points,
"records skipped for a point that is not on Earth (NaN, infinite or out of range)"
);
}
Ok(())
}
fn add_credit(path: &Path, india_outline: bool) -> Result<()> {
let sources = geolith::attribution::DataSources::new(true, true, india_outline);
let meta = geolith::attribution::meta_json(
"geolith-search-builder",
env!("CARGO_PKG_VERSION"),
sources,
);
let kind = glx::container::PartKind::Other(geolith::attribution::META_PART_TAG);
glx::parts::append(path, path, kind, |out| out.write_all(&meta)).map_err(|source| {
SearchError::AddCredit {
path: path.to_path_buf(),
source,
}
})?;
Ok(())
}
fn ddl_table_name(out_path: &Path) -> Result<String> {
let Some(stem) = out_path.file_stem().and_then(|stem| stem.to_str()) else {
return Ok("geocoding".to_owned());
};
let mapped: String = stem
.chars()
.map(|c| if c == '-' { '_' } else { c })
.collect();
if mapped.is_empty()
|| !mapped
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_')
{
return Err(SearchError::InvalidTableName {
name: stem.to_owned(),
});
}
Ok(if mapped.starts_with(|c: char| c.is_ascii_digit()) {
format!("t_{mapped}")
} else {
mapped
})
}
fn write_pg_ddl(out_path: &Path, flavor: PgIndexFlavor) -> Result<()> {
let table_name = ddl_table_name(out_path)?;
let ddl_path = out_path.with_extension("sql");
std::fs::write(
&ddl_path,
crate::output::pg_copy::generate_ddl(&table_name, flavor),
)
.map_err(|source| SearchError::WriteDdl {
path: ddl_path.clone(),
source,
})?;
tracing::info!(path = %ddl_path.display(), ?flavor, "geocoding schema written");
Ok(())
}
fn emit_records(
options: &SearchOptions,
sources: &[&geolith::source::SourceFile],
division_sources: &[&geolith::source::SourceFile],
bbox: Option<&Bbox>,
admin_index: &AdminHierarchyIndex,
mut write: impl FnMut(&GeocodingRecord) -> std::io::Result<()>,
) -> Result<()> {
let Some(pbf) = options.osm_pbf.as_deref() else {
emit_overture_records(sources, bbox, admin_index, &mut write)?;
let divisions = DivisionIndex::default();
return emit_division_records(
options,
division_sources,
bbox,
admin_index,
&divisions,
|r| write(&r),
);
};
let mut divisions = DivisionIndex::default();
let mut places = PlaceSignalIndex::default();
for src in division_sources {
read_parquet_file_with_source_id(&src.path, src.overture_type, bbox, |feature| {
divisions.add(&feature);
places.add(&feature);
})
.map_err(|source| SearchError::ReadSource {
path: src.path.clone(),
source,
})?;
}
divisions.seal();
tracing::info!(places = places.len(), "overture settlement signals loaded");
let tmp_dir = options
.tmpdir
.clone()
.unwrap_or_else(|| std::env::temp_dir().join("geolith-geocoding"));
std::fs::create_dir_all(&tmp_dir).map_err(|source| SearchError::CreateTmpDir {
path: tmp_dir.clone(),
source,
})?;
let extract = match bbox {
Some(b) => geolith::source::osmium::try_extract(pbf, b, &tmp_dir)?,
None => geolith::source::osmium::ExtractResult {
pbf_path: pbf.to_path_buf(),
is_extracted: false,
},
};
let mut settlements = load_settlements(&extract.pbf_path)?;
tracing::info!(count = settlements.len(), "osm cities and towns loaded");
let resolving = std::time::Instant::now();
let resolved = settlements.resolve_admin(admin_index);
tracing::info!(
settlements = settlements.len(),
areas = settlements.area_count(),
without_country = resolved.without_country,
without_region = resolved.without_region,
secs = resolving.elapsed().as_secs_f64(),
"settlement countries and regions resolved"
);
let mut spill = OvertureSpill::new(&tmp_dir, bucket_count()).map_err(|source| {
SearchError::CreateDedupBuckets {
dir: tmp_dir.clone(),
source,
}
})?;
emit_overture_records(sources, bbox, admin_index, |record| {
spill.add(record)?;
let mut record = record.clone();
fill_locality(&mut record, &settlements);
write(&record)
})?;
let mut spill = spill.into_osm().map_err(SearchError::StartDedup)?;
let mut direct = 0_u64;
let linked = emit_osm_records(
options,
&extract.pbf_path,
pbf,
&tmp_dir,
bbox,
&Lookups {
admin: admin_index,
places: &places,
},
|mut record| {
if is_deduped(record.layer) && !is_notable(&record) {
return spill.add(&record);
}
divisions.mark(&record);
fill_locality(&mut record, &settlements);
direct += 1;
write(&record)
},
)?;
let stats = spill
.finish(|mut record| {
fill_locality(&mut record, &settlements);
write(&record)
})
.map_err(SearchError::WriteRecord)?;
tracing::info!(
written = direct + stats.kept,
duplicates = stats.duplicates,
"osm geocoding records written"
);
divisions.place_linked(&linked);
emit_division_records(
options,
division_sources,
bbox,
admin_index,
&divisions,
|mut r| {
fill_locality(&mut r, &settlements);
write(&r)
},
)?;
cleanup_extract(&extract);
Ok(())
}
fn emit_division_records(
options: &SearchOptions,
sources: &[&geolith::source::SourceFile],
bbox: Option<&Bbox>,
admin_index: &AdminHierarchyIndex,
written: &DivisionIndex,
mut write: impl FnMut(GeocodingRecord) -> std::io::Result<()>,
) -> Result<()> {
if sources.is_empty() {
return Ok(());
}
let wikipedia = match options.wikimedia_importance.as_deref() {
Some(path) => Wikipedia::load(path)?,
None => Wikipedia::default(),
};
let (mut kept, mut repeats) = (0_u64, 0_u64);
for src in sources {
let mut write_err: Option<std::io::Error> = None;
read_parquet_file_with_source_id(&src.path, src.overture_type, bbox, |feature| {
if write_err.is_some() {
return;
}
let at = written.located(&feature);
let Some(mut record) = division_record(&feature, at, admin_index, &wikipedia) else {
return;
};
if let Some(below) = written.seat_importance(&feature) {
record.importance = record.importance.min(below);
}
if written.written(&feature) {
repeats += 1;
return;
}
match write(record) {
Ok(()) => kept += 1,
Err(e) => write_err = Some(e),
}
})
.map_err(|source| SearchError::ReadSource {
path: src.path.clone(),
source,
})?;
if let Some(e) = write_err {
return Err(SearchError::WriteRecord(e));
}
}
tracing::info!(written = kept, repeats, "overture division points written");
Ok(())
}
fn cleanup_extract(extract: &geolith::source::osmium::ExtractResult) {
if !extract.is_extracted {
return;
}
if let Err(e) = std::fs::remove_file(&extract.pbf_path) {
tracing::warn!(path = %extract.pbf_path.display(), error = %e, "could not remove osm extract");
}
}
fn load_settlements(pbf: &Path) -> Result<SettlementIndex> {
use osmpbf::Element;
type Node = (
i64,
Option<String>,
Option<String>,
Option<String>,
f64,
f64,
);
fn node<'a>(
id: i64,
lon: f64,
lat: f64,
tags: impl Iterator<Item = (&'a str, &'a str)>,
) -> Option<Node> {
let (mut place, mut name, mut postcode) = (None, None, None);
for (k, v) in tags {
match k {
"place" => place = Some(v),
"name" => name = Some(v),
"addr:postcode" => postcode = Some(v),
_ => {}
}
}
let place = place.zip(name);
if place.is_none() && postcode.is_none() {
return None;
}
Some((
id,
place.map(|(p, _)| p.to_string()),
place.map(|(_, n)| n.to_string()),
postcode.map(str::to_string),
lon,
lat,
))
}
let mut found: Vec<Node> = osmpbf::ElementReader::from_path(pbf)
.map_err(|source| SearchError::ReadOsmPbf {
path: pbf.to_path_buf(),
source,
})?
.par_map_reduce(
|element| {
match element {
Element::Node(n) => node(n.id(), n.lon(), n.lat(), n.tags()),
Element::DenseNode(n) => node(n.id(), n.lon(), n.lat(), n.tags()),
_ => None,
}
.into_iter()
.collect::<Vec<_>>()
},
Vec::new,
|mut a, mut b| {
a.append(&mut b);
a
},
)?;
found.sort_unstable_by_key(|n| n.0);
let mut index = SettlementIndex::new();
for (_, place, name, postcode, lon, lat) in &found {
if let (Some(place), Some(name)) = (place, name) {
index.add(place, name, *lon, *lat);
}
if let Some(postcode) = postcode {
index.add_postcode(postcode, *lon, *lat);
}
}
Ok(index)
}
fn way_points(
refs: impl Iterator<Item = i64>,
store: &geolith::source::node_store::NodeStore,
) -> Vec<[f64; 2]> {
refs.filter_map(|id| u64::try_from(id).ok().and_then(|id| store.get(id)))
.map(|(lat, lon)| [lon, lat])
.collect()
}
const fn is_settlement(layer: crate::record::GeocodingLayer) -> bool {
use crate::record::GeocodingLayer as L;
matches!(layer, L::Locality | L::County | L::Region | L::Country)
}
fn takes_boundary_outline(record: &GeocodingRecord, admin_index: &AdminHierarchyIndex) -> bool {
use crate::record::GeocodingLayer as L;
let admin_area = matches!(record.layer, L::Country | L::Region | L::County);
!(admin_area && admin_index.in_soi(record.lon, record.lat))
}
const PROGRESS_ELEMENTS: u64 = 100_000_000;
struct TemporaryFile(std::path::PathBuf);
impl Drop for TemporaryFile {
fn drop(&mut self) {
if let Err(e) = std::fs::remove_file(&self.0)
&& e.kind() != std::io::ErrorKind::NotFound
{
tracing::warn!(path = %self.0.display(), error = %e, "could not remove the temporary node store");
}
}
}
struct Lookups<'a> {
admin: &'a AdminHierarchyIndex,
places: &'a PlaceSignalIndex,
}
fn emit_osm_records(
options: &SearchOptions,
pbf: &Path,
source_pbf: &Path,
tmp_dir: &Path,
bbox: Option<&Bbox>,
lookups: &Lookups<'_>,
mut route: impl FnMut(GeocodingRecord) -> std::io::Result<()>,
) -> Result<std::collections::HashMap<i64, [f64; 2]>> {
use rayon::prelude::*;
let (admin_index, places) = (lookups.admin, lookups.places);
use std::sync::atomic::{AtomicU64, Ordering};
let wikipedia = match options.wikimedia_importance.as_deref() {
Some(path) => Wikipedia::load(path)?,
None => Wikipedia::default(),
};
tracing::info!(items = wikipedia.len(), "wikipedia importance loaded");
let named = options.node_store.as_deref();
let store_path = named.map_or_else(
|| tmp_dir.join("geolith-geocoding-nodes.bin"),
Path::to_path_buf,
);
let _temporary = named.is_none().then(|| TemporaryFile(store_path.clone()));
let (pass1, cached) = geolith::source::osm::pass1_or_cached(
pbf,
source_pbf,
&store_path,
true,
options.reuse_node_cache && named.is_some(),
geolith::source::osm::Relations::Skip,
)?;
tracing::info!(
nodes = pass1.node_stats.nodes_stored,
cached,
"osm geocoding: nodes ready"
);
let relations = crate::areas::load_area_relations(pbf)?;
let wanted: std::collections::HashSet<i64> = relations
.iter()
.flat_map(|r| r.outer.iter().chain(&r.inner).copied())
.collect();
let mut way_store = crate::areas::WayPoints::new(tmp_dir)?;
tracing::info!(
relations = relations.len(),
ways = wanted.len(),
"osm area relations loaded"
);
let mut deferred = crate::dedup::RecordSpill::new(tmp_dir)?;
let mut settlements: Vec<crate::areas::Settlement> = Vec::new();
let elements = AtomicU64::new(0);
type Found = (GeocodingRecord, Option<(i64, Option<String>, bool)>);
type Batch = (Vec<Found>, Vec<(i64, Vec<[f64; 2]>)>);
let to_records = |blob: osmpbf::Blob| -> Result<Batch> {
let osmpbf::BlobDecode::OsmData(block) = blob.decode()? else {
return Ok((Vec::new(), Vec::new()));
};
let mut records = Vec::new();
let mut ways = Vec::new();
for element in block.elements() {
elements.fetch_add(1, Ordering::Relaxed);
if let osmpbf::Element::Way(way) = &element
&& wanted.contains(&way.id())
{
let points = way_points(way.refs(), &pass1.store);
if !points.is_empty() {
ways.push((way.id(), points));
}
}
let tags_pass = match &element {
osmpbf::Element::DenseNode(n) => may_be_record(n.tags()),
osmpbf::Element::Node(n) => may_be_record(n.tags()),
osmpbf::Element::Way(w) => may_be_record(w.tags()),
osmpbf::Element::Relation(r) => may_be_record(r.tags()),
};
if !tags_pass {
continue;
}
let Some(feature) = geolith::source::osm::element_to_feature(
element,
&pass1.store,
&pass1.way_to_relations,
false,
) else {
continue;
};
let Some(record) = osm_record_with(&feature, admin_index, &wikipedia, places) else {
continue;
};
if bbox.is_none_or(|b| b.contains_point(record.lon, record.lat)) {
let node = matches!(
feature.source,
geolith::source::input::DataSource::Osm {
element_type: geolith::source::input::OsmElementType::Node,
..
}
)
.then(|| {
let wikidata = match feature.properties.get("wikidata") {
Some(geolith::tile::feature::PropValue::Str(item)) => {
Some(item.to_string())
}
_ => None,
};
let counted = matches!(
feature.properties.get("place"),
Some(geolith::tile::feature::PropValue::Str(kind))
if matches!(kind.as_ref(), "city" | "town" | "village")
);
(
i64::try_from(feature.id).unwrap_or(i64::MAX),
wikidata,
counted,
)
});
let twin = address_twin(&record);
records.push((record, node));
if let Some(twin) = twin {
records.push((twin, None));
}
}
}
Ok((records, ways))
};
let batch_len = rayon::current_num_threads().max(1) * 8;
let (mut routed, mut logged) = (0_u64, 0_u64);
let mut blobs = osmpbf::BlobReader::from_path(pbf)
.map_err(|source| SearchError::ReadOsmPbf {
path: pbf.to_path_buf(),
source,
})?
.peekable();
while blobs.peek().is_some() {
let batch: Vec<_> = blobs.by_ref().take(batch_len).collect();
let records: Vec<Result<Batch>> = batch
.into_par_iter()
.map(|blob| to_records(blob?))
.collect();
for batch in records {
let (records, ways) = batch?;
for (record, node) in records {
if let Some((node, wikidata, counted)) = node
&& record.shape.is_empty()
&& is_settlement(record.layer)
{
settlements.push(crate::areas::Settlement {
record: record.id,
node,
layer: record.layer,
point: [record.lon, record.lat],
wikidata,
names: record
.all_names()
.into_iter()
.map(crate::areas::name_hash)
.collect(),
counted,
});
deferred.add(&record)?;
continue;
}
route(record).map_err(SearchError::WriteRecord)?;
routed += 1;
}
for (id, points) in ways {
way_store.add(id, &points)?;
}
}
let seen = elements.load(Ordering::Relaxed);
if seen / PROGRESS_ELEMENTS > logged {
logged = seen / PROGRESS_ELEMENTS;
tracing::info!(elements = seen, records = routed, "osm geocoding pass");
}
}
pass1
.store
.check_reads()
.map_err(|e| e.context(format!("node store {}", store_path.display())))?;
way_store.finish()?;
let way_file = way_store.open()?;
let mut boundaries = Vec::new();
let (wanted_nodes, wanted_items, wanted_names) = {
let nodes: std::collections::HashSet<i64> = settlements.iter().map(|s| s.node).collect();
let items: std::collections::HashSet<&str> = settlements
.iter()
.filter_map(|s| s.wikidata.as_deref())
.collect();
let names: std::collections::HashSet<u64> = settlements
.iter()
.flat_map(|s| s.names.iter().copied())
.collect();
(nodes, items, names)
};
for relation in &relations {
if let crate::areas::AreaKind::Boundary(_) = relation.kind {
let may_link = relation.label.is_some_and(|n| wanted_nodes.contains(&n))
|| relation
.tags
.get("wikidata")
.is_some_and(|item| wanted_items.contains(item.as_str()))
|| ["name", "name:en", "official_name", "alt_name", "short_name"]
.iter()
.filter_map(|key| relation.tags.get(*key))
.flat_map(|value| value.split(';'))
.any(|name| wanted_names.contains(&crate::areas::name_hash(name)));
if may_link {
let polygons = crate::rings::polygons(
way_store.read(&way_file, &relation.outer)?,
way_store.read(&way_file, &relation.inner)?,
);
if !polygons.is_empty() {
boundaries.push((relation, polygons));
}
}
continue;
}
let outer = way_store.read(&way_file, &relation.outer)?;
let Some([w, s, e, n]) = outer
.iter()
.flatten()
.fold(None, |acc: Option<[f64; 4]>, p| {
Some(match acc {
None => [p[0], p[1], p[0], p[1]],
Some([w, s, e, n]) => [w.min(p[0]), s.min(p[1]), e.max(p[0]), n.max(p[1])],
})
})
else {
continue;
};
let polygons = crate::rings::polygons(outer, way_store.read(&way_file, &relation.inner)?);
let feature = geolith::source::input::InputFeature {
id: relation.id.unsigned_abs(),
geometry: std::sync::Arc::new(geo::Geometry::Point(geo::Point::new(
f64::midpoint(w, e),
f64::midpoint(s, n),
))),
properties: geolith::source::osm::tags_to_properties(&relation.tags),
bbox: None,
source: geolith::source::input::DataSource::Osm {
element_type: geolith::source::input::OsmElementType::Relation,
relations: Vec::new(),
},
};
let Some(mut record) = osm_record_with(&feature, admin_index, &wikipedia, places) else {
continue;
};
record.shape = crate::shape::from_rings(&polygons, crate::shape::VENUE_TOLERANCE);
if bbox.is_none_or(|b| b.contains_point(record.lon, record.lat)) {
let twin = address_twin(&record);
route(record).map_err(SearchError::WriteRecord)?;
routed += 1;
if let Some(twin) = twin {
route(twin).map_err(SearchError::WriteRecord)?;
routed += 1;
}
}
}
let mut links = crate::areas::link_boundaries(&settlements, &boundaries);
let points = crate::areas::linked_points(&settlements, &boundaries);
tracing::info!(
settlements = settlements.len(),
boundaries = boundaries.len(),
linked = links.len(),
"osm boundary outlines linked"
);
drop(boundaries);
drop(settlements);
deferred
.drain(|mut record| {
if let Some(polygons) = links.remove(&record.id)
&& takes_boundary_outline(&record, admin_index)
{
record.shape = crate::shape::from_rings(&polygons, crate::shape::AREA_TOLERANCE);
}
routed += 1;
route(record)
})
.map_err(SearchError::WriteRecord)?;
tracing::info!(
elements = elements.load(Ordering::Relaxed),
records = routed,
"osm geocoding pass done"
);
Ok(points)
}
fn emit_overture_records(
sources: &[&geolith::source::SourceFile],
bbox: Option<&Bbox>,
admin_index: &AdminHierarchyIndex,
mut write: impl FnMut(&GeocodingRecord) -> std::io::Result<()>,
) -> Result<()> {
let mut written = 0_u64;
for (done, src) in sources.iter().enumerate() {
tracing::info!(
file = done + 1,
files = sources.len(),
records = written,
"overture geocoding pass"
);
let is_place = src.overture_type.theme == "places";
let mut write_err: Option<std::io::Error> = None;
read_parquet_file_with_source_id(&src.path, src.overture_type, bbox, |feature| {
if write_err.is_some() {
return;
}
let record = if is_place {
overture_place_record(&feature, admin_index)
} else {
overture_address_record(&feature, admin_index)
};
if let Some(record) = record {
match write(&record) {
Ok(()) => written += 1,
Err(e) => write_err = Some(e),
}
}
})
.map_err(|source| SearchError::ReadSource {
path: src.path.clone(),
source,
})?;
if let Some(e) = write_err {
return Err(SearchError::WriteRecord(e));
}
}
Ok(())
}
fn write_pelias_buildings(
sources: &[geolith::source::SourceFile],
bbox: Option<&Bbox>,
places_out: &Path,
) -> Result<()> {
let building_sources: Vec<_> = sources
.iter()
.filter(|s| s.overture_type.theme == "buildings")
.collect();
if building_sources.is_empty() {
tracing::info!("no overture buildings files found — skipping buildings output");
return Ok(());
}
let stem = places_out
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("geocoding");
let out_path = places_out
.parent()
.unwrap_or_else(|| Path::new("."))
.join(format!("{stem}-buildings.ndjson"));
tracing::info!(path = %out_path.display(), files = building_sources.len(), "writing buildings output");
let file = File::create(&out_path).map_err(|source| SearchError::CreateBuildingsOutput {
path: out_path.clone(),
source,
})?;
let mut w = OvertureBuildingsWriter::new(BufWriter::new(file), "overture-buildings");
for src in &building_sources {
let mut write_err: Option<std::io::Error> = None;
read_parquet_file_with_source_id(&src.path, src.overture_type, bbox, |feature| {
if write_err.is_some() {
return;
}
if let Err(e) = w.write_feature(&feature) {
write_err = Some(e);
}
})
.map_err(|source| SearchError::ReadSource {
path: src.path.clone(),
source,
})?;
if let Some(e) = write_err {
return Err(SearchError::WriteBuildingDocument(e));
}
}
w.flush()?;
tracing::info!(count = w.count(), "building documents written");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
#[test]
fn cleanup_extract_removes_only_extracted_pbfs() {
let tmp = tempfile::tempdir().expect("tmp");
let extracted = tmp.path().join("extracted.osm.pbf");
std::fs::write(&extracted, b"pbf").expect("write");
cleanup_extract(&geolith::source::osmium::ExtractResult {
pbf_path: extracted.clone(),
is_extracted: true,
});
assert!(!extracted.exists(), "the extract must be removed");
let original = tmp.path().join("original.osm.pbf");
std::fs::write(&original, b"pbf").expect("write");
cleanup_extract(&geolith::source::osmium::ExtractResult {
pbf_path: original.clone(),
is_extracted: false,
});
assert!(original.exists(), "the input pbf must never be removed");
cleanup_extract(&geolith::source::osmium::ExtractResult {
pbf_path: tmp.path().join("gone.osm.pbf"),
is_extracted: true,
});
}
#[test]
fn load_settlements_reads_plain_and_dense_nodes() {
use osmpbf::Element;
let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
let dense = load_settlements(&dir.join("geocoding.osm.pbf")).expect("dense nodes");
let plain = load_settlements(&dir.join("geocoding-plain.osm.pbf")).expect("plain nodes");
assert_eq!(dense.nearest(-122.4194, 37.7749), Some("San Francisco"));
assert_eq!(dense.nearest(-73.9857, 40.7484), Some("New York"));
assert_eq!(plain.nearest(77.5946, 12.9716), Some("Bengaluru"));
let mut saw_plain_node = false;
osmpbf::ElementReader::from_path(dir.join("geocoding-plain.osm.pbf"))
.expect("read")
.for_each(|element| {
saw_plain_node |= matches!(element, Element::Node(_));
})
.expect("scan");
assert!(saw_plain_node, "the plain fixture must not use dense nodes");
}
#[test]
fn a_node_cache_from_one_run_serves_the_next() {
use crate::admin::AdminHierarchyBuilder;
let tmp = tempfile::tempdir().expect("tmp");
let pbf = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/geocoding.osm.pbf");
let store = tmp.path().join("nodes.bin");
let mut options = SearchOptions::new("/data", "/out.tsv");
options.osm_pbf = Some(pbf.clone());
options.node_store = Some(store.clone());
options.reuse_node_cache = true;
let admin = AdminHierarchyBuilder::new().build().unwrap();
let run = || {
let mut names = Vec::new();
emit_osm_records(
&options,
&pbf,
&pbf,
tmp.path(),
None,
&Lookups {
admin: &admin,
places: &PlaceSignalIndex::default(),
},
|r| {
names.push(r.name);
Ok(())
},
)
.expect("osm pass");
names
};
let first = run();
let meta = geolith::source::node_store::meta_path(&store);
assert!(meta.exists(), "the first run records the cache");
let (_, cached) = geolith::source::osm::pass1_or_cached(
&pbf,
&pbf,
&store,
true,
true,
geolith::source::osm::Relations::Skip,
)
.expect("cache");
assert!(cached, "a matching store is reused");
assert_eq!(run(), first, "the cached nodes give the same records");
assert!(first.iter().any(|n| n == "New York"), "{first:?}");
}
#[test]
fn venue_relations_keep_named_venue_multipolygons_and_their_outer_ways() {
let pbf =
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/relation-venues.osm.pbf");
let found = crate::areas::load_area_relations(&pbf).expect("relations");
let kept: Vec<(i64, Vec<i64>, Vec<i64>)> = found
.iter()
.map(|r| (r.id, r.outer.clone(), r.inner.clone()))
.collect();
assert_eq!(kept, [(100, vec![10], vec![12]), (300, vec![99], vec![])]);
}
#[test]
fn a_named_venue_multipolygon_becomes_a_record() {
use crate::admin::AdminHierarchyBuilder;
let tmp = tempfile::tempdir().expect("tmp");
let pbf =
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/relation-venues.osm.pbf");
let mut options = SearchOptions::new("/data", "/out.tsv");
options.osm_pbf = Some(pbf.clone());
let admin = AdminHierarchyBuilder::new().build().unwrap();
let mut records = Vec::new();
emit_osm_records(
&options,
&pbf,
&pbf,
tmp.path(),
None,
&Lookups {
admin: &admin,
places: &PlaceSignalIndex::default(),
},
|r| {
records.push(r);
Ok(())
},
)
.expect("osm pass");
let names: Vec<&str> = records.iter().map(|r| r.name.as_str()).collect();
assert_eq!(names, ["東京タワー"]);
let tower = &records[0];
assert_eq!(tower.source_id.as_deref(), Some("relation/100"));
assert_eq!(tower.categories, ["attraction"]);
assert_eq!(tower.search_text, "東京タワー Tokyo Tower attraction");
assert!((tower.lon - 139.745).abs() < 1e-9, "{}", tower.lon);
assert!((tower.lat - 35.6585).abs() < 1e-9, "{}", tower.lat);
assert_eq!(
glx::format::decode_shape(&tower.shape),
Some(vec![vec![vec![
[139.744, 35.658],
[139.746, 35.658],
[139.746, 35.659],
[139.744, 35.659],
[139.744, 35.658],
]]])
);
}
#[test]
fn settlements_take_their_boundary_outlines() {
use crate::admin::AdminHierarchyBuilder;
let tmp = tempfile::tempdir().expect("tmp");
let pbf = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/boundaries.osm.pbf");
let mut options = SearchOptions::new("/data", "/out.tsv");
options.osm_pbf = Some(pbf.clone());
let admin = AdminHierarchyBuilder::new().build().unwrap();
let mut records = Vec::new();
emit_osm_records(
&options,
&pbf,
&pbf,
tmp.path(),
None,
&Lookups {
admin: &admin,
places: &PlaceSignalIndex::default(),
},
|r| {
records.push(r);
Ok(())
},
)
.expect("osm pass");
let mut names: Vec<&str> = records.iter().map(|r| r.name.as_str()).collect();
names.sort_unstable();
assert_eq!(names, ["Chennai", "Labelled Town", "Pune"]);
let shape = |name: &str| {
records
.iter()
.find(|r| r.name == name)
.map(|r| glx::format::decode_shape(&r.shape))
};
assert_eq!(
shape("Chennai"),
Some(Some(vec![vec![vec![
[80.0, 13.0],
[80.4, 13.0],
[80.4, 13.3],
[80.0, 13.3],
[80.0, 13.0],
]]]))
);
assert_eq!(
shape("Labelled Town"),
Some(Some(vec![vec![vec![
[76.0, 10.0],
[76.1, 10.0],
[76.1, 10.1],
[76.0, 10.0],
]]]))
);
assert_eq!(
records
.iter()
.find(|r| r.name == "Pune")
.map(|r| r.shape.len()),
Some(0)
);
assert!(!tmp.path().join("osm-deferred.bin").exists());
}
#[test]
fn an_osm_boundary_never_outlines_an_admin_area_on_soi_land() {
use crate::admin::AdminHierarchyBuilder;
use crate::admin::india::{IndiaOutline, IndiaView};
let square = |x0: f64, y0: f64, x1: f64, y1: f64| {
geo::Polygon::new(
geo::LineString::from(vec![(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)]),
vec![],
)
};
let outline = IndiaOutline::new(geo::MultiPolygon(vec![square(73.0, 35.0, 77.0, 37.0)]))
.expect("outline");
let mut builder = AdminHierarchyBuilder::new();
IndiaView::new(&outline)
.finish_into(&mut builder)
.expect("india");
let admin = builder.build().expect("index");
let tmp = tempfile::tempdir().expect("tmp");
let pbf =
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/soi-boundaries.osm.pbf");
let mut options = SearchOptions::new("/data", "/out.tsv");
options.osm_pbf = Some(pbf.clone());
let mut records = Vec::new();
emit_osm_records(
&options,
&pbf,
&pbf,
tmp.path(),
None,
&Lookups {
admin: &admin,
places: &PlaceSignalIndex::default(),
},
|r| {
records.push(r);
Ok(())
},
)
.expect("osm pass");
let shape_len = |name: &str| {
records
.iter()
.find(|r| r.name == name)
.map(|r| r.shape.len())
};
assert_eq!(
shape_len("Gilgit-Baltistan"),
Some(0),
"no OSM outline on SOI land"
);
assert!(
shape_len("Gilgit").is_some_and(|n| n > 0),
"a town keeps its outline"
);
assert!(
shape_len("Control Province").is_some_and(|n| n > 0),
"off SOI land the link is unchanged"
);
}
#[test]
fn a_node_store_in_the_temporary_directory_is_removed_after_the_osm_pass() {
use crate::admin::AdminHierarchyBuilder;
let tmp = tempfile::tempdir().expect("tmp");
let pbf = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/geocoding.osm.pbf");
let mut options = SearchOptions::new("/data", "/out.tsv");
options.osm_pbf = Some(pbf.clone());
let admin = AdminHierarchyBuilder::new().build().unwrap();
let mut names = Vec::new();
emit_osm_records(
&options,
&pbf,
&pbf,
tmp.path(),
None,
&Lookups {
admin: &admin,
places: &PlaceSignalIndex::default(),
},
|r| {
names.push(r.name);
Ok(())
},
)
.expect("osm pass");
assert!(names.iter().any(|n| n == "New York"), "{names:?}");
let left: Vec<_> = std::fs::read_dir(tmp.path()).expect("dir").collect();
assert!(left.is_empty(), "files left: {left:?}");
}
fn logged(dir: &Path, f: impl FnOnce()) -> String {
let path = dir.join("log.txt");
let file = std::sync::Arc::new(std::fs::File::create(&path).expect("log file"));
let subscriber = tracing_subscriber::fmt()
.with_writer(file)
.with_ansi(false)
.finish();
tracing::subscriber::with_default(subscriber, f);
std::fs::read_to_string(&path).expect("log")
}
#[test]
fn a_temporary_node_store_that_cannot_be_removed_is_reported() {
let tmp = tempfile::tempdir().expect("tmp");
let store = tmp.path().join("nodes.bin");
std::fs::create_dir(&store).expect("dir");
let log = logged(tmp.path(), || drop(TemporaryFile(store.clone())));
assert!(
log.contains("could not remove the temporary node store"),
"{log}"
);
assert!(store.is_dir(), "a directory is never removed");
let missing = tmp.path().join("missing.bin");
let log = logged(tmp.path(), || drop(TemporaryFile(missing)));
assert!(!log.contains("could not remove"), "{log}");
}
#[test]
fn emit_osm_records_fails_when_the_writer_or_the_pbf_fails() {
use crate::admin::AdminHierarchyBuilder;
let tmp = tempfile::tempdir().expect("tmp");
let pbf = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/geocoding.osm.pbf");
let mut options = SearchOptions::new("/data", "/out.tsv");
options.osm_pbf = Some(pbf.clone());
let admin = AdminHierarchyBuilder::new().build().unwrap();
let failing =
|_: GeocodingRecord| -> std::io::Result<()> { Err(std::io::Error::other("boom")) };
let err = emit_osm_records(
&options,
&pbf,
&pbf,
tmp.path(),
None,
&Lookups {
admin: &admin,
places: &PlaceSignalIndex::default(),
},
failing,
)
.expect_err("a failing writer must fail the run");
assert!(
geolith::error::report(&err).contains("failed to write geocoding record"),
"{err:#}"
);
let missing = tmp.path().join("missing.osm.pbf");
let err = emit_osm_records(
&options,
&missing,
&missing,
tmp.path(),
None,
&Lookups {
admin: &admin,
places: &PlaceSignalIndex::default(),
},
failing,
)
.expect_err("a missing PBF must fail the run");
assert!(
geolith::error::report(&err).contains("os error 2"),
"{err:#}"
);
}
#[test]
fn default_output_pg_copy_uses_tsv_extension() {
let out = default_geocoding_output(Path::new("/data/planet.pmtiles"), "pg-copy");
assert_eq!(out, PathBuf::from("/data/planet.tsv"));
}
#[test]
fn ddl_table_name_follows_the_output_file_stem() {
assert_eq!(
ddl_table_name(Path::new("/data/places.tsv")).unwrap(),
"places"
);
assert_eq!(
ddl_table_name(Path::new("geocoding.tsv")).unwrap(),
"geocoding"
);
}
#[test]
fn ddl_table_name_is_a_plain_sql_identifier() {
assert_eq!(
ddl_table_name(Path::new("/out/planet-geocoding.tsv")).unwrap(),
"planet_geocoding"
);
assert_eq!(
ddl_table_name(Path::new("2026-planet.tsv")).unwrap(),
"t_2026_planet"
);
for hostile in [
"x; DROP TABLE y.tsv",
"a b.tsv",
"places\"; --.tsv",
"a'b.tsv",
"é.tsv",
"a(b).tsv",
] {
let error = ddl_table_name(Path::new(hostile)).expect_err(hostile);
assert!(
matches!(error, SearchError::InvalidTableName { .. }),
"{hostile}: {error}"
);
}
}
#[test]
fn a_hostile_output_name_writes_no_sql() {
let dir = tempfile::tempdir().expect("tmp");
let out = dir.path().join("x; DROP TABLE y.tsv");
assert!(write_pg_ddl(&out, PgIndexFlavor::Tin).is_err());
assert!(
std::fs::read_dir(dir.path()).expect("dir").next().is_none(),
"no .sql file is written"
);
}
#[test]
fn a_hyphenated_output_name_gives_a_valid_schema() {
let dir = tempfile::tempdir().expect("tmp");
let out = dir.path().join("planet-geocoding.tsv");
write_pg_ddl(&out, PgIndexFlavor::Tin).expect("ddl");
let sql = std::fs::read_to_string(dir.path().join("planet-geocoding.sql")).expect("sql");
assert!(
sql.contains("CREATE TABLE IF NOT EXISTS planet_geocoding ("),
"{sql}"
);
assert!(!sql.contains("planet-geocoding"), "{sql}");
}
#[test]
fn ddl_table_name_falls_back_when_the_path_has_no_stem() {
assert_eq!(ddl_table_name(Path::new("/")).unwrap(), "geocoding");
assert_eq!(ddl_table_name(Path::new("..")).unwrap(), "geocoding");
}
#[cfg(unix)]
#[test]
fn ddl_table_name_falls_back_when_the_stem_is_not_utf8() {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
let path = Path::new(OsStr::from_bytes(b"/data/\xff\xfe.tsv"));
assert_eq!(ddl_table_name(path).unwrap(), "geocoding");
}
#[test]
fn default_output_pelias_uses_ndjson_extension() {
for format in ["pelias", "photon"] {
let out = default_geocoding_output(Path::new("/data/planet.pmtiles"), format);
assert_eq!(out, PathBuf::from("/data/planet.ndjson"), "{format}");
}
}
#[test]
fn default_output_unknown_format_uses_tsv() {
let out = default_geocoding_output(Path::new("/data/out.pmtiles"), "unknown");
assert_eq!(out, PathBuf::from("/data/out.tsv"));
}
}