Skip to main content

osmflow_sync/
update.rs

1//! Updates: replication diffs applied to the database and its files, a batch of diffs per transaction.
2
3use std::collections::{BTreeMap, BTreeSet, HashMap};
4use std::time::Instant;
5
6use osmflow::nodes::PagedStore;
7use osmflow::nodes::prelude::*;
8use osmflow::osc::{self, Action, Change, Object, Replication, StateSource as _};
9use osmflow::{Location, Timestamp};
10use postgres::{Client, Transaction};
11use tracing::{debug, info, warn};
12
13use crate::copy::Rows;
14use crate::db::{self, DbState, Table};
15use crate::files::{read_diffs, set_locations, way_pairs};
16use crate::index::{Pair, ReverseIndex};
17use crate::{OpenMirror, SyncError};
18
19/// How to update.
20#[derive(Debug, Clone)]
21pub struct UpdateOpts {
22    /// The most diffs applied in one transaction, 60 by default. Merged, they cost far less than one at a time, as an
23    /// object changed in several is written once.
24    pub max_diffs: u64,
25    /// The last sequence to apply, instead of the stream's latest.
26    pub until: Option<u64>,
27}
28
29impl Default for UpdateOpts {
30    fn default() -> Self {
31        Self {
32            max_diffs: 60,
33            until: None,
34        }
35    }
36}
37
38/// What an update applied.
39#[derive(Debug, Clone, Default, PartialEq, Eq)]
40pub struct UpdateStats {
41    /// Transactions, each a new revision.
42    pub batches: u64,
43    /// Diffs read.
44    pub diffs: u64,
45    /// Rows of `osm.nodes`, `osm.ways` and `osm.relations` written or deleted.
46    pub rows: u64,
47    /// Ways whose geometry changed only because their nodes did.
48    pub moved_ways: u64,
49    /// The sequence the database is now at.
50    pub sequence: i64,
51}
52
53/// The changes of one or more diffs: of each object, its last version, or that it was deleted.
54#[derive(Debug, Default)]
55pub(crate) struct Changes {
56    nodes: BTreeMap<i64, (bool, osc::Node)>,
57    ways: BTreeMap<i64, (bool, osc::Way)>,
58    relations: BTreeMap<i64, (bool, osc::Relation)>,
59}
60
61impl Changes {
62    pub(crate) fn add(&mut self, changes: Vec<Change>) {
63        for c in changes {
64            let deleted = c.action == Action::Delete;
65            match c.object {
66                Object::Node(n) => self.nodes.insert(n.id, (deleted, n)).map(drop),
67                Object::Way(w) => self.ways.insert(w.id, (deleted, w)).map(drop),
68                Object::Relation(r) => self.relations.insert(r.id, (deleted, r)).map(drop),
69            };
70        }
71    }
72
73    /// Each changed node's new location, or none if it was deleted, in ID order.
74    pub(crate) fn locations(&self) -> impl Iterator<Item = (u64, Option<Location>)> + '_ {
75        self.nodes.iter().filter_map(|(&id, (deleted, n))| {
76            Some((
77                u64::try_from(id).ok()?,
78                if *deleted { None } else { n.location },
79            ))
80        })
81    }
82
83    fn len(&self) -> usize {
84        self.nodes.len() + self.ways.len() + self.relations.len()
85    }
86}
87
88impl OpenMirror {
89    /// Applies the diffs of `replication` after the database's sequence, up to the stream's latest or
90    /// [`UpdateOpts::until`]. The files are checked against the database first, and brought up to it if a crash or an
91    /// earlier error left them behind; a file of another database or ahead of it is an error, as on
92    /// [`Mirror::open`](crate::Mirror::open).
93    pub fn update(
94        &mut self,
95        replication: &Replication,
96        opts: &UpdateOpts,
97    ) -> Result<UpdateStats, SyncError> {
98        let mut state = DbState::read(&mut self.client)?;
99        check_stream(&state, replication)?;
100        self.sync_index(&state)?;
101        // Out of the mirror until every batch succeeds: a failed batch can leave locations in the node file that its
102        // database did not commit, so the file is opened again on the next update
103        let mut store = self.take_node_file(&state, replication)?;
104        if !self.temp_tables {
105            create_temp_tables(&mut self.client)?;
106            self.temp_tables = true;
107        }
108        let total = apply_diffs(
109            &mut self.client,
110            &mut store,
111            &self.index,
112            &mut state,
113            replication,
114            opts,
115        )?;
116        self.store = Some(store);
117        Ok(total)
118    }
119}
120
121/// Applies the diffs after `state`'s sequence in batches, moving `state` along.
122fn apply_diffs(
123    client: &mut Client,
124    store: &mut PagedStore,
125    index: &ReverseIndex,
126    state: &mut DbState,
127    replication: &Replication,
128    opts: &UpdateOpts,
129) -> Result<UpdateStats, SyncError> {
130    let latest = match opts.until {
131        Some(until) => until,
132        None => replication.state()?.sequence,
133    };
134    let mut total = UpdateStats {
135        sequence: state.sequence,
136        ..UpdateStats::default()
137    };
138    let mut next = state.sequence.cast_unsigned() + 1;
139    while next <= latest {
140        let t = Instant::now();
141        let last = latest.min(next + opts.max_diffs.max(1) - 1);
142        let (changes, last_state) = read_diffs(replication, next..=last)?;
143        let read = t.elapsed();
144        let batch = Batch {
145            rev: state.rev + 1,
146            first: next.cast_signed(),
147            last: last.cast_signed(),
148            timestamp: last_state.map(|s| s.timestamp),
149        };
150        let applied = apply(client, store, index, &changes, &batch)?;
151        info!(
152            rev = batch.rev,
153            sequences = format!("{next}..={last}"),
154            changes = changes.len(),
155            rows = applied.rows,
156            moved_ways = applied.moved_ways,
157            read_secs = read.as_secs_f32(),
158            secs = t.elapsed().as_secs_f32(),
159            "applied a batch"
160        );
161        state.rev = batch.rev;
162        total.batches += 1;
163        total.diffs += last + 1 - next;
164        total.rows += applied.rows;
165        total.moved_ways += applied.moved_ways;
166        total.sequence = batch.last;
167        next = last + 1;
168    }
169    Ok(total)
170}
171
172/// Checks that `replication` is the database's stream: its diff at the database's sequence has the database's time.
173/// A stream without that diff's state, such as a directory of only the diffs after it, cannot be checked: a warning,
174/// unless the stream ends before it.
175pub(crate) fn check_stream(state: &DbState, replication: &Replication) -> Result<(), SyncError> {
176    let Some(time) = state.timestamp else {
177        return Ok(());
178    };
179    let sequence = state.sequence.cast_unsigned();
180    let Some(theirs) = replication.get(sequence)? else {
181        let latest = replication.state()?.sequence;
182        if latest < sequence {
183            return Err(SyncError::state(format!(
184                "the replication stream ends at diff {latest}, before the database's {sequence}: it is not the \
185                 database's stream, {}",
186                state.url.as_deref().unwrap_or("which it does not name")
187            )));
188        }
189        warn!(
190            "the replication stream has no state of diff {sequence}, the database's, so it cannot be checked to be \
191             the database's stream"
192        );
193        return Ok(());
194    };
195    if theirs.timestamp == time {
196        Ok(())
197    } else {
198        Err(SyncError::state(format!(
199            "the replication stream's diff {sequence} is at {}, but the database's is at {time}: the stream is \
200             not the database's, {}",
201            theirs.timestamp,
202            state.url.as_deref().unwrap_or("which it does not name")
203        )))
204    }
205}
206
207/// One transaction's place in the stream.
208struct Batch {
209    rev: i64,
210    first: i64,
211    last: i64,
212    timestamp: Option<Timestamp>,
213}
214
215/// Rows to write into a table, and IDs to delete from it.
216#[derive(Default)]
217struct Writes {
218    rows: Rows,
219    written: Vec<i64>,
220    deleted: Vec<i64>,
221}
222
223/// What a batch writes into the database, and changes in the reverse index.
224#[derive(Default)]
225struct Plan {
226    nodes: Writes,
227    ways: Writes,
228    relations: Writes,
229    /// The new geometries of the ways whose nodes moved but which did not change themselves.
230    geoms: Rows,
231    moved_ways: Vec<i64>,
232    remove: Vec<Pair>,
233    add: Vec<Pair>,
234}
235
236/// Applies `changes` as revision `batch.rev`: the database in one transaction, then the node file and the index.
237fn apply(
238    client: &mut Client,
239    store: &mut PagedStore,
240    index: &ReverseIndex,
241    changes: &Changes,
242    batch: &Batch,
243) -> Result<UpdateStats, SyncError> {
244    let t = Instant::now();
245    let moved = set_locations(store, changes)?;
246    let through = index.ways_of(moved.iter().copied())?;
247    // The node lists of the changed ways, and of the ways the index says pass through a moved node
248    let mut ids: Vec<i64> = changes
249        .ways
250        .keys()
251        .copied()
252        .chain(through.iter().map(|p| p.1.cast_signed()))
253        .collect();
254    ids.sort_unstable();
255    ids.dedup();
256    let old: HashMap<i64, Vec<i64>> = client
257        .query("SELECT id, nodes FROM osm.ways WHERE id = ANY($1)", &[&ids])?
258        .into_iter()
259        .map(|r| (r.get(0), r.get(1)))
260        .collect();
261    let read = t.elapsed();
262    let plan = plan(store, changes, &through, &old, batch.rev);
263    let planned = t.elapsed();
264    let rows = write(client, changes, &plan, batch)?;
265    let written = t.elapsed();
266    // The database is committed; the files follow it, and catch up on the next start if a crash comes first
267    store.commit(batch.rev.cast_unsigned())?;
268    index.apply(&plan.remove, &plan.add, batch.rev)?;
269    debug!(
270        moved_nodes = moved.len(),
271        read_secs = read.as_secs_f32(),
272        encode_secs = planned.saturating_sub(read).as_secs_f32(),
273        db_secs = written.saturating_sub(planned).as_secs_f32(),
274        files_secs = t.elapsed().saturating_sub(written).as_secs_f32(),
275        "batch steps"
276    );
277    Ok(UpdateStats {
278        rows,
279        moved_ways: plan.moved_ways.len() as u64,
280        ..UpdateStats::default()
281    })
282}
283
284/// Encodes the rows of `changes`, given the ways the index found through the moved nodes and the old node lists of
285/// those and of the changed ways.
286fn plan(
287    store: &PagedStore,
288    changes: &Changes,
289    through: &[Pair],
290    old: &HashMap<i64, Vec<i64>>,
291    rev: i64,
292) -> Plan {
293    let mut plan = Plan::default();
294    for (&id, (deleted, w)) in &changes.ways {
295        if let Some(nodes) = old.get(&id) {
296            plan.remove.extend(way_pairs(id, nodes));
297        }
298        if !deleted {
299            plan.add.extend(way_pairs(id, &w.refs));
300        }
301    }
302    // Ways through a moved node that did not change themselves; an outdated entry of the index is dropped
303    let mut moved_ways = BTreeSet::new();
304    for &(node, way) in through {
305        let id = way.cast_signed();
306        match old.get(&id) {
307            _ if changes.ways.contains_key(&id) => {}
308            Some(nodes) if nodes.contains(&node.cast_signed()) => {
309                moved_ways.insert(id);
310            }
311            _ => plan.remove.push((node, way)),
312        }
313    }
314    for pairs in [&mut plan.remove, &mut plan.add] {
315        pairs.sort_unstable();
316        pairs.dedup();
317    }
318
319    let mut reader = store.reader();
320    let mut locs = Vec::new();
321    for (&id, (deleted, n)) in &changes.nodes {
322        if *deleted || n.tags.is_empty() {
323            plan.nodes.deleted.push(id);
324        } else {
325            plan.nodes.written.push(id);
326            plan.nodes
327                .rows
328                .node(id, (&n.meta).into(), rev, n.tags.iter(), n.location);
329        }
330    }
331    for (&id, (deleted, w)) in &changes.ways {
332        if *deleted {
333            plan.ways.deleted.push(id);
334        } else {
335            plan.ways.written.push(id);
336            let complete = locate(&mut reader, &w.refs, &mut locs);
337            let line = complete.then_some(&locs[..]);
338            let nodes = w.refs.iter().copied();
339            plan.ways
340                .rows
341                .way(id, (&w.meta).into(), rev, w.tags.iter(), nodes, line);
342        }
343    }
344    for &id in &moved_ways {
345        let complete = locate(&mut reader, &old[&id], &mut locs);
346        plan.geoms
347            .row(2)
348            .i64(id)
349            .line(complete.then_some(&locs[..]));
350    }
351    plan.moved_ways = moved_ways.into_iter().collect();
352    for (&id, (deleted, r)) in &changes.relations {
353        if *deleted {
354            plan.relations.deleted.push(id);
355        } else {
356            plan.relations.written.push(id);
357            let members: Vec<_> = r.members().collect();
358            plan.relations
359                .rows
360                .relation(id, (&r.meta).into(), rev, r.tags.iter(), &members);
361        }
362    }
363    plan
364}
365
366/// Writes `plan` into the database in one transaction, with the change log and the new state; returns the rows
367/// written and deleted.
368fn write(
369    client: &mut Client,
370    changes: &Changes,
371    plan: &Plan,
372    batch: &Batch,
373) -> Result<u64, SyncError> {
374    let rev = batch.rev;
375    let mut tx = client.transaction()?;
376    let mut log = Rows::default();
377    let mut rows = 0;
378    for (table, kind, w) in [
379        (Table::Nodes, b'n', &plan.nodes),
380        (Table::Ways, b'w', &plan.ways),
381        (Table::Relations, b'r', &plan.relations),
382    ] {
383        let gone = if w.deleted.is_empty() {
384            Vec::new()
385        } else {
386            tx.query(
387                &format!(
388                    "DELETE FROM {} WHERE id = ANY($1) RETURNING id",
389                    table.name()
390                ),
391                &[&w.deleted],
392            )?
393        };
394        for row in &gone {
395            log.row(4).i64(rev).char(kind).i64(row.get(0)).char(b'd');
396        }
397        upsert(&mut tx, table, &w.rows)?;
398        for &id in &w.written {
399            log.row(4).i64(rev).char(kind).i64(id).char(b'u');
400        }
401        rows += gone.len() as u64 + w.rows.count;
402    }
403    if plan.geoms.count > 0 {
404        db::copy(&mut tx, "osm_geoms", "id, geom", &plan.geoms)?;
405        tx.execute(
406            "UPDATE osm.ways w SET geom = g.geom, minor = w.minor + 1, rev = $1 FROM osm_geoms g WHERE w.id = g.id",
407            &[&rev],
408        )?;
409        for &id in &plan.moved_ways {
410            log.row(4).i64(rev).char(b'w').i64(id).char(b'g');
411        }
412    }
413    if log.count > 0 {
414        db::copy(&mut tx, "osm.changes", "rev, kind, id, action", &log)?;
415    }
416    let timestamp = batch.timestamp.map(Timestamp::as_millis);
417    let count = |n: usize| i64::try_from(n).unwrap_or(i64::MAX);
418    tx.execute(
419        "INSERT INTO osm.batches (rev, first_sequence, last_sequence, timestamp, nodes, ways, relations) \
420         VALUES ($1, $2, $3, to_timestamp($4::int8 / 1000.0), $5, $6, $7)",
421        &[
422            &rev,
423            &batch.first,
424            &batch.last,
425            &timestamp,
426            &count(changes.nodes.len()),
427            &count(changes.ways.len()),
428            &count(changes.relations.len()),
429        ],
430    )?;
431    tx.execute(
432        "UPDATE osm.state SET rev = $1, sequence = $2, timestamp = to_timestamp($3::int8 / 1000.0)",
433        &[&rev, &batch.last, &timestamp],
434    )?;
435    tx.commit()?;
436    Ok(rows)
437}
438
439/// Creates the session's temporary tables that each batch copies its rows into, emptied at every commit.
440fn create_temp_tables(client: &mut Client) -> Result<(), SyncError> {
441    let tables = [Table::Nodes, Table::Ways, Table::Relations].map(|t| {
442        format!(
443            "CREATE TEMP TABLE {} (LIKE {}) ON COMMIT DELETE ROWS;",
444            temp_name(t),
445            t.name()
446        )
447    });
448    client.batch_execute(&format!(
449        "CREATE TEMP TABLE osm_geoms (id int8, geom geometry(LineString, 4326)) ON COMMIT DELETE ROWS; {}",
450        tables.concat()
451    ))?;
452    Ok(())
453}
454
455/// The temporary table rows of `table` are copied into.
456fn temp_name(table: Table) -> String {
457    table.name().replace('.', "_")
458}
459
460/// Writes `rows` of `table` over the rows with their IDs, or as new rows: copied into its temporary table, then
461/// merged.
462fn upsert(tx: &mut Transaction<'_>, table: Table, rows: &Rows) -> Result<(), SyncError> {
463    if rows.count == 0 {
464        return Ok(());
465    }
466    let (name, columns, tmp) = (table.name(), table.columns(), temp_name(table));
467    let list = columns.join(", ");
468    let set = columns[1..]
469        .iter()
470        .map(|c| format!("{c} = EXCLUDED.{c}"))
471        .collect::<Vec<_>>()
472        .join(", ");
473    db::copy(tx, &tmp, &list, rows)?;
474    tx.execute(&format!("INSERT INTO {name} ({list}) SELECT {list} FROM {tmp} ON CONFLICT (id) DO UPDATE SET {set}"), &[])?;
475    Ok(())
476}
477
478/// Puts the locations of `refs` in `locs`; false if one is missing.
479fn locate(reader: &mut impl NodeReader, refs: &[i64], locs: &mut Vec<Location>) -> bool {
480    locs.clear();
481    refs.iter().all(|&r| {
482        u64::try_from(r)
483            .ok()
484            .and_then(|r| reader.get(r))
485            .map(|l| locs.push(l))
486            .is_some()
487    })
488}