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, 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            geometry: state.geometry,
150        };
151        let applied = apply(client, store, index, &changes, &batch)?;
152        info!(
153            rev = batch.rev,
154            sequences = format!("{next}..={last}"),
155            changes = changes.len(),
156            rows = applied.rows,
157            moved_ways = applied.moved_ways,
158            read_secs = read.as_secs_f32(),
159            secs = t.elapsed().as_secs_f32(),
160            "applied a batch"
161        );
162        state.rev = batch.rev;
163        total.batches += 1;
164        total.diffs += last + 1 - next;
165        total.rows += applied.rows;
166        total.moved_ways += applied.moved_ways;
167        total.sequence = batch.last;
168        next = last + 1;
169    }
170    Ok(total)
171}
172
173/// Checks that `replication` is the database's stream: its diff at the database's sequence has the database's time.
174/// A stream without that diff's state, such as a directory of only the diffs after it, cannot be checked: a warning,
175/// unless the stream ends before it.
176pub(crate) fn check_stream(state: &DbState, replication: &Replication) -> Result<(), SyncError> {
177    let Some(time) = state.timestamp else {
178        return Ok(());
179    };
180    let sequence = state.sequence.cast_unsigned();
181    let Some(theirs) = replication.get(sequence)? else {
182        let latest = replication.state()?.sequence;
183        if latest < sequence {
184            return Err(SyncError::state(format!(
185                "the replication stream ends at diff {latest}, before the database's {sequence}: it is not the \
186                 database's stream, {}",
187                state.url.as_deref().unwrap_or("which it does not name")
188            )));
189        }
190        warn!(
191            "the replication stream has no state of diff {sequence}, the database's, so it cannot be checked to be \
192             the database's stream"
193        );
194        return Ok(());
195    };
196    if theirs.timestamp == time {
197        Ok(())
198    } else {
199        Err(SyncError::state(format!(
200            "the replication stream's diff {sequence} is at {}, but the database's is at {time}: the stream is \
201             not the database's, {}",
202            theirs.timestamp,
203            state.url.as_deref().unwrap_or("which it does not name")
204        )))
205    }
206}
207
208/// One transaction's place in the stream.
209struct Batch {
210    rev: i64,
211    first: i64,
212    last: i64,
213    timestamp: Option<Timestamp>,
214    geometry: GeometryFormat,
215}
216
217/// Rows to write into a table, and IDs to delete from it.
218#[derive(Default)]
219struct Writes {
220    rows: Rows,
221    written: Vec<i64>,
222    deleted: Vec<i64>,
223}
224
225/// What a batch writes into the database, and changes in the reverse index.
226#[derive(Default)]
227struct Plan {
228    nodes: Writes,
229    ways: Writes,
230    relations: Writes,
231    /// The new geometries of the ways whose nodes moved but which did not change themselves.
232    geoms: Rows,
233    moved_ways: Vec<i64>,
234    remove: Vec<Pair>,
235    add: Vec<Pair>,
236}
237
238/// Applies `changes` as revision `batch.rev`: the database in one transaction, then the node file and the index.
239fn apply(
240    client: &mut Client,
241    store: &mut PagedStore,
242    index: &ReverseIndex,
243    changes: &Changes,
244    batch: &Batch,
245) -> Result<UpdateStats, SyncError> {
246    let t = Instant::now();
247    let moved = set_locations(store, changes)?;
248    let through = index.ways_of(moved.iter().copied())?;
249    // The node lists of the changed ways, and of the ways the index says pass through a moved node
250    let mut ids: Vec<i64> = changes
251        .ways
252        .keys()
253        .copied()
254        .chain(through.iter().map(|p| p.1.cast_signed()))
255        .collect();
256    ids.sort_unstable();
257    ids.dedup();
258    let old: HashMap<i64, Vec<i64>> = client
259        .query("SELECT id, nodes FROM osm.ways WHERE id = ANY($1)", &[&ids])?
260        .into_iter()
261        .map(|r| (r.get(0), r.get(1)))
262        .collect();
263    let read = t.elapsed();
264    let plan = plan(store, changes, &through, &old, batch);
265    let planned = t.elapsed();
266    let rows = write(client, changes, &plan, batch)?;
267    let written = t.elapsed();
268    // The database is committed; the files follow it, and catch up on the next start if a crash comes first
269    store.commit(batch.rev.cast_unsigned())?;
270    index.apply(&plan.remove, &plan.add, batch.rev)?;
271    debug!(
272        moved_nodes = moved.len(),
273        read_secs = read.as_secs_f32(),
274        encode_secs = planned.saturating_sub(read).as_secs_f32(),
275        db_secs = written.saturating_sub(planned).as_secs_f32(),
276        files_secs = t.elapsed().saturating_sub(written).as_secs_f32(),
277        "batch steps"
278    );
279    Ok(UpdateStats {
280        rows,
281        moved_ways: plan.moved_ways.len() as u64,
282        ..UpdateStats::default()
283    })
284}
285
286/// Encodes the rows of `changes`, given the ways the index found through the moved nodes and the old node lists of
287/// those and of the changed ways.
288fn plan(
289    store: &PagedStore,
290    changes: &Changes,
291    through: &[Pair],
292    old: &HashMap<i64, Vec<i64>>,
293    batch: &Batch,
294) -> Plan {
295    let (rev, format) = (batch.rev, batch.geometry);
296    let mut plan = Plan::default();
297    plan.nodes.rows = Rows::new(format);
298    plan.ways.rows = Rows::new(format);
299    plan.geoms = Rows::new(format);
300    for (&id, (deleted, w)) in &changes.ways {
301        if let Some(nodes) = old.get(&id) {
302            plan.remove.extend(way_pairs(id, nodes));
303        }
304        if !deleted {
305            plan.add.extend(way_pairs(id, &w.refs));
306        }
307    }
308    // Ways through a moved node that did not change themselves; an outdated entry of the index is dropped
309    let mut moved_ways = BTreeSet::new();
310    for &(node, way) in through {
311        let id = way.cast_signed();
312        match old.get(&id) {
313            _ if changes.ways.contains_key(&id) => {}
314            Some(nodes) if nodes.contains(&node.cast_signed()) => {
315                moved_ways.insert(id);
316            }
317            _ => plan.remove.push((node, way)),
318        }
319    }
320    for pairs in [&mut plan.remove, &mut plan.add] {
321        pairs.sort_unstable();
322        pairs.dedup();
323    }
324
325    let mut reader = store.reader();
326    let mut locs = Vec::new();
327    for (&id, (deleted, n)) in &changes.nodes {
328        if *deleted || n.tags.is_empty() {
329            plan.nodes.deleted.push(id);
330        } else {
331            plan.nodes.written.push(id);
332            plan.nodes
333                .rows
334                .node(id, (&n.meta).into(), rev, n.tags.iter(), n.location);
335        }
336    }
337    for (&id, (deleted, w)) in &changes.ways {
338        if *deleted {
339            plan.ways.deleted.push(id);
340        } else {
341            plan.ways.written.push(id);
342            let complete = locate(&mut reader, &w.refs, &mut locs);
343            let line = complete.then_some(&locs[..]);
344            let nodes = w.refs.iter().copied();
345            plan.ways
346                .rows
347                .way(id, (&w.meta).into(), rev, w.tags.iter(), nodes, line);
348        }
349    }
350    for &id in &moved_ways {
351        let complete = locate(&mut reader, &old[&id], &mut locs);
352        plan.geoms
353            .row(2)
354            .i64(id)
355            .line(complete.then_some(&locs[..]));
356    }
357    plan.moved_ways = moved_ways.into_iter().collect();
358    for (&id, (deleted, r)) in &changes.relations {
359        if *deleted {
360            plan.relations.deleted.push(id);
361        } else {
362            plan.relations.written.push(id);
363            plan.relations
364                .rows
365                .relation(id, (&r.meta).into(), rev, r.tags.iter(), r.members());
366        }
367    }
368    plan
369}
370
371/// Writes `plan` into the database in one transaction, with the change log and the new state; returns the rows
372/// written and deleted.
373fn write(
374    client: &mut Client,
375    changes: &Changes,
376    plan: &Plan,
377    batch: &Batch,
378) -> Result<u64, SyncError> {
379    let rev = batch.rev;
380    let mut tx = client.transaction()?;
381    let mut log = Rows::default();
382    let mut rows = 0;
383    for (table, kind, w) in [
384        (Table::Nodes, b'n', &plan.nodes),
385        (Table::Ways, b'w', &plan.ways),
386        (Table::Relations, b'r', &plan.relations),
387    ] {
388        let gone = if w.deleted.is_empty() {
389            Vec::new()
390        } else {
391            tx.query(
392                &format!("DELETE FROM {table} WHERE id = ANY($1) RETURNING id"),
393                &[&w.deleted],
394            )?
395        };
396        for row in &gone {
397            log.row(4).i64(rev).char(kind).i64(row.get(0)).char(b'd');
398        }
399        upsert(&mut tx, table, &w.rows)?;
400        for &id in &w.written {
401            log.row(4).i64(rev).char(kind).i64(id).char(b'u');
402        }
403        rows += gone.len() as u64 + w.rows.count;
404    }
405    if plan.geoms.count > 0 {
406        db::copy(&mut tx, "osm_geoms", "id, geom", &plan.geoms)?;
407        tx.execute(
408            "UPDATE osm.ways w SET geom = g.geom, minor = w.minor + 1, rev = $1 FROM osm_geoms g WHERE w.id = g.id",
409            &[&rev],
410        )?;
411        for &id in &plan.moved_ways {
412            log.row(4).i64(rev).char(b'w').i64(id).char(b'g');
413        }
414    }
415    if log.count > 0 {
416        db::copy(&mut tx, "osm.changes", "rev, kind, id, action", &log)?;
417    }
418    let timestamp = batch.timestamp.map(Timestamp::as_millis);
419    let count = |n: usize| i64::try_from(n).unwrap_or(i64::MAX);
420    tx.execute(
421        "INSERT INTO osm.batches (rev, first_sequence, last_sequence, timestamp, nodes, ways, relations) \
422         VALUES ($1, $2, $3, to_timestamp($4::int8 / 1000.0), $5, $6, $7)",
423        &[
424            &rev,
425            &batch.first,
426            &batch.last,
427            &timestamp,
428            &count(changes.nodes.len()),
429            &count(changes.ways.len()),
430            &count(changes.relations.len()),
431        ],
432    )?;
433    tx.execute(
434        "UPDATE osm.state SET rev = $1, sequence = $2, timestamp = to_timestamp($3::int8 / 1000.0)",
435        &[&rev, &batch.last, &timestamp],
436    )?;
437    tx.commit()?;
438    Ok(rows)
439}
440
441/// Creates the session's temporary tables that each batch copies its rows into, emptied at every commit.
442fn create_temp_tables(client: &mut Client) -> Result<(), SyncError> {
443    let tables = [Table::Nodes, Table::Ways, Table::Relations].map(|t| {
444        format!(
445            "CREATE TEMP TABLE {} (LIKE {t}) ON COMMIT DELETE ROWS;",
446            temp_name(t)
447        )
448    });
449    client.batch_execute(&format!(
450        "CREATE TEMP TABLE osm_geoms ON COMMIT DELETE ROWS AS SELECT id, geom FROM osm.ways WITH NO DATA; {}",
451        tables.concat()
452    ))?;
453    Ok(())
454}
455
456/// The temporary table rows of `table` are copied into.
457fn temp_name(table: Table) -> String {
458    <&str>::from(table).replace('.', "_")
459}
460
461/// Writes `rows` of `table` over the rows with their IDs, or as new rows: copied into its temporary table, then
462/// merged.
463fn upsert(tx: &mut Transaction<'_>, table: Table, rows: &Rows) -> Result<(), SyncError> {
464    if rows.count == 0 {
465        return Ok(());
466    }
467    let (list, tmp) = (table.columns(), temp_name(table));
468    // Every column but `id`, set to the new row's
469    let rest = list.strip_prefix("id, ").unwrap_or(list);
470    let new = rest.replace(", ", ", EXCLUDED.");
471    db::copy(tx, &tmp, list, rows)?;
472    tx.execute(&format!("INSERT INTO {table} ({list}) SELECT {list} FROM {tmp} ON CONFLICT (id) DO UPDATE SET ({rest}) = ROW(EXCLUDED.{new})"), &[])?;
473    Ok(())
474}
475
476/// Puts the locations of `refs` in `locs`; false if one is missing.
477fn locate(reader: &mut impl NodeReader, refs: &[i64], locs: &mut Vec<Location>) -> bool {
478    locs.clear();
479    refs.iter().all(|&r| {
480        u64::try_from(r)
481            .ok()
482            .and_then(|r| reader.get(r))
483            .map(|l| locs.push(l))
484            .is_some()
485    })
486}