use std::cmp::{Ordering, Reverse};
use std::collections::BinaryHeap;
use std::fs::File;
use std::io::{self, BufReader, BufWriter, Read, Write};
use std::path::{Path, PathBuf};
use rayon::iter::ParallelIterator;
use rayon::prelude::ParallelDrainRange;
use rayon::slice::ParallelSliceMut;
use serde::{Deserialize, Serialize};
use crate::record::GeocodingRecord;
pub const IMPORTANCE_WEIGHT: f32 = 10.0;
const PREPARE_BATCH: usize = 1 << 16;
pub const DEFAULT_SORT_BYTES: usize = 1 << 30;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct Row {
id: i64,
name: String,
lon: f64,
lat: f64,
layer: String,
country_code: String,
country: String,
region: String,
county: String,
locality: String,
street: String,
postcode: String,
housenumber: String,
source_id: String,
search_text: String,
name_text: String,
importance: f32,
shape: Vec<u8>,
neighbourhood: String,
borough: String,
category: String,
languages: String,
bbox: Option<[f64; 4]>,
}
fn languages_column(record: &GeocodingRecord) -> String {
let mut names: Vec<(&String, &String)> = record
.names
.iter()
.filter(|(code, name)| crate::record::is_language_code(code) && !name.trim().is_empty())
.collect();
names.sort_unstable_by(|a, b| a.0.cmp(b.0));
let mut out = String::new();
for (code, name) in names {
if !out.is_empty() {
out.push(glx::format::LANGUAGE_ENTRY_SEP);
}
out.push_str(code);
out.push(glx::format::LANGUAGE_SEP);
out.push_str(&name.trim().replace(
[glx::format::LANGUAGE_SEP, glx::format::LANGUAGE_ENTRY_SEP],
" ",
));
}
out
}
fn pg_text(value: Option<&str>) -> String {
value.map(|s| s.replace('\0', "")).unwrap_or_default()
}
fn rounded<T: std::str::FromStr + Default>(text: &str) -> T {
text.parse().unwrap_or_default()
}
impl Row {
fn from_record(record: &GeocodingRecord) -> Self {
let address = record.address.as_ref();
Self {
id: crate::output::pg_copy::pg_bigint_id(record.id),
name: pg_text(Some(&record.name)),
lon: rounded(&format!("{:.7}", record.lon)),
lat: rounded(&format!("{:.7}", record.lat)),
layer: record.layer.as_str().to_owned(),
country_code: pg_text(record.country_code.as_deref()),
country: pg_text(record.admin.country.as_deref()),
region: pg_text(record.admin.region.as_deref()),
county: pg_text(record.admin.county.as_deref()),
locality: pg_text(record.admin.locality.as_deref()),
street: pg_text(address.and_then(|a| a.street.as_deref())),
postcode: pg_text(
address
.and_then(|a| a.postcode.as_deref())
.or(record.admin.postcode.as_deref()),
),
housenumber: pg_text(address.and_then(|a| a.number.as_deref())),
source_id: pg_text(record.source_id.as_deref()),
search_text: pg_text(Some(&record.search_text)),
name_text: pg_text(Some(&record.name_text())),
importance: rounded(&format!("{:.4}", record.importance)),
shape: record.shape.clone(),
neighbourhood: pg_text(record.admin.neighbourhood.as_deref()),
borough: pg_text(record.admin.borough.as_deref()),
category: pg_text(record.category_words().as_deref()),
languages: languages_column(record),
bbox: (!record.shape.is_empty())
.then(|| glx::format::decode_shape(&record.shape))
.flatten()
.and_then(|polygons| glx::format::shape_bbox(&polygons)),
}
}
const fn size(&self) -> usize {
std::mem::size_of::<Self>()
+ self.name.len()
+ self.layer.len()
+ self.country_code.len()
+ self.country.len()
+ self.region.len()
+ self.county.len()
+ self.locality.len()
+ self.street.len()
+ self.postcode.len()
+ self.housenumber.len()
+ self.source_id.len()
+ self.search_text.len()
+ self.name_text.len()
+ self.shape.len()
+ self.neighbourhood.len()
+ self.borough.len()
+ self.category.len()
+ self.languages.len()
}
fn band(&self) -> i64 {
if self.layer == "address" {
0
} else {
let band = (f64::from(self.importance) * 20.0).floor() as i64;
-band
}
}
fn into_doc(self) -> glx::write::Doc {
glx::write::Doc {
importance: self.importance,
record: glx::format::Record {
id: self.id,
lon: self.lon,
lat: self.lat,
name: self.name,
layer: self.layer,
country_code: self.country_code,
country: self.country,
region: self.region,
county: self.county,
locality: self.locality,
street: self.street,
postcode: self.postcode,
housenumber: self.housenumber,
source_id: self.source_id,
search_text: self.search_text,
name_text: self.name_text,
importance: self.importance,
neighbourhood: self.neighbourhood,
borough: self.borough,
category: self.category,
languages: self.languages,
bbox: self.bbox,
},
shape: self.shape,
}
}
}
#[cfg(test)]
fn order(a: &Row, b: &Row) -> Ordering {
Keyed::new(a.clone()).cmp(&Keyed::new(b.clone()))
}
fn by_place(a: &Row, b: &Row) -> Ordering {
a.region
.cmp(&b.region)
.then_with(|| a.county.cmp(&b.county))
.then_with(|| a.locality.cmp(&b.locality))
.then_with(|| a.street.cmp(&b.street))
.then_with(|| a.name.cmp(&b.name))
.then_with(|| a.id.cmp(&b.id))
}
struct Keyed {
address: bool,
band: i64,
pieces: usize,
row: Row,
}
impl Keyed {
fn new(row: Row) -> Self {
Self {
address: row.layer == "address",
band: row.band(),
pieces: pieces(scored(&row.search_text)),
row,
}
}
fn cmp(&self, other: &Self) -> Ordering {
self.address
.cmp(&other.address)
.then(self.band.cmp(&other.band))
.then(self.pieces.cmp(&other.pieces))
.then_with(|| by_place(&self.row, &other.row))
}
}
fn scored(text: &str) -> &str {
text.split(glx::tokenize::LANGUAGE_MARK)
.next()
.unwrap_or("")
}
fn pieces(text: &str) -> usize {
#[cfg(test)]
PIECES_CALLS.with(|c| c.set(c.get() + 1));
let mut count = 1;
let mut in_separator = false;
for ch in text.chars() {
let separator = !ch.is_alphanumeric();
if separator && !in_separator {
count += 1;
}
in_separator = separator;
}
count
}
#[cfg(test)]
thread_local! {
static PIECES_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
pub struct GlxWriter<W: Write> {
out: W,
dir: PathBuf,
sort_bytes: usize,
buffer: Vec<Keyed>,
buffer_bytes: usize,
runs: Vec<PathBuf>,
count: u64,
}
impl<W: Write> GlxWriter<W> {
pub fn new(out: W, dir: &Path, sort_bytes: usize) -> io::Result<Self> {
std::fs::create_dir_all(dir)?;
Ok(Self {
out,
dir: dir.to_path_buf(),
sort_bytes,
buffer: Vec::new(),
buffer_bytes: 0,
runs: Vec::new(),
count: 0,
})
}
pub fn write_record(&mut self, record: &GeocodingRecord) -> io::Result<()> {
self.push(Row::from_record(record))
}
#[must_use]
pub const fn count(&self) -> u64 {
self.count
}
#[must_use]
pub const fn runs(&self) -> usize {
self.runs.len()
}
fn push(&mut self, row: Row) -> io::Result<()> {
self.buffer_bytes += row.size();
self.buffer.push(Keyed::new(row));
self.count += 1;
if self.buffer_bytes >= self.sort_bytes {
self.spill()?;
}
Ok(())
}
fn spill(&mut self) -> io::Result<()> {
self.buffer.par_sort_by(Keyed::cmp);
let path = self.dir.join(format!("run-{:05}.lz4", self.runs.len()));
let mut out = lz4_flex::frame::FrameEncoder::new(BufWriter::new(File::create(&path)?));
for keyed in self.buffer.drain(..) {
let bytes = postcard::to_allocvec(&keyed.row).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)?;
}
out.finish().map_err(io::Error::other)?.flush()?;
self.buffer_bytes = 0;
self.runs.push(path);
Ok(())
}
fn merged(&mut self) -> io::Result<Merge> {
let mut sources = Vec::with_capacity(self.runs.len() + 1);
for path in &self.runs {
let file = BufReader::with_capacity(1 << 20, File::open(path)?);
sources.push(Source::Run(lz4_flex::frame::FrameDecoder::new(file)));
}
let mut memory = std::mem::take(&mut self.buffer);
memory.par_sort_by(Keyed::cmp);
sources.push(Source::Memory(memory.into_iter()));
let mut merge = Merge {
heap: BinaryHeap::with_capacity(sources.len()),
sources,
};
for source in 0..merge.sources.len() {
merge.refill(source)?;
}
Ok(merge)
}
pub fn finish(mut self) -> io::Result<glx::write::Stats> {
let index_dir = self.dir.join("index");
let mut writer = glx::write::Writer::new(&index_dir)?;
let mut merged = self.merged()?;
let mut batch: Vec<Row> = Vec::with_capacity(PREPARE_BATCH);
loop {
batch.clear();
for row in merged.by_ref().take(PREPARE_BATCH) {
batch.push(row?);
}
if batch.is_empty() {
break;
}
let prepared: Vec<glx::write::Prepared> = batch
.par_drain(..)
.map(|row| glx::write::Prepared::new(&row.into_doc()))
.collect();
for p in prepared {
writer.add_prepared(p)?;
}
}
for run in &self.runs {
std::fs::remove_file(run)?;
}
let stats = writer.finish(&mut self.out, IMPORTANCE_WEIGHT)?;
if index_dir.exists() {
std::fs::remove_dir_all(&index_dir)?;
}
Ok(stats)
}
}
struct Merge {
heap: BinaryHeap<Reverse<Head>>,
sources: Vec<Source>,
}
struct Head {
row: Keyed,
source: usize,
}
impl PartialEq for Head {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl Eq for Head {}
impl PartialOrd for Head {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Head {
fn cmp(&self, other: &Self) -> Ordering {
self.row
.cmp(&other.row)
.then(self.source.cmp(&other.source))
}
}
enum Source {
Run(lz4_flex::frame::FrameDecoder<BufReader<File>>),
Memory(std::vec::IntoIter<Keyed>),
}
impl Iterator for Merge {
type Item = io::Result<Row>;
fn next(&mut self) -> Option<Self::Item> {
let Reverse(head) = self.heap.pop()?;
match self.refill(head.source) {
Ok(()) => Some(Ok(head.row.row)),
Err(e) => Some(Err(e)),
}
}
}
impl Merge {
fn refill(&mut self, source: usize) -> io::Result<()> {
let row = match &mut self.sources[source] {
Source::Memory(rows) => rows.next(),
Source::Run(reader) => read_row(reader)?.map(Keyed::new),
};
if let Some(row) = row {
self.heap.push(Reverse(Head { row, source }));
}
Ok(())
}
}
fn read_row(reader: &mut impl Read) -> io::Result<Option<Row>> {
let mut len = [0_u8; 4];
match reader.read_exact(&mut len) {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
Err(e) => return Err(e),
}
let mut bytes = vec![0_u8; u32::from_le_bytes(len) as usize];
reader.read_exact(&mut bytes)?;
postcard::from_bytes(&bytes)
.map(Some)
.map_err(io::Error::other)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::record::RecordInit;
fn row(layer: &str, importance: f32, text: &str, locality: &str, id: i64) -> Row {
Row {
id,
name: text.to_owned(),
lon: 0.0,
lat: 0.0,
layer: layer.to_owned(),
country_code: String::new(),
country: String::new(),
region: String::new(),
county: String::new(),
locality: locality.to_owned(),
street: String::new(),
postcode: String::new(),
housenumber: String::new(),
source_id: String::new(),
search_text: text.to_owned(),
name_text: text.to_owned(),
importance,
shape: Vec::new(),
neighbourhood: String::new(),
borough: String::new(),
category: String::new(),
languages: String::new(),
bbox: None,
}
}
#[test]
fn a_row_carries_languages_neighbourhood_and_the_shape_box() {
let mut record = GeocodingRecord::new(RecordInit {
id: 1,
source: geolith::source::input::DataSource::Overture {
theme: "divisions".into(),
otype: "division_area".into(),
},
layer: crate::record::GeocodingLayer::Region,
name: "Maharashtra".into(),
lon: 75.0,
lat: 19.0,
admin: geolith::admin::AdminHierarchy {
neighbourhood: Some("Seawoods East".into()),
borough: Some("Nerul".into()),
..Default::default()
},
address: None,
names: std::collections::HashMap::from([
("mr".to_owned(), "महाराष्ट्र".to_owned()),
("hi".to_owned(), "महाराष्ट्र".to_owned()),
("name:etymology".to_owned(), "great nation".to_owned()),
]),
importance: 0.5,
});
glx::format::encode_shape(
&[vec![vec![
[72.6, 15.6],
[80.9, 15.6],
[80.9, 22.0],
[72.6, 15.6],
]]],
&mut record.shape,
);
let row = Row::from_record(&record);
assert_eq!(row.languages, "hi\u{1F}महाराष्ट्र\u{1E}mr\u{1F}महाराष्ट्र");
assert_eq!(row.neighbourhood, "Seawoods East");
assert_eq!(row.borough, "Nerul");
assert_eq!(row.bbox, Some([72.6, 15.6, 80.9, 22.0]));
}
#[test]
fn pieces_count_like_postgres_regexp_split() {
assert_eq!(pieces("India Gate"), 2);
assert_eq!(pieces("12, MG Road"), 3);
assert_eq!(pieces(" Pune"), 2);
assert_eq!(pieces("Pune"), 1);
assert_eq!(pieces(""), 1);
}
#[test]
fn venues_come_by_falling_importance_band_then_addresses_by_word_count() {
let mut rows = [
row("address", 0.0, "7 MG Road Pune", "Pune", 1),
row("venue", 0.10, "Cafe", "Pune", 2),
row("address", 0.0, "MG Road", "Pune", 3),
row("locality", 0.95, "Pune", "Pune", 4),
row("venue", 0.92, "Shaniwar Wada", "Pune", 5),
];
rows.sort_by(order);
let ids: Vec<i64> = rows.iter().map(|r| r.id).collect();
assert_eq!(ids, vec![4, 5, 2, 3, 1]);
}
#[test]
fn rows_of_one_place_sit_together_then_by_id() {
let mut rows = [
row("address", 0.0, "1 A Road", "Wakad", 9),
row("address", 0.0, "1 A Road", "Aundh", 8),
row("address", 0.0, "1 A Road", "Wakad", 7),
];
rows.sort_by(order);
let ids: Vec<i64> = rows.iter().map(|r| r.id).collect();
assert_eq!(ids, vec![8, 7, 9]);
}
#[test]
fn row_keeps_values_as_postgres_stores_them() {
use crate::record::{AddressFields, GeocodingLayer};
use geolith::admin::AdminHierarchy;
use geolith::source::input::{DataSource, OsmElementType};
let admin = AdminHierarchy {
country_code: Some("IN".to_owned()),
country: Some("India".to_owned()),
region: Some("Maharashtra".to_owned()),
locality: Some("Pune".to_owned()),
..AdminHierarchy::default()
};
let record = GeocodingRecord::new(RecordInit {
id: u64::MAX,
source: DataSource::Osm {
element_type: OsmElementType::Node,
relations: Vec::new(),
},
layer: GeocodingLayer::Address,
name: "7".to_owned(),
lon: 73.856_743_21,
lat: 18.520_430_49,
admin,
address: Some(AddressFields {
number: Some("7".to_owned()),
street: Some("MG Road".to_owned()),
unit: None,
postcode: None,
city: None,
}),
names: std::collections::HashMap::new(),
importance: 0.123_456,
});
let row = Row::from_record(&record);
assert_eq!(row.id, -1);
assert_eq!(row.lon, 73.856_743_2);
assert_eq!(row.lat, 18.520_430_5);
assert_eq!(row.importance, 0.1235);
assert_eq!(row.layer, "address");
assert_eq!(row.street, "MG Road");
assert_eq!(row.county, "");
assert_eq!(row.postcode, "");
assert_eq!(row.region, "Maharashtra");
}
fn sorted_ids_through_writer(rows: &[Row], sort_bytes: usize) -> (Vec<i64>, usize) {
let dir = tempfile::tempdir().expect("tempdir");
let mut writer = GlxWriter::new(Vec::new(), dir.path(), sort_bytes).expect("writer");
for r in rows {
writer.push(r.clone()).expect("push");
}
let runs_before = writer.runs();
let merged: Vec<i64> = writer
.merged()
.expect("merge")
.map(|r| r.expect("row").id)
.collect();
(merged, runs_before)
}
struct Watch {
dir: PathBuf,
runs_at_first_write: Option<usize>,
bytes: Vec<u8>,
}
impl Write for Watch {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
if self.runs_at_first_write.is_none() {
let runs = std::fs::read_dir(&self.dir)
.expect("dir")
.filter_map(Result::ok)
.filter(|entry| entry.file_name().to_string_lossy().starts_with("run-"))
.count();
self.runs_at_first_write = Some(runs);
}
self.bytes.extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
#[test]
fn the_runs_are_gone_before_the_file_is_written() {
let dir = tempfile::tempdir().expect("tempdir");
let mut watch = Watch {
dir: dir.path().to_path_buf(),
runs_at_first_write: None,
bytes: Vec::new(),
};
let mut writer = GlxWriter::new(&mut watch, dir.path(), 2_000).expect("writer");
for id in 0..200 {
writer
.push(row("venue", 0.5, "Some Place Name", "Pune", id))
.expect("push");
}
let runs = writer.runs();
assert!(runs > 5, "only {runs} runs");
writer.finish().expect("finish");
assert_eq!(watch.runs_at_first_write, Some(0));
let start = glx::format::FILE_HEADER_LEN;
let part = glx::format::Span {
offset: start,
len: watch.bytes.len() as u64 - start,
};
let header =
glx::format::Header::decode(&watch.bytes[start as usize..], part).expect("header");
assert_eq!(header.docs, 200);
}
#[test]
fn a_file_that_cannot_be_written_fails_the_build() {
let dir = tempfile::tempdir().expect("tempdir");
let full: &mut [u8] = &mut [];
let mut writer = GlxWriter::new(full, dir.path(), DEFAULT_SORT_BYTES).expect("writer");
writer
.push(row("venue", 0.5, "Some Place Name", "Pune", 1))
.expect("push");
let err = writer.finish().expect_err("a full output fails the build");
assert_eq!(err.kind(), io::ErrorKind::WriteZero);
}
#[test]
fn a_sort_counts_each_rows_words_once() {
let rows: Vec<Row> = (0..1_000)
.map(|i| {
let text = ["Some Place Name", "Café", "12, MG Road Pune", "東京タワー"]
[usize::try_from(i % 4).unwrap_or(0)];
row("address", 0.0, text, "Pune", i)
})
.collect();
PIECES_CALLS.with(|c| c.set(0));
let (spilled, _) = sorted_ids_through_writer(&rows, 20_000);
let calls = PIECES_CALLS.with(std::cell::Cell::get);
assert_eq!(spilled.len(), 1_000);
assert!(calls <= 2_000, "{calls} word counts for 1,000 rows");
}
#[test]
fn spilled_runs_merge_into_the_same_order_as_one_sort() {
let rows: Vec<Row> = (0..200)
.map(|i| {
let layer = if i % 3 == 0 { "address" } else { "venue" };
let importance = f32::from(u8::try_from(i % 20).unwrap_or(0)) / 20.0;
let locality = ["Aundh", "Baner", "Wakad"][usize::try_from(i % 3).unwrap_or(0)];
row(layer, importance, "Some Place Name", locality, i)
})
.collect();
let mut expected = rows.clone();
expected.sort_by(order);
let expected: Vec<i64> = expected.iter().map(|r| r.id).collect();
let (in_memory, no_runs) = sorted_ids_through_writer(&rows, usize::MAX);
assert_eq!(no_runs, 0);
assert_eq!(in_memory, expected);
let (spilled, runs) = sorted_ids_through_writer(&rows, 2_000);
assert!(runs > 5, "expected many runs, got {runs}");
assert_eq!(spilled, expected);
}
}