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 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/// Where [`Mirror::rebuild`] takes node locations from. The reverse index is always made from the database's ways.
24#[derive(Clone, Copy)]
25pub enum Rebuild<'a> {
26    /// The database: the points of the ways' geometries, and the tagged nodes. Nodes in no way with a geometry
27    /// and without tags are not in the database, so they are missing from the new file; they matter only if a later
28    /// edit adds them to a way.
29    Database,
30    /// A PBF file, then the diffs after it up to the database's sequence: every node, as an import has it.
31    Pbf {
32        /// The file, which must be sorted by type and ID.
33        path: &'a Path,
34        /// The stream's sequence the file is up to, instead of the one its header gives.
35        sequence: Option<u64>,
36        /// The database's replication stream, which has the diffs.
37        replication: &'a Replication,
38        /// The most diffs applied in one commit.
39        max_diffs: u64,
40    },
41}
42
43/// What a rebuild made.
44#[derive(Debug, Clone, Default, PartialEq, Eq)]
45pub struct RebuildStats {
46    /// Nodes in the node file after loading, before any diffs.
47    pub nodes: u64,
48    /// Diffs applied to the node file.
49    pub diffs: u64,
50    /// (node, way) pairs in the reverse index.
51    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                // A node of several ways has the same location in each; one is enough
71                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                // Without the database's identity until the end, so a rebuild cut short is never taken as done
116                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
142/// The node locations the database has, as (ID, packed location), sorted, sorted with temporary files in `dir`.
143fn db_locations(client: &mut Client, dir: &Path) -> Result<Sorted, SyncError> {
144    let sorter = Sorter::new(dir)?;
145    // The ways' points, then the tagged nodes': (node IDs, WKB) rows
146    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
165/// The reverse index's pairs, from the ways' node lists, sorted with temporary files in `dir`.
166fn 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
175/// A location as one number to sort beside its node ID.
176fn 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}