use std::path::Path;
use std::time::Instant;
use std::{fs, iter};
use geo_traits::{
CoordTrait, GeometryTrait as _, GeometryType, LineStringTrait as _, PointTrait as _,
};
use osmflow::nodes::PagedStore;
use osmflow::nodes::prelude::*;
use osmflow::osc::Replication;
use osmflow::{Location, PbfReader};
use postgres::Client;
use postgres::fallible_iterator::FallibleIterator as _;
use tracing::info;
use wkb::reader::read_wkb;
use crate::copy::{locations, osm_twkb};
use crate::db::{self, DbState, NodeIds, Table};
use crate::files::{ID_KEY, read_diffs, remove_node_file, set_locations, way_pairs};
use crate::index::ReverseIndex;
use crate::sort::{Sorted, Sorter};
use crate::update::check_stream;
use crate::{Mirror, SyncError, TableLayout};
#[derive(Clone, Copy)]
pub enum Rebuild<'a> {
Database,
Pbf {
path: &'a Path,
sequence: Option<u64>,
replication: &'a Replication,
max_diffs: u64,
},
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RebuildStats {
pub nodes: u64,
pub diffs: u64,
pub pairs: u64,
}
pub(crate) fn rebuild(m: &Mirror, from: &Rebuild<'_>) -> Result<RebuildStats, SyncError> {
let mut client = db::connect(&m.url)?;
let state = DbState::read(&mut client)?;
let mut made = RebuildStats::default();
let t = Instant::now();
let path = m.node_path();
fs::create_dir_all(&m.dir)?;
remove_node_file(&path)?;
let mut store = PagedStore::open(&path)?;
match *from {
Rebuild::Database => {
let mut load = store.bulk_load()?;
let mut batch = Vec::with_capacity(1 << 20);
let mut last = None;
for node in db_locations(&mut client, &m.dir, state.tables)? {
let (id, loc) = node?;
if last != Some(id) {
last = Some(id);
batch.push((id, unpack(loc)));
}
if batch.len() == batch.capacity() {
load.push_batch(&batch)?;
made.nodes += batch.len() as u64;
batch.clear();
}
}
load.push_batch(&batch)?;
made.nodes += batch.len() as u64;
load.finish(0)?;
}
Rebuild::Pbf {
path,
sequence,
replication,
max_diffs,
} => {
check_stream(&state, replication)?;
let reader = PbfReader::open(path)?;
let from =
sequence.or_else(|| reader.header().replication_sequence.map(i64::cast_unsigned));
let Some(from) = from.filter(|&s| s <= state.sequence.cast_unsigned()) else {
return Err(SyncError::state(format!(
"{}: give the sequence of the file, which must be at or before the database's {}",
path.display(),
state.sequence
)));
};
made.nodes = reader.load_nodes(&mut store)?;
info!(
nodes = made.nodes,
secs = t.elapsed().as_secs_f32(),
"loaded the node file"
);
let end = state.sequence.cast_unsigned();
let mut next = from + 1;
while next <= end {
let last = end.min(next + max_diffs.max(1) - 1);
let (changes, _) = read_diffs(replication, next..=last)?;
set_locations(&mut store, &changes)?;
store.commit(0)?;
made.diffs += last + 1 - next;
next = last + 1;
}
}
}
store.set_metadata(ID_KEY, &state.id.to_le_bytes())?;
store.commit(state.rev.cast_unsigned())?;
info!(
nodes = made.nodes,
diffs = made.diffs,
secs = t.elapsed().as_secs_f32(),
"rebuilt the node file"
);
let t = Instant::now();
let pairs = db_pairs(&mut client, &m.dir, state.tables)?.map(|p| p.map_err(SyncError::from));
made.pairs = ReverseIndex::create(&m.index_path(), state.id, state.rev, pairs)?.1;
info!(
pairs = made.pairs,
secs = t.elapsed().as_secs_f32(),
"rebuilt the reverse index"
);
Ok(made)
}
fn db_locations(client: &mut Client, dir: &Path, layout: TableLayout) -> Result<Sorted, SyncError> {
let sorter = Sorter::new(dir)?;
let geom = match layout {
TableLayout::Packed => "geom",
TableLayout::Plain => "ST_AsBinary(geom)",
};
for (is_way, sql) in [
(
true,
format!(
"SELECT 'way', id, nodes, {geom} FROM {} WHERE geom IS NOT NULL",
Table::Ways.name(layout)
),
),
(
false,
format!(
"SELECT 'node', id, id, {geom} FROM {} WHERE geom IS NOT NULL",
Table::Nodes.name(layout)
),
),
] {
let mut rows = client.query_raw(&sql, iter::empty::<&str>())?;
while let Some(row) = rows.next()? {
let nodes = if is_way {
row.get::<_, NodeIds>(2).0
} else {
vec![row.get(2)]
};
let buf: &[u8] = row.get(3);
let added = match layout {
TableLayout::Packed => {
let g = osm_twkb(buf);
add_locations(&sorter, &nodes, g.as_ref().map(locations))?
}
TableLayout::Plain => match read_wkb(buf).as_ref().map(|g| g.as_type()) {
Ok(GeometryType::Point(p)) => {
add_locations(&sorter, &nodes, Some(p.coord().iter().map(location)))?
}
Ok(GeometryType::LineString(l)) => {
add_locations(&sorter, &nodes, Some(l.coords().map(|c| location(&c))))?
}
_ => false,
},
};
if !added {
let (kind, id): (&str, i64) = (row.get(0), row.get(1));
return Err(SyncError::state(format!(
"{kind} {id}: its geometry does not have one point for each of its {} nodes",
nodes.len()
)));
}
}
}
Ok(sorter.finish()?)
}
fn add_locations(
sorter: &Sorter,
nodes: &[i64],
points: Option<impl ExactSizeIterator<Item = Location>>,
) -> Result<bool, SyncError> {
let Some(points) = points.filter(|p| p.len() == nodes.len()) else {
return Ok(false);
};
sorter.extend(
nodes
.iter()
.zip(points)
.filter_map(|(&id, l)| Some((u64::try_from(id).ok()?, pack(l)))),
)?;
Ok(true)
}
fn db_pairs(client: &mut Client, dir: &Path, tables: TableLayout) -> Result<Sorted, SyncError> {
let sorter = Sorter::new(dir)?;
let sql = format!("SELECT id, nodes FROM {}", Table::Ways.name(tables));
let mut rows = client.query_raw(&sql, iter::empty::<&str>())?;
while let Some(row) = rows.next()? {
sorter.extend(way_pairs(row.get(0), &row.get::<_, NodeIds>(1).0))?;
}
Ok(sorter.finish()?)
}
fn location(c: &impl CoordTrait<T = f64>) -> Location {
Location::from_degrees(c.y(), c.x())
}
fn pack(l: Location) -> u64 {
(u64::from(l.lat.cast_unsigned()) << 32) | u64::from(l.lon.cast_unsigned())
}
fn unpack(v: u64) -> Location {
let [lat, lon] =
[v >> 32, v & 0xffff_ffff].map(|h| u32::try_from(h).unwrap_or_default().cast_signed());
Location::new(lat, lon)
}