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::{Mirror, SyncError};
18
19#[derive(Debug, Clone)]
21pub struct UpdateOpts {
22 pub max_diffs: u64,
25 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
40pub struct UpdateStats {
41 pub batches: u64,
43 pub diffs: u64,
45 pub rows: u64,
47 pub moved_ways: u64,
49 pub sequence: i64,
51}
52
53#[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 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
88pub(crate) fn update(
89 m: &Mirror,
90 replication: &Replication,
91 opts: &UpdateOpts,
92) -> Result<UpdateStats, SyncError> {
93 let mut client = db::connect(&m.url)?;
94 let mut state = DbState::read(&mut client)?;
95 check_stream(&state, replication)?;
96 let mut store = m.open_node_file(&mut client, &state, replication)?;
97 let index = m.open_index(&mut client, &state)?;
98 create_temp_tables(&mut client)?;
99 let latest = match opts.until {
100 Some(until) => until,
101 None => replication.state()?.sequence,
102 };
103 let mut total = UpdateStats {
104 sequence: state.sequence,
105 ..UpdateStats::default()
106 };
107 let mut next = state.sequence.cast_unsigned() + 1;
108 while next <= latest {
109 let t = Instant::now();
110 let last = latest.min(next + opts.max_diffs.max(1) - 1);
111 let (changes, last_state) = read_diffs(replication, next..=last)?;
112 let read = t.elapsed();
113 let batch = Batch {
114 rev: state.rev + 1,
115 first: next.cast_signed(),
116 last: last.cast_signed(),
117 timestamp: last_state.map(|s| s.timestamp),
118 };
119 let applied = apply(&mut client, &mut store, &index, &changes, &batch)?;
120 info!(
121 rev = batch.rev,
122 sequences = format!("{next}..={last}"),
123 changes = changes.len(),
124 rows = applied.rows,
125 moved_ways = applied.moved_ways,
126 read_secs = read.as_secs_f32(),
127 secs = t.elapsed().as_secs_f32(),
128 "applied a batch"
129 );
130 state.rev = batch.rev;
131 total.batches += 1;
132 total.diffs += last + 1 - next;
133 total.rows += applied.rows;
134 total.moved_ways += applied.moved_ways;
135 total.sequence = batch.last;
136 next = last + 1;
137 }
138 Ok(total)
139}
140
141pub(crate) fn check_stream(state: &DbState, replication: &Replication) -> Result<(), SyncError> {
145 let Some(time) = state.timestamp else {
146 return Ok(());
147 };
148 let sequence = state.sequence.cast_unsigned();
149 let Some(theirs) = replication.get(sequence)? else {
150 let latest = replication.state()?.sequence;
151 if latest < sequence {
152 return Err(SyncError::state(format!(
153 "the replication stream ends at diff {latest}, before the database's {sequence}: it is not the \
154 database's stream, {}",
155 state.url.as_deref().unwrap_or("which it does not name")
156 )));
157 }
158 warn!(
159 "the replication stream has no state of diff {sequence}, the database's, so it cannot be checked to be \
160 the database's stream"
161 );
162 return Ok(());
163 };
164 if theirs.timestamp == time {
165 Ok(())
166 } else {
167 Err(SyncError::state(format!(
168 "the replication stream's diff {sequence} is at {}, but the database's is at {time}: the stream is \
169 not the database's, {}",
170 theirs.timestamp,
171 state.url.as_deref().unwrap_or("which it does not name")
172 )))
173 }
174}
175
176struct Batch {
178 rev: i64,
179 first: i64,
180 last: i64,
181 timestamp: Option<Timestamp>,
182}
183
184#[derive(Default)]
186struct Writes {
187 rows: Rows,
188 written: Vec<i64>,
189 deleted: Vec<i64>,
190}
191
192#[derive(Default)]
194struct Plan {
195 nodes: Writes,
196 ways: Writes,
197 relations: Writes,
198 geoms: Rows,
200 moved_ways: Vec<i64>,
201 remove: Vec<Pair>,
202 add: Vec<Pair>,
203}
204
205fn apply(
207 client: &mut Client,
208 store: &mut PagedStore,
209 index: &ReverseIndex,
210 changes: &Changes,
211 batch: &Batch,
212) -> Result<UpdateStats, SyncError> {
213 let t = Instant::now();
214 let moved = set_locations(store, changes)?;
215 let through = index.ways_of(&moved)?;
216 let mut ids: Vec<i64> = changes
218 .ways
219 .keys()
220 .copied()
221 .chain(through.iter().map(|p| p.1.cast_signed()))
222 .collect();
223 ids.sort_unstable();
224 ids.dedup();
225 let old: HashMap<i64, Vec<i64>> = client
226 .query("SELECT id, nodes FROM osm.ways WHERE id = ANY($1)", &[&ids])?
227 .into_iter()
228 .map(|r| (r.get(0), r.get(1)))
229 .collect();
230 let read = t.elapsed();
231 let plan = plan(store, changes, &through, &old, batch.rev);
232 let planned = t.elapsed();
233 let rows = write(client, changes, &plan, batch)?;
234 let written = t.elapsed();
235 store.commit(batch.rev.cast_unsigned())?;
237 index.apply(&plan.remove, &plan.add, batch.rev)?;
238 debug!(
239 moved_nodes = moved.len(),
240 read_secs = read.as_secs_f32(),
241 encode_secs = planned.saturating_sub(read).as_secs_f32(),
242 db_secs = written.saturating_sub(planned).as_secs_f32(),
243 files_secs = t.elapsed().saturating_sub(written).as_secs_f32(),
244 "batch steps"
245 );
246 Ok(UpdateStats {
247 rows,
248 moved_ways: plan.moved_ways.len() as u64,
249 ..UpdateStats::default()
250 })
251}
252
253fn plan(
256 store: &PagedStore,
257 changes: &Changes,
258 through: &[Pair],
259 old: &HashMap<i64, Vec<i64>>,
260 rev: i64,
261) -> Plan {
262 let mut plan = Plan::default();
263 for (&id, (deleted, w)) in &changes.ways {
264 if let Some(nodes) = old.get(&id) {
265 plan.remove.extend(way_pairs(id, nodes));
266 }
267 if !deleted {
268 plan.add.extend(way_pairs(id, &w.refs));
269 }
270 }
271 let mut moved_ways = BTreeSet::new();
273 for &(node, way) in through {
274 let id = way.cast_signed();
275 match old.get(&id) {
276 _ if changes.ways.contains_key(&id) => {}
277 Some(nodes) if nodes.contains(&node.cast_signed()) => {
278 moved_ways.insert(id);
279 }
280 _ => plan.remove.push((node, way)),
281 }
282 }
283 for pairs in [&mut plan.remove, &mut plan.add] {
284 pairs.sort_unstable();
285 pairs.dedup();
286 }
287
288 let mut reader = store.reader();
289 let mut locs = Vec::new();
290 for (&id, (deleted, n)) in &changes.nodes {
291 if *deleted || n.tags.is_empty() {
292 plan.nodes.deleted.push(id);
293 } else {
294 plan.nodes.written.push(id);
295 plan.nodes
296 .rows
297 .node(id, (&n.meta).into(), rev, n.tags.iter(), n.location);
298 }
299 }
300 for (&id, (deleted, w)) in &changes.ways {
301 if *deleted {
302 plan.ways.deleted.push(id);
303 } else {
304 plan.ways.written.push(id);
305 let complete = locate(&mut reader, &w.refs, &mut locs);
306 let line = complete.then_some(&locs[..]);
307 let nodes = w.refs.iter().copied();
308 plan.ways
309 .rows
310 .way(id, (&w.meta).into(), rev, w.tags.iter(), nodes, line);
311 }
312 }
313 for &id in &moved_ways {
314 let complete = locate(&mut reader, &old[&id], &mut locs);
315 plan.geoms
316 .row(2)
317 .i64(id)
318 .line(complete.then_some(&locs[..]));
319 }
320 plan.moved_ways = moved_ways.into_iter().collect();
321 for (&id, (deleted, r)) in &changes.relations {
322 if *deleted {
323 plan.relations.deleted.push(id);
324 } else {
325 plan.relations.written.push(id);
326 let members: Vec<_> = r.members().collect();
327 plan.relations
328 .rows
329 .relation(id, (&r.meta).into(), rev, r.tags.iter(), &members);
330 }
331 }
332 plan
333}
334
335fn write(
338 client: &mut Client,
339 changes: &Changes,
340 plan: &Plan,
341 batch: &Batch,
342) -> Result<u64, SyncError> {
343 let rev = batch.rev;
344 let mut tx = client.transaction()?;
345 let mut log = Rows::default();
346 let mut rows = 0;
347 for (table, kind, w) in [
348 (Table::Nodes, b'n', &plan.nodes),
349 (Table::Ways, b'w', &plan.ways),
350 (Table::Relations, b'r', &plan.relations),
351 ] {
352 let gone = if w.deleted.is_empty() {
353 Vec::new()
354 } else {
355 tx.query(
356 &format!(
357 "DELETE FROM {} WHERE id = ANY($1) RETURNING id",
358 table.name()
359 ),
360 &[&w.deleted],
361 )?
362 };
363 for row in &gone {
364 log.row(4).i64(rev).char(kind).i64(row.get(0)).char(b'd');
365 }
366 upsert(&mut tx, table, &w.rows)?;
367 for &id in &w.written {
368 log.row(4).i64(rev).char(kind).i64(id).char(b'u');
369 }
370 rows += gone.len() as u64 + w.rows.count;
371 }
372 if plan.geoms.count > 0 {
373 db::copy(&mut tx, "osm_geoms", "id, geom", &plan.geoms)?;
374 tx.execute(
375 "UPDATE osm.ways w SET geom = g.geom, minor = w.minor + 1, rev = $1 FROM osm_geoms g WHERE w.id = g.id",
376 &[&rev],
377 )?;
378 for &id in &plan.moved_ways {
379 log.row(4).i64(rev).char(b'w').i64(id).char(b'g');
380 }
381 }
382 if log.count > 0 {
383 db::copy(&mut tx, "osm.changes", "rev, kind, id, action", &log)?;
384 }
385 let timestamp = batch.timestamp.map(Timestamp::as_millis);
386 let count = |n: usize| i64::try_from(n).unwrap_or(i64::MAX);
387 tx.execute(
388 "INSERT INTO osm.batches (rev, first_sequence, last_sequence, timestamp, nodes, ways, relations) \
389 VALUES ($1, $2, $3, to_timestamp($4::int8 / 1000.0), $5, $6, $7)",
390 &[
391 &rev,
392 &batch.first,
393 &batch.last,
394 ×tamp,
395 &count(changes.nodes.len()),
396 &count(changes.ways.len()),
397 &count(changes.relations.len()),
398 ],
399 )?;
400 tx.execute(
401 "UPDATE osm.state SET rev = $1, sequence = $2, timestamp = to_timestamp($3::int8 / 1000.0)",
402 &[&rev, &batch.last, ×tamp],
403 )?;
404 tx.commit()?;
405 Ok(rows)
406}
407
408fn create_temp_tables(client: &mut Client) -> Result<(), SyncError> {
410 let tables = [Table::Nodes, Table::Ways, Table::Relations].map(|t| {
411 format!(
412 "CREATE TEMP TABLE {} (LIKE {}) ON COMMIT DELETE ROWS;",
413 temp_name(t),
414 t.name()
415 )
416 });
417 client.batch_execute(&format!(
418 "CREATE TEMP TABLE osm_geoms (id int8, geom geometry(LineString, 4326)) ON COMMIT DELETE ROWS; {}",
419 tables.concat()
420 ))?;
421 Ok(())
422}
423
424fn temp_name(table: Table) -> String {
426 table.name().replace('.', "_")
427}
428
429fn upsert(tx: &mut Transaction<'_>, table: Table, rows: &Rows) -> Result<(), SyncError> {
432 if rows.count == 0 {
433 return Ok(());
434 }
435 let (name, columns, tmp) = (table.name(), table.columns(), temp_name(table));
436 let list = columns.join(", ");
437 let set = columns[1..]
438 .iter()
439 .map(|c| format!("{c} = EXCLUDED.{c}"))
440 .collect::<Vec<_>>()
441 .join(", ");
442 db::copy(tx, &tmp, &list, rows)?;
443 tx.execute(&format!("INSERT INTO {name} ({list}) SELECT {list} FROM {tmp} ON CONFLICT (id) DO UPDATE SET {set}"), &[])?;
444 Ok(())
445}
446
447fn locate(reader: &mut impl NodeReader, refs: &[i64], locs: &mut Vec<Location>) -> bool {
449 locs.clear();
450 refs.iter().all(|&r| {
451 u64::try_from(r)
452 .ok()
453 .and_then(|r| reader.get(r))
454 .map(|l| locs.push(l))
455 .is_some()
456 })
457}