Skip to main content

osmflow_sync/
rebuild.rs

1//! Rebuilding the node file and the reverse index, up to the database's revision, which is only read.
2
3use 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, NodeIds, Table};
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::{Mirror, SyncError, TableLayout};
26
27/// Where [`Mirror::rebuild`] takes node locations from. The reverse index is always made from the database's ways.
28#[derive(Clone, Copy)]
29pub enum Rebuild<'a> {
30    /// The database: the points of the ways' geometries, and the tagged nodes. Nodes in no way with a geometry
31    /// and without tags are not in the database, so they are missing from the new file; they matter only if a later
32    /// edit adds them to a way.
33    Database,
34    /// A PBF file, then the diffs after it up to the database's sequence: every node, as an import has it.
35    Pbf {
36        /// The file, which must be sorted by type and ID.
37        path: &'a Path,
38        /// The stream's sequence the file is up to, instead of the one its header gives.
39        sequence: Option<u64>,
40        /// The database's replication stream, which has the diffs.
41        replication: &'a Replication,
42        /// The most diffs applied in one commit.
43        max_diffs: u64,
44    },
45}
46
47/// What a rebuild made.
48#[derive(Debug, Clone, Default, PartialEq, Eq)]
49pub struct RebuildStats {
50    /// Nodes in the node file after loading, before any diffs.
51    pub nodes: u64,
52    /// Diffs applied to the node file.
53    pub diffs: u64,
54    /// (node, way) pairs in the reverse index.
55    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.tables)? {
74                // A node of several ways has the same location in each; one is enough
75                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                // Without the database's identity until the end, so a rebuild cut short is never taken as done
120                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, state.tables)?.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
146/// The node locations the database has, as (ID, packed location), sorted, sorted with temporary files in `dir`.
147fn db_locations(client: &mut Client, dir: &Path, layout: TableLayout) -> Result<Sorted, SyncError> {
148    let sorter = Sorter::new(dir)?;
149    // The ways' points, then the tagged nodes': (kind, ID, node IDs, geometry) rows, every point as stored. Not
150    // through `ST_AsTWKB`, which leaves out a point that repeats the one before it.
151    let geom = match layout {
152        TableLayout::Packed => "geom",
153        TableLayout::Plain => "ST_AsBinary(geom)",
154    };
155    for (is_way, sql) in [
156        (
157            true,
158            format!(
159                "SELECT 'way', id, nodes, {geom} FROM {} WHERE geom IS NOT NULL",
160                Table::Ways.name(layout)
161            ),
162        ),
163        (
164            false,
165            format!(
166                "SELECT 'node', id, id, {geom} FROM {} WHERE geom IS NOT NULL",
167                Table::Nodes.name(layout)
168            ),
169        ),
170    ] {
171        let mut rows = client.query_raw(&sql, iter::empty::<&str>())?;
172        while let Some(row) = rows.next()? {
173            let nodes = if is_way {
174                row.get::<_, NodeIds>(2).0
175            } else {
176                vec![row.get(2)]
177            };
178            let buf: &[u8] = row.get(3);
179            let added = match layout {
180                TableLayout::Packed => {
181                    let g = osm_twkb(buf);
182                    add_locations(&sorter, &nodes, g.as_ref().map(locations))?
183                }
184                TableLayout::Plain => match read_wkb(buf).as_ref().map(|g| g.as_type()) {
185                    Ok(GeometryType::Point(p)) => {
186                        add_locations(&sorter, &nodes, Some(p.coord().iter().map(location)))?
187                    }
188                    Ok(GeometryType::LineString(l)) => {
189                        add_locations(&sorter, &nodes, Some(l.coords().map(|c| location(&c))))?
190                    }
191                    _ => false,
192                },
193            };
194            if !added {
195                let (kind, id): (&str, i64) = (row.get(0), row.get(1));
196                return Err(SyncError::state(format!(
197                    "{kind} {id}: its geometry does not have one point for each of its {} nodes",
198                    nodes.len()
199                )));
200            }
201        }
202    }
203    Ok(sorter.finish()?)
204}
205
206/// Adds each node of `nodes` with its point of `points` to `sorter`; false, adding none, unless there is one point
207/// for each node.
208fn add_locations(
209    sorter: &Sorter,
210    nodes: &[i64],
211    points: Option<impl ExactSizeIterator<Item = Location>>,
212) -> Result<bool, SyncError> {
213    let Some(points) = points.filter(|p| p.len() == nodes.len()) else {
214        return Ok(false);
215    };
216    sorter.extend(
217        nodes
218            .iter()
219            .zip(points)
220            .filter_map(|(&id, l)| Some((u64::try_from(id).ok()?, pack(l)))),
221    )?;
222    Ok(true)
223}
224
225/// The reverse index's pairs, from the ways' node lists in the tables of `tables`, sorted with temporary files in `dir`.
226fn db_pairs(client: &mut Client, dir: &Path, tables: TableLayout) -> Result<Sorted, SyncError> {
227    let sorter = Sorter::new(dir)?;
228    let sql = format!("SELECT id, nodes FROM {}", Table::Ways.name(tables));
229    let mut rows = client.query_raw(&sql, iter::empty::<&str>())?;
230    while let Some(row) = rows.next()? {
231        sorter.extend(way_pairs(row.get(0), &row.get::<_, NodeIds>(1).0))?;
232    }
233    Ok(sorter.finish()?)
234}
235
236/// A WKB coordinate's location.
237fn location(c: &impl CoordTrait<T = f64>) -> Location {
238    Location::from_degrees(c.y(), c.x())
239}
240
241/// A location as one number to sort beside its node ID.
242fn pack(l: Location) -> u64 {
243    (u64::from(l.lat.cast_unsigned()) << 32) | u64::from(l.lon.cast_unsigned())
244}
245
246fn unpack(v: u64) -> Location {
247    let [lat, lon] =
248        [v >> 32, v & 0xffff_ffff].map(|h| u32::try_from(h).unwrap_or_default().cast_signed());
249    Location::new(lat, lon)
250}