1use std::hash::{BuildHasher as _, Hasher as _, RandomState};
4use std::path::Path;
5use std::sync::atomic::{AtomicU64, Ordering};
6use std::time::{Instant, SystemTime};
7use std::{fs, io, thread};
8
9use osmflow::nodes::PagedStore;
10use osmflow::nodes::prelude::*;
11use osmflow::osc::{COMMIT_DELAY, Replication, Start, StateSource, plan};
12use osmflow::{Location, PbfError, PbfReader, Select, Timestamp};
13use postgres::Client;
14use tracing::{debug, info, warn};
15
16use crate::copy::Rows;
17use crate::db::{self, DbState, SCHEMA_VERSION, Table, Writers};
18use crate::files::{ID_KEY, remove_node_file};
19use crate::index::{self, ReverseIndex};
20use crate::sort::Sorter;
21use crate::{Mirror, SyncError, TableLayout};
22
23pub(crate) const IMPORT_REV: i32 = 1;
25
26#[derive(Debug, Clone)]
28pub struct ImportOpts {
29 pub replace: bool,
31 pub replication_url: Option<String>,
34 pub sequence: Option<u64>,
37 pub connections: usize,
39 pub tables: TableLayout,
41}
42
43impl Default for ImportOpts {
44 fn default() -> Self {
45 Self {
46 replace: false,
47 replication_url: None,
48 sequence: None,
49 connections: crate::default_connections(),
50 tables: TableLayout::default(),
51 }
52 }
53}
54
55#[derive(Debug, Clone, Default, PartialEq, Eq)]
57pub struct ImportStats {
58 pub nodes: u64,
60 pub tagged_nodes: u64,
62 pub ways: u64,
64 pub relations: u64,
66 pub pairs: u64,
68}
69
70pub(crate) fn import(
71 m: &Mirror,
72 pbf: &Path,
73 replication: Option<&Replication>,
74 opts: &ImportOpts,
75) -> Result<ImportStats, SyncError> {
76 let reader = PbfReader::open(pbf)?;
77 let header = reader.header();
78 let header_sequence = match header.replication_sequence.map(i64::cast_unsigned) {
79 Some(h) if !same_url(opts, header.replication_base_url.as_ref()) => {
80 header_stream(h, header.replication_timestamp, replication)?
81 }
82 h => h,
83 };
84 let (sequence, timestamp) = start(
85 opts.sequence,
86 header_sequence,
87 header.replication_timestamp,
88 replication,
89 )?;
90 let url = opts
91 .replication_url
92 .clone()
93 .or_else(|| header.replication_base_url.clone());
94
95 let mut client = db::connect(&m.url)?;
96 create_schema(&mut client, opts.replace, opts.tables)?;
97 fs::create_dir_all(&m.dir)?;
98 remove_node_file(&m.node_path())?;
99 index::remove(&m.index_path())?;
100 let id = random_id();
101
102 let t = Instant::now();
103 let mut store = PagedStore::open(m.node_path())?;
104 let mut stats = ImportStats {
105 nodes: reader.load_nodes(&mut store)?,
106 ..ImportStats::default()
107 };
108 store.preload()?;
109 info!(
110 nodes = stats.nodes,
111 secs = t.elapsed().as_secs_f32(),
112 "loaded the node file"
113 );
114
115 let t = Instant::now();
116 let pairs = copy_objects(
117 &reader,
118 &store,
119 &m.url,
120 opts.connections,
121 opts.tables,
122 &mut stats,
123 &m.dir,
124 )?;
125 info!(
126 tagged_nodes = stats.tagged_nodes,
127 ways = stats.ways,
128 relations = stats.relations,
129 secs = t.elapsed().as_secs_f32(),
130 "copied the objects"
131 );
132
133 let t = Instant::now();
136 let (index, tables) = thread::scope(|s| {
137 let tables = s.spawn(|| finish_tables(&m.url, opts.tables));
138 let t = Instant::now();
139 let index = pairs.finish().map_err(SyncError::from).and_then(|sorted| {
140 ReverseIndex::create(
141 &m.index_path(),
142 id,
143 IMPORT_REV.into(),
144 sorted.map(|p| p.map_err(SyncError::from)),
145 )
146 });
147 debug!(secs = t.elapsed().as_secs_f32(), "built the reverse index");
148 (
149 index,
150 tables
151 .join()
152 .unwrap_or_else(|_| Err(SyncError::state("finishing the tables panicked"))),
153 )
154 });
155 stats.pairs = index?.1;
156 tables?;
157 store.set_metadata(ID_KEY, &id.to_le_bytes())?;
158 store.commit(u64::from(IMPORT_REV.cast_unsigned()))?;
159 info!(
160 pairs = stats.pairs,
161 secs = t.elapsed().as_secs_f32(),
162 "built the reverse index and the primary keys"
163 );
164
165 let position = DbState {
166 id,
167 rev: IMPORT_REV.into(),
168 url,
169 sequence,
170 timestamp,
171 tables: opts.tables,
172 };
173 record(&mut client, &position, &stats)?;
174 Ok(stats)
175}
176
177fn record(client: &mut Client, at: &DbState, loaded: &ImportStats) -> Result<(), SyncError> {
179 let timestamp = at.timestamp.map(Timestamp::as_millis);
180 let mut tx = client.transaction()?;
181 tx.execute(
182 "INSERT INTO osm.batches (rev, first_sequence, last_sequence, timestamp, nodes, ways, relations) \
183 VALUES ($1, $2, $2, to_timestamp($3::int8 / 1000.0), $4, $5, $6)",
184 &[
185 &IMPORT_REV,
186 &at.sequence,
187 ×tamp,
188 &loaded.tagged_nodes.cast_signed(),
189 &loaded.ways.cast_signed(),
190 &loaded.relations.cast_signed(),
191 ],
192 )?;
193 tx.execute(
194 "INSERT INTO osm.state (id, version, rev, url, sequence, timestamp, tables) \
195 VALUES ($1, $2, $3, $4, $5, to_timestamp($6::int8 / 1000.0), $7)",
196 &[
197 &at.id,
198 &SCHEMA_VERSION,
199 &IMPORT_REV,
200 &at.url,
201 &at.sequence,
202 ×tamp,
203 &at.tables.as_ref(),
204 ],
205 )?;
206 tx.commit()?;
207 Ok(())
208}
209
210fn same_url(opts: &ImportOpts, header_url: Option<&String>) -> bool {
212 opts.replication_url
213 .as_ref()
214 .is_none_or(|u| Some(u) == header_url)
215}
216
217fn header_stream(
222 h: u64,
223 time: Option<Timestamp>,
224 replication: Option<&Replication>,
225) -> Result<Option<u64>, SyncError> {
226 let Some(r) = replication else {
227 return Ok(Some(h));
228 };
229 Ok(match r.get(h)? {
230 Some(state) if Some(state.timestamp) != time => None,
231 _ => Some(h),
232 })
233}
234
235fn start(
243 given: Option<u64>,
244 header: Option<u64>,
245 file_time: Option<Timestamp>,
246 replication: Option<&Replication>,
247) -> Result<(i64, Option<Timestamp>), SyncError> {
248 let bound = match (header, replication, file_time) {
250 (Some(h), ..) => Some((h, file_time)),
251 (None, Some(r), Some(at)) => {
252 let sources: [&dyn StateSource; 1] = [r];
253 let first = plan(&sources, Start::Snapshot { at }, None)?
254 .first()
255 .map(|s| s.from);
256 let since = first.map_or_else(|| r.state(), Ok)?;
257 Some((since.sequence, Some(since.timestamp)))
258 }
259 (None, ..) => None,
260 };
261 match (given, bound) {
262 (None, Some((b, time))) => {
263 if header.is_none() {
264 info!(sequence = b, "found the file's sequence from its timestamp");
265 }
266 Ok((b.cast_signed(), time))
267 }
268 (Some(g), Some((b, time))) if g == b => Ok((g.cast_signed(), time)),
269 (Some(g), Some((b, _))) if g > b => Err(SyncError::state(match header {
270 Some(_) => format!(
271 "the header says the file is up to diff {b}, so diffs {} to {g} would be skipped; give sequence \
272 {b} or earlier",
273 b + 1
274 ),
275 None => format!(
276 "the file has the changes made up to {}, and a change can show in a diff {} minutes after it is \
277 made, so diffs {} to {g} may have changes it does not have; give sequence {b} or earlier",
278 file_time.unwrap_or_default(),
279 COMMIT_DELAY.as_secs() / 60,
280 b + 1,
281 ),
282 })),
283 (Some(g), bound) => {
284 if let Some((b, _)) = bound {
285 warn!(
286 "sequence {g} is {} diffs before the file's {b}: until they are applied, the database has older \
287 versions of the objects they change, and nodes they move add to their ways' minor",
288 b - g
289 );
290 }
291 let time = replication
292 .map(|r| r.sequence_state(g))
293 .transpose()?
294 .map(|s| s.timestamp);
295 Ok((g.cast_signed(), time))
296 }
297 (None, None) => Err(SyncError::state(if file_time.is_some() {
298 "the header gives no replication sequence; give the replication stream, to find it from the file's \
299 timestamp, or the sequence"
300 } else {
301 "the header gives neither a replication sequence nor a timestamp; give the sequence"
302 })),
303 }
304}
305
306fn create_schema(client: &mut Client, replace: bool, layout: TableLayout) -> Result<(), SyncError> {
309 if replace {
310 client.batch_execute("DROP SCHEMA IF EXISTS osm CASCADE")?;
311 } else if client
312 .query_one("SELECT to_regnamespace('osm') IS NOT NULL", &[])?
313 .get(0)
314 {
315 return Err(SyncError::state(
316 "the database already has an osm schema: replace it, or update it",
317 ));
318 }
319 client.batch_execute("CREATE EXTENSION IF NOT EXISTS postgis")?;
321 let postgis: String = client
322 .query_one(
323 "SELECT n.nspname FROM pg_extension e JOIN pg_namespace n ON n.oid = e.extnamespace \
324 WHERE e.extname = 'postgis'",
325 &[],
326 )?
327 .get(0);
328 let sql = layout.sql(&postgis);
329 let schema = include_str!("schema.sql")
330 .replace("{nodes}", Table::Nodes.name(layout))
331 .replace("{ways}", Table::Ways.name(layout))
332 .replace("{point}", sql.point)
333 .replace("{line}", sql.line)
334 .replace("{ids}", sql.ids)
335 .replace("{views}", &sql.after);
336 client.batch_execute(&schema)?;
337 Ok(())
338}
339
340fn copy_objects(
343 reader: &PbfReader,
344 store: &PagedStore,
345 url: &str,
346 connections: usize,
347 layout: TableLayout,
348 stats: &mut ImportStats,
349 dir: &Path,
350) -> Result<Sorter, SyncError> {
351 let writers = Writers::start(url, connections, layout)?;
352 let pairs = Sorter::new(dir)?;
353 let counts = [const { AtomicU64::new(0) }; 3];
354 let read = reader.par_resolve(Select::all(), store, |block, locator| {
355 let mut rows = [Rows::new(layout), Rows::new(layout), Rows::default()];
356 for n in block.nodes().filter(|n| n.tags().len() > 0) {
357 let loc = Location::new(n.decimicro_lat(), n.decimicro_lon());
358 rows[0].node(n.id(), n.info().into(), IMPORT_REV, n.tags(), Some(loc));
359 }
360 let mut block_pairs = Vec::new();
361 let mut locs = Vec::new();
362 for w in block.ways() {
363 locs.clear();
364 let complete = w
365 .refs()
366 .all(|r| locator.location(r).map(|l| locs.push(l)).is_some());
367 block_pairs.extend(
368 w.refs()
369 .filter_map(|n| Some((u64::try_from(n).ok()?, w.id().cast_unsigned()))),
370 );
371 let line = complete.then_some(&locs[..]);
372 rows[1].way(
373 w.id(),
374 w.info().into(),
375 IMPORT_REV,
376 w.tags(),
377 w.refs(),
378 line,
379 );
380 }
381 for r in block.relations() {
382 rows[2].relation(r.id(), r.info().into(), IMPORT_REV, r.tags(), r.members());
383 }
384 let mut sent = true;
385 for ((rows, count), table) in
386 rows.into_iter()
387 .zip(&counts)
388 .zip([Table::Nodes, Table::Ways, Table::Relations])
389 {
390 count.fetch_add(rows.count, Ordering::Relaxed);
391 sent &= writers.send(table, rows);
392 }
393 pairs.extend(block_pairs).map_err(PbfError::Io)?;
394 if sent {
395 Ok(())
396 } else {
397 Err(PbfError::Io(io::Error::other(
398 "the database connections stopped",
399 )))
400 }
401 });
402 writers.finish()?;
404 read?;
405 [stats.tagged_nodes, stats.ways, stats.relations] = counts.map(AtomicU64::into_inner);
406 Ok(pairs)
407}
408
409fn finish_tables(url: &str, layout: TableLayout) -> Result<(), SyncError> {
412 thread::scope(|s| {
413 let tables = [Table::Nodes, Table::Ways, Table::Relations].map(|t| {
414 let t = t.name(layout);
415 s.spawn(move || -> Result<(), SyncError> {
416 let mut client = db::connect(url)?;
417 for sql in [
418 format!("ALTER TABLE {t} ADD PRIMARY KEY (id)"),
419 format!("ANALYZE {t}"),
420 format!("ALTER TABLE {t} RESET (autovacuum_enabled)"),
421 ] {
422 let t = Instant::now();
423 client.batch_execute(&sql)?;
424 debug!(secs = t.elapsed().as_secs_f32(), sql, "finished");
425 }
426 Ok(())
427 })
428 });
429 tables.into_iter().try_for_each(|t| {
430 t.join()
431 .unwrap_or_else(|_| Err(SyncError::state("finishing a table panicked")))
432 })
433 })
434}
435
436fn random_id() -> i64 {
439 let mut h = RandomState::new().build_hasher();
440 let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH);
441 h.write_u128(now.map_or(0, |d| d.as_nanos()));
442 (h.finish() >> 1).cast_signed()
443}
444
445#[cfg(test)]
446mod tests {
447 use super::*;
448
449 fn stream(dir: &Path) -> Replication {
451 let times = ["20:08:00", "20:14:00", "20:20:00", "20:21:01", "20:22:00"];
452 fs::create_dir_all(dir.join("000/001")).unwrap();
453 for (n, time) in (705..).zip(times) {
454 let state = format!(
455 "sequenceNumber={}\ntimestamp=2025-04-23T{}Z\n",
456 1000 + n,
457 time.replace(':', "\\:")
458 );
459 fs::write(dir.join(format!("000/001/{n}.state.txt")), &state).unwrap();
460 if n == 709 {
461 fs::write(dir.join("state.txt"), &state).unwrap();
462 }
463 }
464 Replication::local(dir)
465 }
466
467 #[test]
468 fn the_sequence_is_found_or_checked() {
469 let dir = tempfile::tempdir().unwrap();
470 let r = stream(dir.path());
471 let at = |t: &str| format!("2025-04-23T{t}Z").parse::<Timestamp>().unwrap();
472 let made = Some(at("20:21:01"));
473 assert_eq!(start(None, Some(1708), made, None).unwrap(), (1708, made));
475 assert_eq!(
476 start(Some(1708), Some(1708), made, Some(&r)).unwrap(),
477 (1708, made)
478 );
479 let err = start(Some(1709), Some(1708), made, Some(&r))
480 .unwrap_err()
481 .to_string();
482 assert!(err.contains("give sequence 1708"), "{err}");
483 assert_eq!(
484 start(Some(1707), Some(1708), made, Some(&r)).unwrap(),
485 (1707, Some(at("20:20:00")))
486 );
487 let found = (1706, Some(at("20:14:00")));
489 assert_eq!(start(None, None, made, Some(&r)).unwrap(), found);
490 assert_eq!(start(Some(1706), None, made, Some(&r)).unwrap(), found);
491 let err = start(Some(1708), None, made, Some(&r))
492 .unwrap_err()
493 .to_string();
494 assert!(err.contains("diffs 1707 to 1708"), "{err}");
495 start(None, None, made, None).unwrap_err();
496 assert_eq!(start(Some(1708), None, None, None).unwrap(), (1708, None));
497 }
498
499 #[test]
500 fn a_copy_of_the_headers_stream_keeps_its_sequence() {
501 let dir = tempfile::tempdir().unwrap();
502 let r = stream(dir.path());
503 let at = |t: &str| Some(format!("2025-04-23T{t}Z").parse::<Timestamp>().unwrap());
504 assert_eq!(
506 header_stream(1708, at("20:21:01"), Some(&r)).unwrap(),
507 Some(1708)
508 );
509 assert_eq!(
510 header_stream(1710, at("20:23:00"), Some(&r)).unwrap(),
511 Some(1710)
512 );
513 assert_eq!(header_stream(1708, at("20:30:00"), Some(&r)).unwrap(), None);
514 }
515}