1use 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, Stop, StopReason, SyncError, TableLayout};
18
19#[derive(Debug, Clone)]
21pub struct UpdateOpts {
22 pub max_diffs: u64,
25 pub until: Option<u64>,
27 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
44pub struct UpdateStats {
45 pub batches: u64,
47 pub diffs: u64,
49 pub rows: u64,
51 pub moved_ways: u64,
53 pub sequence: i64,
55 pub stopped: Option<StopReason>,
58}
59
60impl UpdateStats {
61 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#[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 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 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 let mut store = self.take_node_file(&state, replication)?;
123 if !self.temp_tables {
124 create_temp_tables(&mut self.client, state.tables)?;
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
140fn 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: i32::try_from(state.rev + 1)
169 .map_err(|_| SyncError::state("the database's revisions are used up"))?,
170 first: next.cast_signed(),
171 last: last.cast_signed(),
172 timestamp: last_state.map(|s| s.timestamp),
173 tables: state.tables,
174 };
175 let applied = apply(client, store, index, &changes, &batch)?;
176 info!(
177 rev = batch.rev,
178 sequences = format!("{next}..={last}"),
179 changes = changes.len(),
180 rows = applied.rows,
181 moved_ways = applied.moved_ways,
182 read_secs = read.as_secs_f32(),
183 secs = t.elapsed().as_secs_f32(),
184 "applied a batch"
185 );
186 state.rev = batch.rev.into();
187 total.batches += 1;
188 total.diffs += last + 1 - next;
189 total.rows += applied.rows;
190 total.moved_ways += applied.moved_ways;
191 total.sequence = batch.last;
192 next = last + 1;
193 }
194 Ok(total)
195}
196
197pub(crate) fn batch_end(next: u64, latest: u64, max_diffs: u64) -> u64 {
199 latest.min(next + max_diffs.max(1) - 1)
200}
201
202pub(crate) fn check_stream(state: &DbState, replication: &Replication) -> Result<(), SyncError> {
206 let Some(time) = state.timestamp else {
207 return Ok(());
208 };
209 let sequence = state.sequence.cast_unsigned();
210 let Some(theirs) = replication.get(sequence)? else {
211 let latest = replication.state()?.sequence;
212 if latest < sequence {
213 return Err(SyncError::state(format!(
214 "the replication stream ends at diff {latest}, before the database's {sequence}: it is not the \
215 database's stream, {}",
216 state.url.as_deref().unwrap_or("which it does not name")
217 )));
218 }
219 warn!(
220 "the replication stream has no state of diff {sequence}, the database's, so it cannot be checked to be \
221 the database's stream"
222 );
223 return Ok(());
224 };
225 if theirs.timestamp == time {
226 Ok(())
227 } else {
228 Err(SyncError::state(format!(
229 "the replication stream's diff {sequence} is at {}, but the database's is at {time}: the stream is \
230 not the database's, {}",
231 theirs.timestamp,
232 state.url.as_deref().unwrap_or("which it does not name")
233 )))
234 }
235}
236
237struct Batch {
239 rev: i32,
240 first: i64,
241 last: i64,
242 timestamp: Option<Timestamp>,
243 tables: TableLayout,
244}
245
246#[derive(Default)]
248struct Writes {
249 rows: Rows,
250 written: Vec<i64>,
251 deleted: Vec<i64>,
252}
253
254#[derive(Default)]
256struct Plan {
257 nodes: Writes,
258 ways: Writes,
259 relations: Writes,
260 geoms: Rows,
262 moved_ways: Vec<i64>,
263 remove: Vec<Pair>,
264 add: Vec<Pair>,
265}
266
267fn apply(
269 client: &mut Client,
270 store: &mut PagedStore,
271 index: &ReverseIndex,
272 changes: &Changes,
273 batch: &Batch,
274) -> Result<UpdateStats, SyncError> {
275 let t = Instant::now();
276 let moved = set_locations(store, changes)?;
277 let through = index.ways_of(moved.iter().copied())?;
278 let mut ids: Vec<i64> = changes
280 .ways
281 .keys()
282 .copied()
283 .chain(through.iter().map(|p| p.1.cast_signed()))
284 .collect();
285 ids.sort_unstable();
286 ids.dedup();
287 let tables = batch.tables;
288 let old: HashMap<i64, Vec<i64>> = client
290 .query(
291 &format!(
292 "SELECT id, nodes FROM {} WHERE id = ANY($1)",
293 Table::Ways.name(tables)
294 ),
295 &[&ids],
296 )?
297 .iter()
298 .map(|r| (r.get(0), tables.node_ids(r, 1)))
299 .collect();
300 let read = t.elapsed();
301 let plan = plan(store, changes, &through, &old, batch);
302 let planned = t.elapsed();
303 let rows = write(client, changes, &plan, batch)?;
304 let written = t.elapsed();
305 store.commit(u64::from(batch.rev.cast_unsigned()))?;
307 index.apply(&plan.remove, &plan.add, batch.rev.into())?;
308 debug!(
309 moved_nodes = moved.len(),
310 read_secs = read.as_secs_f32(),
311 encode_secs = planned.saturating_sub(read).as_secs_f32(),
312 db_secs = written.saturating_sub(planned).as_secs_f32(),
313 files_secs = t.elapsed().saturating_sub(written).as_secs_f32(),
314 "batch steps"
315 );
316 Ok(UpdateStats {
317 rows,
318 moved_ways: plan.moved_ways.len() as u64,
319 ..UpdateStats::default()
320 })
321}
322
323fn plan(
326 store: &PagedStore,
327 changes: &Changes,
328 through: &[Pair],
329 old: &HashMap<i64, Vec<i64>>,
330 batch: &Batch,
331) -> Plan {
332 let (rev, layout) = (batch.rev, batch.tables);
333 let mut plan = Plan::default();
334 plan.nodes.rows = Rows::new(layout);
335 plan.ways.rows = Rows::new(layout);
336 plan.geoms = Rows::new(layout);
337 for (&id, (deleted, w)) in &changes.ways {
338 if let Some(nodes) = old.get(&id) {
339 plan.remove.extend(way_pairs(id, nodes));
340 }
341 if !deleted {
342 plan.add.extend(way_pairs(id, &w.refs));
343 }
344 }
345 let mut moved_ways = BTreeSet::new();
347 for &(node, way) in through {
348 let id = way.cast_signed();
349 match old.get(&id) {
350 _ if changes.ways.contains_key(&id) => {}
351 Some(nodes) if nodes.contains(&node.cast_signed()) => {
352 moved_ways.insert(id);
353 }
354 _ => plan.remove.push((node, way)),
355 }
356 }
357 for pairs in [&mut plan.remove, &mut plan.add] {
358 pairs.sort_unstable();
359 pairs.dedup();
360 }
361
362 let mut reader = store.reader();
363 let mut locs = Vec::new();
364 for (&id, (deleted, n)) in &changes.nodes {
365 if *deleted || n.tags.is_empty() {
366 plan.nodes.deleted.push(id);
367 } else {
368 plan.nodes.written.push(id);
369 plan.nodes
370 .rows
371 .node(id, (&n.meta).into(), rev, n.tags.iter(), n.location);
372 }
373 }
374 for (&id, (deleted, w)) in &changes.ways {
375 if *deleted {
376 plan.ways.deleted.push(id);
377 } else {
378 plan.ways.written.push(id);
379 let complete = locate(&mut reader, &w.refs, &mut locs);
380 let line = complete.then_some(&locs[..]);
381 let nodes = w.refs.iter().copied();
382 plan.ways
383 .rows
384 .way(id, (&w.meta).into(), rev, w.tags.iter(), nodes, line);
385 }
386 }
387 for &id in &moved_ways {
388 let complete = locate(&mut reader, &old[&id], &mut locs);
389 plan.geoms
390 .row(2)
391 .i64(id)
392 .line(complete.then_some(&locs[..]));
393 }
394 plan.moved_ways = moved_ways.into_iter().collect();
395 for (&id, (deleted, r)) in &changes.relations {
396 if *deleted {
397 plan.relations.deleted.push(id);
398 } else {
399 plan.relations.written.push(id);
400 plan.relations
401 .rows
402 .relation(id, (&r.meta).into(), rev, r.tags.iter(), r.members());
403 }
404 }
405 plan
406}
407
408fn write(
411 client: &mut Client,
412 changes: &Changes,
413 plan: &Plan,
414 batch: &Batch,
415) -> Result<u64, SyncError> {
416 let (rev, layout) = (batch.rev, batch.tables);
417 let mut tx = client.transaction()?;
418 let mut log = Rows::default();
419 let mut rows = 0;
420 for (table, kind, w) in [
421 (Table::Nodes, b'n', &plan.nodes),
422 (Table::Ways, b'w', &plan.ways),
423 (Table::Relations, b'r', &plan.relations),
424 ] {
425 let gone = if w.deleted.is_empty() {
426 Vec::new()
427 } else {
428 tx.query(
429 &format!(
430 "DELETE FROM {} WHERE id = ANY($1) RETURNING id",
431 table.name(layout)
432 ),
433 &[&w.deleted],
434 )?
435 };
436 for row in &gone {
437 log.row(4).i64(row.get(0)).i32(rev).char(kind).char(b'd');
438 }
439 upsert(&mut tx, table, layout, &w.rows)?;
440 for &id in &w.written {
441 log.row(4).i64(id).i32(rev).char(kind).char(b'u');
442 }
443 rows += gone.len() as u64 + w.rows.count;
444 }
445 if plan.geoms.count > 0 {
446 db::copy(&mut tx, "osm_geoms", "id, geom", &plan.geoms)?;
447 tx.execute(
448 &format!(
449 "UPDATE {} w SET geom = g.geom, minor = w.minor + 1, rev = $1 FROM osm_geoms g WHERE w.id = g.id",
450 Table::Ways.name(layout)
451 ),
452 &[&rev],
453 )?;
454 for &id in &plan.moved_ways {
455 log.row(4).i64(id).i32(rev).char(b'w').char(b'g');
456 }
457 }
458 if log.count > 0 {
459 db::copy(&mut tx, "osm.changes", "id, rev, kind, action", &log)?;
460 }
461 let timestamp = batch.timestamp.map(Timestamp::as_millis);
462 let count = |n: usize| i64::try_from(n).unwrap_or(i64::MAX);
463 tx.execute(
464 "INSERT INTO osm.batches (rev, first_sequence, last_sequence, timestamp, nodes, ways, relations) \
465 VALUES ($1, $2, $3, to_timestamp($4::int8 / 1000.0), $5, $6, $7)",
466 &[
467 &rev,
468 &batch.first,
469 &batch.last,
470 ×tamp,
471 &count(changes.nodes.len()),
472 &count(changes.ways.len()),
473 &count(changes.relations.len()),
474 ],
475 )?;
476 tx.execute(
477 "UPDATE osm.state SET rev = $1, sequence = $2, timestamp = to_timestamp($3::int8 / 1000.0)",
478 &[&rev, &batch.last, ×tamp],
479 )?;
480 tx.commit()?;
481 Ok(rows)
482}
483
484fn create_temp_tables(client: &mut Client, layout: TableLayout) -> Result<(), SyncError> {
486 let tables = [Table::Nodes, Table::Ways, Table::Relations].map(|t| {
487 format!(
488 "CREATE TEMP TABLE {} (LIKE {}) ON COMMIT DELETE ROWS;",
489 temp_name(t),
490 t.name(layout)
491 )
492 });
493 client.batch_execute(&format!(
494 "CREATE TEMP TABLE osm_geoms ON COMMIT DELETE ROWS AS SELECT id, geom FROM {} WITH NO DATA; {}",
495 Table::Ways.name(layout),
496 tables.concat()
497 ))?;
498 Ok(())
499}
500
501fn temp_name(table: Table) -> String {
503 <&str>::from(table).replace('.', "_")
504}
505
506fn upsert(
509 tx: &mut Transaction<'_>,
510 table: Table,
511 layout: TableLayout,
512 rows: &Rows,
513) -> Result<(), SyncError> {
514 if rows.count == 0 {
515 return Ok(());
516 }
517 let (list, tmp) = (table.columns(), temp_name(table));
518 let rest = list.strip_prefix("id, ").unwrap_or(list);
520 let new = rest.replace(", ", ", EXCLUDED.");
521 db::copy(tx, &tmp, list, rows)?;
522 tx.execute(&format!("INSERT INTO {} ({list}) SELECT {list} FROM {tmp} ON CONFLICT (id) DO UPDATE SET ({rest}) = ROW(EXCLUDED.{new})", table.name(layout)), &[])?;
523 Ok(())
524}
525
526fn locate(reader: &mut impl NodeReader, refs: &[i64], locs: &mut Vec<Location>) -> bool {
528 locs.clear();
529 refs.iter().all(|&r| {
530 u64::try_from(r)
531 .ok()
532 .and_then(|r| reader.get(r))
533 .map(|l| locs.push(l))
534 .is_some()
535 })
536}