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