Skip to main content

osmflow_sync/
import.rs

1//! The import: a PBF file into the `osm` schema, the node file and the reverse index.
2
3use 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
23/// The revision of the imported data.
24pub(crate) const IMPORT_REV: i32 = 1;
25
26/// How to import.
27#[derive(Debug, Clone)]
28pub struct ImportOpts {
29    /// Drop an existing `osm` schema first; without it, one is an error.
30    pub replace: bool,
31    /// The URL of the replication stream that continues the file, kept for updates, instead of the one its header
32    /// names.
33    pub replication_url: Option<String>,
34    /// The stream's sequence the file is up to, instead of the one its header gives. Without either, it is found from
35    /// the file's timestamp in the stream, as for a planet file.
36    pub sequence: Option<u64>,
37    /// The database connections rows are copied on, at once.
38    pub connections: usize,
39    /// The layout of `osm.nodes` and `osm.ways`, from then on; packed by default: see [`TableLayout`].
40    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/// What an import loaded.
56#[derive(Debug, Clone, Default, PartialEq, Eq)]
57pub struct ImportStats {
58    /// Nodes in the node file.
59    pub nodes: u64,
60    /// Rows of `osm.nodes`: the tagged nodes.
61    pub tagged_nodes: u64,
62    /// Rows of `osm.ways`.
63    pub ways: u64,
64    /// Rows of `osm.relations`.
65    pub relations: u64,
66    /// (node, way) pairs in the reverse index.
67    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    // The files and the database are finished at once: the index on this thread, the tables on connections of
134    // their own
135    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
177/// Records the import's batch and the database's state, which marks the import done.
178fn 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            &timestamp,
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            &timestamp,
203            &at.tables.as_ref(),
204        ],
205    )?;
206    tx.commit()?;
207    Ok(())
208}
209
210/// Whether the stream is the one the header names: none other given, or the same URL.
211fn 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
217/// The header's sequence `h`, if it is of `replication`, another URL than the header's: a copy of the header's stream
218/// has the header's time at `h`, or no state of it, as a directory of only the diffs after the file, and a stream not
219/// given cannot say otherwise. Another stream's state at `h` has another time, and its sequence is found from the
220/// file's time instead.
221fn 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
235/// The sequence the file is up to, and the time of its state.
236///
237/// An extract's header gives its sequence on its own stream (`header`), which is exact: a later one given would skip
238/// changes and is an error. Without it, as for a planet file, it is found or checked in the stream from the file's
239/// timestamp: the file has the changes made up to then, and a change can show in a diff up to [`COMMIT_DELAY`] after
240/// it is made, so a sequence after the last diff before then is an error. An earlier sequence only repeats changes the
241/// file has, which applying again changes nothing in the end, so it is only warned of.
242fn 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    // The last sequence the file is known to have, and its state's time
249    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
306/// Creates the `osm` schema, with `layout`'s column types and, when packed, the functions and views, after dropping
307/// an existing one if `replace`.
308fn 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    // PostGIS first, so the function can name its schema
320    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
340/// Copies the tagged nodes, the ways and the relations into their tables, and returns the reverse index's pairs, to
341/// sort with temporary files in `dir`.
342fn 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    // A failed connection stops the read too, so its error goes first
403    writers.finish()?;
404    read?;
405    [stats.tagged_nodes, stats.ways, stats.relations] = counts.map(AtomicU64::into_inner);
406    Ok(pairs)
407}
408
409/// Adds the primary keys and analyzes, each table on a connection of its own. Autovacuum, off during the load,
410/// vacuums them later.
411fn 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
436/// A random positive identity for a new database. `RandomState` is keyed from the system's random source, once per
437/// thread and then stepped; the time is hashed too, to tell apart imports that start alike.
438fn 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    /// A stream whose diffs 1705 to 1709 are at 20:08, 20:14, 20:20, 20:21:01 and 20:22.
450    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        // As the header gives it, given again or not, without reading the stream; a later one is an error
474        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        // From the file's time: changes made after 20:15:01 can be in diff 1707
488        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        // The same time at 1708, or no state of 1710: the header's stream; another time at 1708: another stream
505        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}