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