Skip to main content

osmflow_sync/
lib.rs

1#![doc = include_str!("../README.md")]
2
3mod copy;
4mod db;
5mod error;
6mod files;
7mod import;
8mod index;
9mod rebuild;
10mod sort;
11mod update;
12
13use std::path::{Path, PathBuf};
14use std::{fmt, thread};
15
16use osmflow::nodes::PagedStore;
17use osmflow::nodes::prelude::*;
18use osmflow::osc::Replication;
19
20pub use crate::db::DbState;
21pub use crate::error::SyncError;
22pub use crate::import::{ImportOpts, ImportStats};
23pub use crate::rebuild::{Rebuild, RebuildStats};
24pub use crate::update::{UpdateOpts, UpdateStats};
25
26/// A database kept current from replication, and the directory of its node file and reverse index.
27#[derive(Clone)]
28pub struct Mirror {
29    url: String,
30    dir: PathBuf,
31}
32
33/// Without the database's URL, which may hold a password.
34impl fmt::Debug for Mirror {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        f.debug_struct("Mirror")
37            .field("dir", &self.dir)
38            .finish_non_exhaustive()
39    }
40}
41
42/// The revision and identity of the node file or the reverse index.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub struct FileStamp {
45    /// The identity of the database the file was made for, which must be the database's; none for a node file whose
46    /// rebuild was cut short.
47    pub id: Option<i64>,
48    /// The database revision the file is up to.
49    pub rev: i64,
50}
51
52/// Where the database and its files are.
53#[derive(Debug)]
54pub struct Status {
55    /// The database's position.
56    pub db: DbState,
57    /// The node file's stamp, or why it could not be read.
58    pub nodes: Result<FileStamp, SyncError>,
59    /// The reverse index's stamp, or why it could not be read.
60    pub index: Result<FileStamp, SyncError>,
61}
62
63impl Mirror {
64    /// A mirror in the database at `url` (`postgresql://user@host/db`, or `host=… user=…`), with its files in `dir`.
65    /// Connections are not encrypted.
66    pub fn new(url: impl Into<String>, dir: impl Into<PathBuf>) -> Self {
67        Self {
68            url: url.into(),
69            dir: dir.into(),
70        }
71    }
72
73    /// Creates the `osm` schema from a PBF file, which must be sorted by type and ID as published files are, and makes
74    /// the node file and the reverse index in the directory, replacing any there.
75    ///
76    /// The file's replication sequence is the one [`ImportOpts::sequence`] or its header gives. `replication`, the
77    /// stream [`ImportOpts::replication_url`] or the header names, finds it from the file's timestamp when neither
78    /// does, as for a planet file, and checks a sequence given in the options against that timestamp when the header
79    /// gives none for the stream.
80    pub fn import(
81        &self,
82        pbf: impl AsRef<Path>,
83        replication: Option<&Replication>,
84        opts: &ImportOpts,
85    ) -> Result<ImportStats, SyncError> {
86        import::import(self, pbf.as_ref(), replication, opts)
87    }
88
89    /// Applies the diffs of `replication` after the database's sequence, up to the stream's latest or
90    /// [`UpdateOpts::until`]. The files are brought up to the database first if a crash left them behind.
91    pub fn update(
92        &self,
93        replication: &Replication,
94        opts: &UpdateOpts,
95    ) -> Result<UpdateStats, SyncError> {
96        update::update(self, replication, opts)
97    }
98
99    /// Makes the node file and the reverse index again, up to the database's revision. The database is only read.
100    pub fn rebuild(&self, from: &Rebuild<'_>) -> Result<RebuildStats, SyncError> {
101        rebuild::rebuild(self, from)
102    }
103
104    /// The database's position in its replication stream.
105    pub fn state(&self) -> Result<DbState, SyncError> {
106        DbState::read(&mut db::connect(&self.url)?)
107    }
108
109    /// The database's position, and its files' stamps.
110    pub fn status(&self) -> Result<Status, SyncError> {
111        let db = self.state()?;
112        let nodes = PagedStore::open_read_only(self.node_path())
113            .map(|s| FileStamp {
114                id: files::node_file_id(&s),
115                rev: s.stamp().cast_signed(),
116            })
117            .map_err(SyncError::from);
118        let index = index::ReverseIndex::open(&self.index_path())
119            .and_then(|i| i.stamp())
120            .map(|(id, rev)| FileStamp { id: Some(id), rev });
121        Ok(Status { db, nodes, index })
122    }
123
124    /// The node file.
125    #[must_use]
126    pub fn node_path(&self) -> PathBuf {
127        self.dir.join("nodes.cache")
128    }
129
130    /// The reverse index.
131    #[must_use]
132    pub fn index_path(&self) -> PathBuf {
133        self.dir.join("ways.redb")
134    }
135}
136
137/// The connections an import copies on by default: half the cores, from 1 to 8.
138fn default_connections() -> usize {
139    (thread::available_parallelism().map_or(1, usize::from) / 2).clamp(1, 8)
140}