1use std::path::Path;
4use std::time::Instant;
5use std::{fs, iter};
6
7use osmflow::nodes::PagedStore;
8use osmflow::nodes::prelude::*;
9use osmflow::osc::Replication;
10use osmflow::{Location, PbfReader};
11use postgres::Client;
12use postgres::fallible_iterator::FallibleIterator as _;
13use tracing::info;
14
15use crate::copy::wkb_locations;
16use crate::db::{self, DbState};
17use crate::files::{ID_KEY, read_diffs, remove_node_file, set_locations, way_pairs};
18use crate::index::ReverseIndex;
19use crate::sort::{Sorted, Sorter};
20use crate::update::check_stream;
21use crate::{Mirror, SyncError};
22
23#[derive(Clone, Copy)]
25pub enum Rebuild<'a> {
26 Database,
30 Pbf {
32 path: &'a Path,
34 sequence: Option<u64>,
36 replication: &'a Replication,
38 max_diffs: u64,
40 },
41}
42
43#[derive(Debug, Clone, Default, PartialEq, Eq)]
45pub struct RebuildStats {
46 pub nodes: u64,
48 pub diffs: u64,
50 pub pairs: u64,
52}
53
54pub(crate) fn rebuild(m: &Mirror, from: &Rebuild<'_>) -> Result<RebuildStats, SyncError> {
55 let mut client = db::connect(&m.url)?;
56 let state = DbState::read(&mut client)?;
57 let mut made = RebuildStats::default();
58
59 let t = Instant::now();
60 let path = m.node_path();
61 fs::create_dir_all(&m.dir)?;
62 remove_node_file(&path)?;
63 let mut store = PagedStore::open(&path)?;
64 match *from {
65 Rebuild::Database => {
66 let mut load = store.bulk_load()?;
67 let mut batch = Vec::with_capacity(1 << 20);
68 let mut last = None;
69 for node in db_locations(&mut client, &m.dir)? {
70 let (id, loc) = node?;
72 if last != Some(id) {
73 last = Some(id);
74 batch.push((id, unpack(loc)));
75 }
76 if batch.len() == batch.capacity() {
77 load.push_batch(&batch)?;
78 made.nodes += batch.len() as u64;
79 batch.clear();
80 }
81 }
82 load.push_batch(&batch)?;
83 made.nodes += batch.len() as u64;
84 load.finish(0)?;
85 }
86 Rebuild::Pbf {
87 path,
88 sequence,
89 replication,
90 max_diffs,
91 } => {
92 check_stream(&state, replication)?;
93 let reader = PbfReader::open(path)?;
94 let from =
95 sequence.or_else(|| reader.header().replication_sequence.map(i64::cast_unsigned));
96 let Some(from) = from.filter(|&s| s <= state.sequence.cast_unsigned()) else {
97 return Err(SyncError::state(format!(
98 "{}: give the sequence of the file, which must be at or before the database's {}",
99 path.display(),
100 state.sequence
101 )));
102 };
103 made.nodes = reader.load_nodes(&mut store)?;
104 info!(
105 nodes = made.nodes,
106 secs = t.elapsed().as_secs_f32(),
107 "loaded the node file"
108 );
109 let end = state.sequence.cast_unsigned();
110 let mut next = from + 1;
111 while next <= end {
112 let last = end.min(next + max_diffs.max(1) - 1);
113 let (changes, _) = read_diffs(replication, next..=last)?;
114 set_locations(&mut store, &changes)?;
115 store.commit(0)?;
117 made.diffs += last + 1 - next;
118 next = last + 1;
119 }
120 }
121 }
122 store.set_metadata(ID_KEY, &state.id.to_le_bytes())?;
123 store.commit(state.rev.cast_unsigned())?;
124 info!(
125 nodes = made.nodes,
126 diffs = made.diffs,
127 secs = t.elapsed().as_secs_f32(),
128 "rebuilt the node file"
129 );
130
131 let t = Instant::now();
132 let pairs = db_pairs(&mut client, &m.dir)?.map(|p| p.map_err(SyncError::from));
133 made.pairs = ReverseIndex::create(&m.index_path(), state.id, state.rev, pairs)?.1;
134 info!(
135 pairs = made.pairs,
136 secs = t.elapsed().as_secs_f32(),
137 "rebuilt the reverse index"
138 );
139 Ok(made)
140}
141
142fn db_locations(client: &mut Client, dir: &Path) -> Result<Sorted, SyncError> {
144 let sorter = Sorter::new(dir)?;
145 for sql in [
147 "SELECT nodes, ST_AsBinary(geom) FROM osm.ways WHERE geom IS NOT NULL",
148 "SELECT ARRAY[id], ST_AsBinary(geom) FROM osm.nodes WHERE geom IS NOT NULL",
149 ] {
150 let mut rows = client.query_raw(sql, iter::empty::<&str>())?;
151 while let Some(row) = rows.next()? {
152 let nodes: Vec<i64> = row.get(0);
153 let points = wkb_locations(row.get(1));
154 sorter.extend(
155 nodes
156 .into_iter()
157 .zip(points)
158 .filter_map(|(id, l)| Some((u64::try_from(id).ok()?, pack(l)))),
159 )?;
160 }
161 }
162 Ok(sorter.finish()?)
163}
164
165fn db_pairs(client: &mut Client, dir: &Path) -> Result<Sorted, SyncError> {
167 let sorter = Sorter::new(dir)?;
168 let mut rows = client.query_raw("SELECT id, nodes FROM osm.ways", iter::empty::<&str>())?;
169 while let Some(row) = rows.next()? {
170 sorter.extend(way_pairs(row.get(0), &row.get::<_, Vec<i64>>(1)))?;
171 }
172 Ok(sorter.finish()?)
173}
174
175fn pack(l: Location) -> u64 {
177 (u64::from(l.lat.cast_unsigned()) << 32) | u64::from(l.lon.cast_unsigned())
178}
179
180fn unpack(v: u64) -> Location {
181 let [lat, lon] =
182 [v >> 32, v & 0xffff_ffff].map(|h| u32::try_from(h).unwrap_or_default().cast_signed());
183 Location::new(lat, lon)
184}