1use std::path::Path;
4use std::time::Instant;
5use std::{fs, iter};
6
7use geo_traits::{
8 CoordTrait, GeometryTrait as _, GeometryType, LineStringTrait as _, PointTrait as _,
9};
10use osmflow::nodes::PagedStore;
11use osmflow::nodes::prelude::*;
12use osmflow::osc::Replication;
13use osmflow::{Location, PbfReader};
14use postgres::Client;
15use postgres::fallible_iterator::FallibleIterator as _;
16use tracing::info;
17use wkb::reader::read_wkb;
18
19use crate::copy::{locations, osm_twkb};
20use crate::db::{self, DbState};
21use crate::files::{ID_KEY, read_diffs, remove_node_file, set_locations, way_pairs};
22use crate::index::ReverseIndex;
23use crate::sort::{Sorted, Sorter};
24use crate::update::check_stream;
25use crate::{GeometryFormat, Mirror, SyncError};
26
27#[derive(Clone, Copy)]
29pub enum Rebuild<'a> {
30 Database,
34 Pbf {
36 path: &'a Path,
38 sequence: Option<u64>,
40 replication: &'a Replication,
42 max_diffs: u64,
44 },
45}
46
47#[derive(Debug, Clone, Default, PartialEq, Eq)]
49pub struct RebuildStats {
50 pub nodes: u64,
52 pub diffs: u64,
54 pub pairs: u64,
56}
57
58pub(crate) fn rebuild(m: &Mirror, from: &Rebuild<'_>) -> Result<RebuildStats, SyncError> {
59 let mut client = db::connect(&m.url)?;
60 let state = DbState::read(&mut client)?;
61 let mut made = RebuildStats::default();
62
63 let t = Instant::now();
64 let path = m.node_path();
65 fs::create_dir_all(&m.dir)?;
66 remove_node_file(&path)?;
67 let mut store = PagedStore::open(&path)?;
68 match *from {
69 Rebuild::Database => {
70 let mut load = store.bulk_load()?;
71 let mut batch = Vec::with_capacity(1 << 20);
72 let mut last = None;
73 for node in db_locations(&mut client, &m.dir, state.geometry)? {
74 let (id, loc) = node?;
76 if last != Some(id) {
77 last = Some(id);
78 batch.push((id, unpack(loc)));
79 }
80 if batch.len() == batch.capacity() {
81 load.push_batch(&batch)?;
82 made.nodes += batch.len() as u64;
83 batch.clear();
84 }
85 }
86 load.push_batch(&batch)?;
87 made.nodes += batch.len() as u64;
88 load.finish(0)?;
89 }
90 Rebuild::Pbf {
91 path,
92 sequence,
93 replication,
94 max_diffs,
95 } => {
96 check_stream(&state, replication)?;
97 let reader = PbfReader::open(path)?;
98 let from =
99 sequence.or_else(|| reader.header().replication_sequence.map(i64::cast_unsigned));
100 let Some(from) = from.filter(|&s| s <= state.sequence.cast_unsigned()) else {
101 return Err(SyncError::state(format!(
102 "{}: give the sequence of the file, which must be at or before the database's {}",
103 path.display(),
104 state.sequence
105 )));
106 };
107 made.nodes = reader.load_nodes(&mut store)?;
108 info!(
109 nodes = made.nodes,
110 secs = t.elapsed().as_secs_f32(),
111 "loaded the node file"
112 );
113 let end = state.sequence.cast_unsigned();
114 let mut next = from + 1;
115 while next <= end {
116 let last = end.min(next + max_diffs.max(1) - 1);
117 let (changes, _) = read_diffs(replication, next..=last)?;
118 set_locations(&mut store, &changes)?;
119 store.commit(0)?;
121 made.diffs += last + 1 - next;
122 next = last + 1;
123 }
124 }
125 }
126 store.set_metadata(ID_KEY, &state.id.to_le_bytes())?;
127 store.commit(state.rev.cast_unsigned())?;
128 info!(
129 nodes = made.nodes,
130 diffs = made.diffs,
131 secs = t.elapsed().as_secs_f32(),
132 "rebuilt the node file"
133 );
134
135 let t = Instant::now();
136 let pairs = db_pairs(&mut client, &m.dir)?.map(|p| p.map_err(SyncError::from));
137 made.pairs = ReverseIndex::create(&m.index_path(), state.id, state.rev, pairs)?.1;
138 info!(
139 pairs = made.pairs,
140 secs = t.elapsed().as_secs_f32(),
141 "rebuilt the reverse index"
142 );
143 Ok(made)
144}
145
146fn db_locations(
148 client: &mut Client,
149 dir: &Path,
150 format: GeometryFormat,
151) -> Result<Sorted, SyncError> {
152 let sorter = Sorter::new(dir)?;
153 let geom = match format {
156 GeometryFormat::Twkb => "geom",
157 GeometryFormat::Wkb => "ST_AsBinary(geom)",
158 };
159 for sql in [
160 format!("SELECT 'way', id, nodes, {geom} FROM osm.ways WHERE geom IS NOT NULL"),
161 format!("SELECT 'node', id, ARRAY[id], {geom} FROM osm.nodes WHERE geom IS NOT NULL"),
162 ] {
163 let mut rows = client.query_raw(&sql, iter::empty::<&str>())?;
164 while let Some(row) = rows.next()? {
165 let nodes: Vec<i64> = row.get(2);
166 let buf: &[u8] = row.get(3);
167 let added = match format {
168 GeometryFormat::Twkb => {
169 let g = osm_twkb(buf);
170 add_locations(&sorter, &nodes, g.as_ref().map(locations))?
171 }
172 GeometryFormat::Wkb => match read_wkb(buf).as_ref().map(|g| g.as_type()) {
173 Ok(GeometryType::Point(p)) => {
174 add_locations(&sorter, &nodes, Some(p.coord().iter().map(location)))?
175 }
176 Ok(GeometryType::LineString(l)) => {
177 add_locations(&sorter, &nodes, Some(l.coords().map(|c| location(&c))))?
178 }
179 _ => false,
180 },
181 };
182 if !added {
183 let (kind, id): (&str, i64) = (row.get(0), row.get(1));
184 return Err(SyncError::state(format!(
185 "{kind} {id}: its geometry does not have one point for each of its {} nodes",
186 nodes.len()
187 )));
188 }
189 }
190 }
191 Ok(sorter.finish()?)
192}
193
194fn add_locations(
197 sorter: &Sorter,
198 nodes: &[i64],
199 points: Option<impl ExactSizeIterator<Item = Location>>,
200) -> Result<bool, SyncError> {
201 let Some(points) = points.filter(|p| p.len() == nodes.len()) else {
202 return Ok(false);
203 };
204 sorter.extend(
205 nodes
206 .iter()
207 .zip(points)
208 .filter_map(|(&id, l)| Some((u64::try_from(id).ok()?, pack(l)))),
209 )?;
210 Ok(true)
211}
212
213fn db_pairs(client: &mut Client, dir: &Path) -> Result<Sorted, SyncError> {
215 let sorter = Sorter::new(dir)?;
216 let mut rows = client.query_raw("SELECT id, nodes FROM osm.ways", iter::empty::<&str>())?;
217 while let Some(row) = rows.next()? {
218 sorter.extend(way_pairs(row.get(0), &row.get::<_, Vec<i64>>(1)))?;
219 }
220 Ok(sorter.finish()?)
221}
222
223fn location(c: &impl CoordTrait<T = f64>) -> Location {
225 Location::from_degrees(c.y(), c.x())
226}
227
228fn pack(l: Location) -> u64 {
230 (u64::from(l.lat.cast_unsigned()) << 32) | u64::from(l.lon.cast_unsigned())
231}
232
233fn unpack(v: u64) -> Location {
234 let [lat, lon] =
235 [v >> 32, v & 0xffff_ffff].map(|h| u32::try_from(h).unwrap_or_default().cast_signed());
236 Location::new(lat, lon)
237}