use std::collections::HashMap;
use std::fs::File;
use std::io::{self, BufReader, BufWriter, Read, Write};
use std::path::{Path, PathBuf};
use h3o::{CellIndex, LatLng, Resolution};
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use crate::osm::{OvertureIndex, OvertureIndexBuilder};
use crate::record::{AddressFields, GeocodingLayer, GeocodingRecord};
use geolith::admin::AdminHierarchy;
use geolith::conflation::spatial::{SpatialCandidate, SpatialDedupConfig};
use geolith::source::input::{DataSource, OsmElementType};
const BUCKET_RESOLUTION: Resolution = Resolution::Four;
const MAX_BUCKETS: usize = 1024;
const MIN_BUCKETS: usize = 16;
const RESERVED_FILES: u64 = 64;
const BUCKET_BUFFER: usize = 32 * 1024;
const CHECK_BATCH: usize = 8 * 1024;
#[must_use]
pub const fn is_deduped(layer: GeocodingLayer) -> bool {
matches!(layer, GeocodingLayer::Venue | GeocodingLayer::Address)
}
#[must_use]
pub fn bucket_count() -> usize {
let files = raise_open_file_limit(MAX_BUCKETS as u64 + RESERVED_FILES);
let usable = usize::try_from(files.saturating_sub(RESERVED_FILES)).unwrap_or(MAX_BUCKETS);
usable.clamp(MIN_BUCKETS, MAX_BUCKETS)
}
#[cfg(unix)]
#[allow(
unsafe_code,
reason = "libc getrlimit and setrlimit on local structs; each unsafe block has a SAFETY comment"
)]
fn raise_open_file_limit(want: u64) -> u64 {
let mut limit = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &raw mut limit) } != 0 {
return 256;
}
let want = want.min(limit.rlim_max);
if limit.rlim_cur < want {
let raised = libc::rlimit {
rlim_cur: want,
rlim_max: limit.rlim_max,
};
if unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &raw const raised) } == 0 {
return want;
}
}
limit.rlim_cur
}
#[cfg(not(unix))]
fn raise_open_file_limit(_want: u64) -> u64 {
512
}
fn dedup_cell(lon: f64, lat: f64) -> CellIndex {
let resolution = Resolution::try_from(SpatialDedupConfig::default().h3_resolution)
.unwrap_or(Resolution::Eight);
let origin = || LatLng::new(0.0, 0.0).map(|p| p.to_cell(resolution));
LatLng::new(lat, lon)
.map(|p| p.to_cell(resolution))
.or_else(|_| origin())
.unwrap_or_else(|_| unreachable!("the origin is a valid point"))
}
fn bucket_of(cell: CellIndex, buckets: usize) -> usize {
let coarse = cell.parent(BUCKET_RESOLUTION).unwrap_or(cell);
let spread = u64::from(coarse).wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 32;
usize::try_from(spread).unwrap_or(0) % buckets
}
fn osm_bucket(lon: f64, lat: f64, buckets: usize) -> usize {
bucket_of(dedup_cell(lon, lat), buckets)
}
fn overture_buckets(lon: f64, lat: f64, buckets: usize) -> Vec<usize> {
let mut out: Vec<usize> = dedup_cell(lon, lat)
.grid_disk::<Vec<_>>(1)
.into_iter()
.map(|cell| bucket_of(cell, buckets))
.collect();
out.sort_unstable();
out.dedup();
out
}
#[derive(Serialize, Deserialize)]
struct OvertureKey {
venue: bool,
id: u64,
lon: f64,
lat: f64,
name: String,
}
#[derive(Serialize, Deserialize)]
struct OsmRow {
id: u64,
element_type: OsmElementType,
layer: GeocodingLayer,
name: String,
search_text: String,
lon: f64,
lat: f64,
country_code: Option<String>,
admin: AdminHierarchy,
address: Option<AddressFields>,
names: HashMap<String, String>,
other_names: Vec<String>,
article_names: Vec<String>,
importance: f32,
source_id: Option<String>,
categories: Vec<String>,
addendum: Vec<(String, String)>,
shape: Vec<u8>,
}
impl OsmRow {
fn new(record: &GeocodingRecord) -> io::Result<Self> {
let DataSource::Osm { element_type, .. } = record.source else {
return Err(io::Error::other("an OSM spill only takes OSM records"));
};
let addendum = record
.addendum
.iter()
.map(|(k, v)| Ok((k.clone(), serde_json::to_string(v)?)))
.collect::<io::Result<_>>()?;
Ok(Self {
id: record.id,
element_type,
layer: record.layer,
name: record.name.clone(),
search_text: record.search_text.clone(),
lon: record.lon,
lat: record.lat,
country_code: record.country_code.clone(),
admin: record.admin.clone(),
address: record.address.clone(),
names: record.names.clone(),
other_names: record.other_names.clone(),
article_names: record.article_names.clone(),
importance: record.importance,
source_id: record.source_id.clone(),
categories: record.categories.clone(),
addendum,
shape: record.shape.clone(),
})
}
fn into_record(self) -> io::Result<GeocodingRecord> {
let addendum = self
.addendum
.into_iter()
.map(|(k, v)| Ok((k, serde_json::from_str(&v)?)))
.collect::<io::Result<_>>()?;
Ok(GeocodingRecord {
id: self.id,
source: DataSource::Osm {
element_type: self.element_type,
relations: Vec::new(),
},
layer: self.layer,
name: self.name,
search_text: self.search_text,
lon: self.lon,
lat: self.lat,
country_code: self.country_code,
admin: self.admin,
address: self.address,
names: self.names,
other_names: self.other_names,
article_names: self.article_names,
importance: self.importance,
source_id: self.source_id,
categories: self.categories,
addendum,
shape: self.shape,
})
}
}
fn put<T: Serialize>(
out: &mut BufWriter<File>,
value: &T,
scratch: &mut Vec<u8>,
) -> io::Result<()> {
scratch.clear();
let bytes = postcard::to_extend(value, std::mem::take(scratch)).map_err(io::Error::other)?;
let len = u32::try_from(bytes.len()).map_err(io::Error::other)?;
out.write_all(&len.to_le_bytes())?;
out.write_all(&bytes)?;
*scratch = bytes;
Ok(())
}
fn each(path: &Path, mut f: impl FnMut(&[u8]) -> io::Result<()>) -> io::Result<()> {
let mut input = BufReader::new(File::open(path)?);
let mut len = [0_u8; 4];
let mut bytes = Vec::new();
loop {
match input.read_exact(&mut len) {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(()),
Err(e) => return Err(e),
}
bytes.resize(u32::from_le_bytes(len) as usize, 0);
input.read_exact(&mut bytes)?;
f(&bytes)?;
}
}
pub struct RecordSpill {
path: PathBuf,
out: BufWriter<File>,
scratch: Vec<u8>,
added: u64,
}
impl RecordSpill {
pub fn new(dir: &Path) -> io::Result<Self> {
let path = dir.join("osm-deferred.bin");
Ok(Self {
out: BufWriter::new(File::create(&path)?),
path,
scratch: Vec::new(),
added: 0,
})
}
pub fn add(&mut self, record: &GeocodingRecord) -> io::Result<()> {
put(&mut self.out, &OsmRow::new(record)?, &mut self.scratch)?;
self.added += 1;
Ok(())
}
pub fn drain(self, mut f: impl FnMut(GeocodingRecord) -> io::Result<()>) -> io::Result<()> {
let Self { path, out, .. } = self;
out.into_inner()
.map_err(io::IntoInnerError::into_error)?
.sync_all()?;
each(&path, |bytes| f(decode::<OsmRow>(bytes)?.into_record()?))?;
std::fs::remove_file(&path)
}
}
fn decode<T: for<'de> Deserialize<'de>>(bytes: &[u8]) -> io::Result<T> {
postcard::from_bytes(bytes).map_err(io::Error::other)
}
fn check(
index: &OvertureIndex,
batch: &mut Vec<Vec<u8>>,
stats: &mut DedupStats,
keep: &mut impl FnMut(GeocodingRecord) -> io::Result<()>,
) -> io::Result<()> {
let checked: Vec<io::Result<Option<GeocodingRecord>>> = batch
.par_drain(..)
.map(|bytes| {
let record = decode::<OsmRow>(&bytes)?.into_record()?;
Ok((!index.is_duplicate(&record)).then_some(record))
})
.collect();
for record in checked {
match record? {
Some(record) => {
stats.kept += 1;
keep(record)?;
}
None => stats.duplicates += 1,
}
}
Ok(())
}
fn create_buckets(dir: &Path, side: &str, buckets: usize) -> io::Result<Vec<BufWriter<File>>> {
(0..buckets)
.map(|i| {
let file = File::create(dir.join(format!("{side}-{i:04}")))?;
Ok(BufWriter::with_capacity(BUCKET_BUFFER, file))
})
.collect()
}
fn close(files: Vec<BufWriter<File>>) -> io::Result<()> {
for file in files {
file.into_inner().map_err(io::IntoInnerError::into_error)?;
}
Ok(())
}
struct Dir(PathBuf);
impl Drop for Dir {
fn drop(&mut self) {
if let Err(e) = std::fs::remove_dir_all(&self.0) {
tracing::warn!(path = %self.0.display(), error = %e, "could not remove dedup buckets");
}
}
}
pub struct OvertureSpill {
dir: Dir,
buckets: usize,
files: Vec<BufWriter<File>>,
scratch: Vec<u8>,
added: u64,
}
impl OvertureSpill {
pub fn new(tmp: &Path, buckets: usize) -> io::Result<Self> {
let path = tmp.join(format!("geolith-dedup-{}", std::process::id()));
std::fs::create_dir_all(&path)?;
let dir = Dir(path);
let files = create_buckets(&dir.0, "overture", buckets)?;
Ok(Self {
dir,
buckets,
files,
scratch: Vec::with_capacity(256),
added: 0,
})
}
pub fn add(&mut self, record: &GeocodingRecord) -> io::Result<()> {
if !is_deduped(record.layer) {
return Ok(());
}
let key = OvertureKey {
venue: record.layer == GeocodingLayer::Venue,
id: record.id,
lon: record.lon,
lat: record.lat,
name: record.name.clone(),
};
for bucket in overture_buckets(record.lon, record.lat, self.buckets) {
put(&mut self.files[bucket], &key, &mut self.scratch)?;
}
self.added += 1;
Ok(())
}
pub fn into_osm(self) -> io::Result<OsmSpill> {
let Self {
dir,
buckets,
files,
scratch,
added,
} = self;
close(files)?;
tracing::info!(overture = added, buckets, "overture dedup records on disk");
let files = create_buckets(&dir.0, "osm", buckets)?;
Ok(OsmSpill {
dir,
buckets,
files,
scratch,
added: 0,
})
}
}
pub struct OsmSpill {
dir: Dir,
buckets: usize,
files: Vec<BufWriter<File>>,
scratch: Vec<u8>,
added: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DedupStats {
pub kept: u64,
pub duplicates: u64,
}
impl OsmSpill {
pub fn add(&mut self, record: &GeocodingRecord) -> io::Result<()> {
let bucket = osm_bucket(record.lon, record.lat, self.buckets);
put(
&mut self.files[bucket],
&OsmRow::new(record)?,
&mut self.scratch,
)?;
self.added += 1;
Ok(())
}
pub fn finish(
self,
mut keep: impl FnMut(GeocodingRecord) -> io::Result<()>,
) -> io::Result<DedupStats> {
let Self {
dir,
buckets,
files,
added,
..
} = self;
close(files)?;
tracing::info!(osm = added, buckets, "osm dedup records on disk");
let mut stats = DedupStats {
kept: 0,
duplicates: 0,
};
let mut batch = Vec::with_capacity(CHECK_BATCH);
for bucket in 0..buckets {
let overture_path = dir.0.join(format!("overture-{bucket:04}"));
let osm_path = dir.0.join(format!("osm-{bucket:04}"));
let mut overture = OvertureIndexBuilder::default();
each(&overture_path, |bytes| {
let key: OvertureKey = decode(bytes)?;
let layer = if key.venue {
GeocodingLayer::Venue
} else {
GeocodingLayer::Address
};
overture.add_candidate(
layer,
SpatialCandidate {
id: key.id,
centroid_lon: key.lon,
centroid_lat: key.lat,
area_m2: None,
name: Some(key.name),
},
);
Ok(())
})?;
std::fs::remove_file(&overture_path)?;
let index = overture.build();
each(&osm_path, |bytes| {
batch.push(bytes.to_vec());
if batch.len() == CHECK_BATCH {
check(&index, &mut batch, &mut stats, &mut keep)?;
}
Ok(())
})?;
check(&index, &mut batch, &mut stats, &mut keep)?;
std::fs::remove_file(&osm_path)?;
}
Ok(stats)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::record::RecordInit;
use geolith::admin::AdminHierarchy;
fn venue(name: &str, lon: f64, lat: f64, source: DataSource) -> GeocodingRecord {
GeocodingRecord::new(RecordInit {
id: 7,
source,
layer: GeocodingLayer::Venue,
name: name.to_string(),
lon,
lat,
admin: AdminHierarchy::default(),
address: None,
names: HashMap::new(),
importance: 0.5,
})
}
fn overture() -> DataSource {
DataSource::Overture {
theme: "places".into(),
otype: "place".into(),
}
}
fn osm() -> DataSource {
DataSource::Osm {
element_type: OsmElementType::Node,
relations: Vec::new(),
}
}
fn dedup(
buckets: usize,
overture: &[GeocodingRecord],
osm: &[GeocodingRecord],
) -> (Vec<GeocodingRecord>, DedupStats) {
let tmp = tempfile::tempdir().expect("tempdir");
let mut spill = OvertureSpill::new(tmp.path(), buckets).expect("spill");
for record in overture {
spill.add(record).expect("add overture");
}
let mut spill = spill.into_osm().expect("osm side");
for record in osm {
spill.add(record).expect("add osm");
}
let mut kept = Vec::new();
let stats = spill
.finish(|record| {
kept.push(record);
Ok(())
})
.expect("finish");
assert_eq!(
std::fs::read_dir(tmp.path()).expect("tmp").count(),
0,
"the buckets are removed"
);
(kept, stats)
}
fn across_a_border(buckets: usize) -> ((f64, f64), (f64, f64)) {
const M_PER_DEG: f64 = 111_194.926;
let lon = 73.85;
let mut lat = 18.5;
loop {
let next = lat + 20.0 / M_PER_DEG;
if osm_bucket(lon, lat, buckets) != osm_bucket(lon, next, buckets) {
return ((lon, lat), (lon, next));
}
lat += 10.0 / M_PER_DEG;
}
}
#[test]
fn a_repeat_across_a_bucket_border_is_still_dropped() {
let buckets = 64;
let ((lon_a, lat_a), (lon_b, lat_b)) = across_a_border(buckets);
let (kept, stats) = dedup(
buckets,
&[venue("Cafe Coffee Day", lon_a, lat_a, overture())],
&[
venue("cafe coffee day", lon_b, lat_b, osm()),
venue("Haldiram", lon_b, lat_b, osm()),
],
);
assert_eq!(
stats,
DedupStats {
kept: 1,
duplicates: 1
}
);
assert_eq!(kept[0].name, "Haldiram");
}
#[test]
fn a_far_or_other_layer_overture_record_keeps_the_osm_one() {
let far = 18.5 + 200.0 / 111_194.926;
let mut address = venue("Cafe Coffee Day", 73.85, 18.5, overture());
address.layer = GeocodingLayer::Address;
let (kept, stats) = dedup(
16,
&[venue("Cafe Coffee Day", 73.85, far, overture()), address],
&[venue("Cafe Coffee Day", 73.85, 18.5, osm())],
);
assert_eq!(stats.duplicates, 0);
assert_eq!(kept.len(), 1);
}
#[test]
fn a_record_comes_back_with_every_field() {
let mut record = GeocodingRecord::new(RecordInit {
id: (1 << 62) | 42,
source: DataSource::Osm {
element_type: OsmElementType::Way,
relations: Vec::new(),
},
layer: GeocodingLayer::Address,
name: "7 MG Road".into(),
lon: 73.856_743,
lat: 18.519_574,
admin: AdminHierarchy {
country_code: Some("IN".into()),
country: Some("India".into()),
region: Some("Maharashtra".into()),
county: Some("Pune".into()),
locality: None,
neighbourhood: Some("Camp".into()),
borough: None,
postcode: None,
city: None,
},
address: Some(AddressFields {
number: Some("7".into()),
street: Some("MG Road".into()),
unit: Some("2B".into()),
postcode: Some("411001".into()),
city: None,
}),
names: HashMap::from([("mr".to_string(), "ą„ ą¤ą¤®ą¤ą„ ą¤°ą„ą¤”".to_string())]),
importance: 0.3,
})
.with_source_id("way/42")
.with_categories(vec!["shop".into()]);
record
.addendum
.insert("osm".into(), serde_json::json!({ "wheelchair": "yes" }));
record.other_names = vec!["Old MG Road".into()];
record.article_names = vec!["Mahatma Gandhi Road".into()];
let (kept, _) = dedup(16, &[], std::slice::from_ref(&record));
let back = &kept[0];
assert_eq!(back.id, (1 << 62) | 42);
assert!(matches!(
back.source,
DataSource::Osm {
element_type: OsmElementType::Way,
..
}
));
assert_eq!(back.layer, GeocodingLayer::Address);
assert_eq!(back.name, "7 MG Road");
assert_eq!(back.search_text, record.search_text);
assert_eq!((back.lon, back.lat), (73.856_743, 18.519_574));
assert_eq!(back.country_code.as_deref(), Some("IN"));
assert_eq!(back.admin, record.admin);
assert_eq!(back.address, record.address);
assert_eq!(back.names.get("mr").map(String::as_str), Some("ą„ ą¤ą¤®ą¤ą„ ą¤°ą„ą¤”"));
assert_eq!(back.importance, 0.3);
assert_eq!(back.source_id.as_deref(), Some("way/42"));
assert_eq!(back.categories, ["shop"]);
assert_eq!(back.addendum["osm"]["wheelchair"], "yes");
assert_eq!(back.other_names, ["Old MG Road"]);
assert_eq!(back.article_names, ["Mahatma Gandhi Road"]);
}
#[test]
fn a_bucket_of_several_batches_keeps_every_record_in_order() {
let n = 2 * CHECK_BATCH + 7;
let repeat = CHECK_BATCH + 3;
let rows: Vec<GeocodingRecord> = (0..n)
.map(|i| {
let name = if i == repeat {
"zebra crossing cafe".to_string()
} else {
format!("osm {i}")
};
venue(&name, 73.85, 18.5, osm())
})
.collect();
let (kept, stats) = dedup(
16,
&[venue("Zebra Crossing Cafe", 73.85, 18.5, overture())],
&rows,
);
assert_eq!(
stats,
DedupStats {
kept: u64::try_from(n - 1).expect("fits"),
duplicates: 1
}
);
let names: Vec<&str> = kept.iter().map(|r| r.name.as_str()).collect();
let expected: Vec<String> = (0..n)
.filter(|&i| i != repeat)
.map(|i| format!("osm {i}"))
.collect();
assert_eq!(names, expected);
}
#[test]
fn a_broken_bucket_or_writer_fails_the_dedup() {
let tmp = tempfile::tempdir().expect("tempdir");
let mut scratch = Vec::new();
let place = venue("Cafe", 73.85, 18.5, osm());
let bucket = osm_bucket(place.lon, place.lat, 16);
let mut kept = Vec::new();
let mut keep = |record: GeocodingRecord| -> io::Result<()> {
kept.push(record.name);
Ok(())
};
let mut spill = OvertureSpill::new(tmp.path(), 16).expect("spill");
put(&mut spill.files[bucket], &1_u8, &mut scratch).expect("put");
let spill = spill.into_osm().expect("osm side");
spill
.finish(&mut keep)
.expect_err("a broken Overture bucket");
let mut spill = OvertureSpill::new(tmp.path(), 16)
.expect("spill")
.into_osm()
.expect("osm side");
spill.add(&place).expect("add");
put(&mut spill.files[bucket], &1_u8, &mut scratch).expect("put");
spill.finish(&mut keep).expect_err("a broken OSM bucket");
let mut spill = OvertureSpill::new(tmp.path(), 16)
.expect("spill")
.into_osm()
.expect("osm side");
let mut row = OsmRow::new(&place).expect("row");
row.addendum = vec![("osm".into(), "{".into())];
put(&mut spill.files[bucket], &row, &mut scratch).expect("put");
spill.finish(&mut keep).expect_err("a broken addendum");
assert_eq!(kept, ["Cafe"]);
let mut spill = OvertureSpill::new(tmp.path(), 16)
.expect("spill")
.into_osm()
.expect("osm side");
for _ in 0..CHECK_BATCH {
spill.add(&place).expect("add");
}
let err = spill
.finish(|_| Err(io::Error::other("disk full")))
.expect_err("a failing writer");
assert_eq!(err.to_string(), "disk full");
}
#[test]
fn an_overture_record_is_never_spilled_as_osm() {
let tmp = tempfile::tempdir().expect("tempdir");
let mut spill = OvertureSpill::new(tmp.path(), 16)
.expect("spill")
.into_osm()
.expect("osm side");
assert!(spill.add(&venue("x", 0.0, 0.0, overture())).is_err());
}
#[test]
fn bucket_count_stays_in_range() {
let n = bucket_count();
assert!((MIN_BUCKETS..=MAX_BUCKETS).contains(&n), "{n}");
}
}