Skip to main content

osmflow_sync/
lib.rs

1#![doc = include_str!("../README.md")]
2
3mod copy;
4mod db;
5mod error;
6mod files;
7mod follow;
8mod import;
9mod index;
10mod rebuild;
11mod sort;
12mod stop;
13mod tls;
14mod update;
15mod varint;
16
17use std::path::{Path, PathBuf};
18use std::{fmt, thread};
19
20use osmflow::nodes::PagedStore;
21use osmflow::nodes::prelude::*;
22use osmflow::osc::Replication;
23use postgres::Client;
24
25pub use crate::db::{DbState, TableLayout};
26pub use crate::error::SyncError;
27pub use crate::follow::{FollowError, FollowOpts};
28pub use crate::import::{ImportOpts, ImportStats};
29pub use crate::rebuild::{Rebuild, RebuildStats};
30#[cfg(feature = "signals")]
31pub use crate::stop::{Signal, SignalError, SignalGuard};
32pub use crate::stop::{Stop, StopReason};
33pub use crate::tls::TlsError;
34pub use crate::update::{UpdateOpts, UpdateStats};
35
36/// A database kept current from replication, and the directory of its node file and reverse index.
37#[derive(Clone)]
38pub struct Mirror {
39    url: String,
40    dir: PathBuf,
41}
42
43/// Without the database's URL, which may hold a password.
44impl fmt::Debug for Mirror {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        f.debug_struct("Mirror")
47            .field("dir", &self.dir)
48            .finish_non_exhaustive()
49    }
50}
51
52/// The revision and identity of the node file or the reverse index.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub struct FileStamp {
55    /// The identity of the database the file was made for, which must be the database's; none for a node file whose
56    /// rebuild was cut short.
57    pub id: Option<i64>,
58    /// The database revision the file is up to.
59    pub rev: i64,
60}
61
62/// Where the database and its files are.
63#[derive(Debug)]
64pub struct Status {
65    /// The database's position.
66    pub db: DbState,
67    /// The node file's stamp, or why it could not be read.
68    pub nodes: Result<FileStamp, SyncError>,
69    /// The reverse index's stamp, or why it could not be read.
70    pub index: Result<FileStamp, SyncError>,
71}
72
73impl Mirror {
74    /// A mirror in the database at `url` (`postgresql://user@host/db`, or `host=… user=…`), with its files in `dir`.
75    /// Connections use TLS as its `sslmode` and `sslrootcert` ask, as the [connections](crate#connections) section
76    /// says.
77    pub fn new(url: impl Into<String>, dir: impl Into<PathBuf>) -> Self {
78        Self {
79            url: url.into(),
80            dir: dir.into(),
81        }
82    }
83
84    /// Creates the `osm` schema from a PBF file, which must be sorted by type and ID as published files are, and makes
85    /// the node file and the reverse index in the directory, replacing any there.
86    ///
87    /// The file's replication sequence is the one [`ImportOpts::sequence`] or its header gives. `replication`, the
88    /// stream [`ImportOpts::replication_url`] or the header names, finds it from the file's timestamp when neither
89    /// does, as for a planet file, and checks a sequence given in the options against that timestamp when the header
90    /// gives none for the stream.
91    pub fn import(
92        &self,
93        pbf: impl AsRef<Path>,
94        replication: Option<&Replication>,
95        opts: &ImportOpts,
96    ) -> Result<ImportStats, SyncError> {
97        import::import(self, pbf.as_ref(), replication, opts)
98    }
99
100    /// [`open`](Self::open), then [`OpenMirror::update`]: the diffs of `replication` after the database's sequence.
101    pub fn update(
102        &self,
103        replication: &Replication,
104        opts: &UpdateOpts,
105    ) -> Result<UpdateStats, SyncError> {
106        self.open()?.update(replication, opts)
107    }
108
109    /// Connects to the database and opens the reverse index, checked against the database and brought up to it if a
110    /// crash left it behind: an error if it is missing, or of another database or ahead of it, which
111    /// [`rebuild`](Self::rebuild) fixes. The node file is opened by the first update, and stays open with the index
112    /// until the mirror is dropped; only one process can have either open at a time.
113    pub fn open(&self) -> Result<OpenMirror, SyncError> {
114        let mut client = db::connect(&self.url)?;
115        let state = DbState::read(&mut client)?;
116        let mut open = OpenMirror {
117            mirror: self.clone(),
118            client,
119            index: index::ReverseIndex::open(&self.index_path())?,
120            store: None,
121            temp_tables: false,
122        };
123        open.sync_index(&state)?;
124        Ok(open)
125    }
126
127    /// Makes the node file and the reverse index again, up to the database's revision. The database is only read.
128    pub fn rebuild(&self, from: &Rebuild<'_>) -> Result<RebuildStats, SyncError> {
129        rebuild::rebuild(self, from)
130    }
131
132    /// The database's position in its replication stream.
133    pub fn state(&self) -> Result<DbState, SyncError> {
134        DbState::read(&mut db::connect(&self.url)?)
135    }
136
137    /// The database's position, and its files' stamps.
138    pub fn status(&self) -> Result<Status, SyncError> {
139        let db = self.state()?;
140        let nodes = PagedStore::open_read_only(self.node_path())
141            .map(|s| FileStamp {
142                id: files::node_file_id(&s),
143                rev: s.stamp().cast_signed(),
144            })
145            .map_err(SyncError::from);
146        let index = index::ReverseIndex::open(&self.index_path())
147            .and_then(|i| i.stamp())
148            .map(|(id, rev)| FileStamp { id: Some(id), rev });
149        Ok(Status { db, nodes, index })
150    }
151
152    /// The node file.
153    #[must_use]
154    pub fn node_path(&self) -> PathBuf {
155        self.dir.join("nodes.cache")
156    }
157
158    /// The reverse index.
159    #[must_use]
160    pub fn index_path(&self) -> PathBuf {
161        self.dir.join("ways.redb")
162    }
163}
164
165/// A [`Mirror`] open for updates and lookups, from [`Mirror::open`]: its database connection, its reverse index, and
166/// after the first update its node file. An update borrows it mutably and a lookup shares it, so no lookup runs while
167/// a batch writes.
168pub struct OpenMirror {
169    mirror: Mirror,
170    client: Client,
171    index: index::ReverseIndex,
172    /// Taken out during an update, and put back when it succeeds.
173    store: Option<PagedStore>,
174    /// Whether the connection has the temporary tables a batch copies its rows into.
175    temp_tables: bool,
176}
177
178/// A way through a node, from the reverse index.
179#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
180pub struct NodeWay {
181    /// The node's ID.
182    pub node: i64,
183    /// The way's ID.
184    pub way: i64,
185}
186
187impl OpenMirror {
188    /// The ways through `nodes`, which may be in any order and repeat, sorted by node and way: the lookup an update
189    /// makes to find the ways a moved node changes. Negative node IDs, which only editors' files have, find none.
190    ///
191    /// The index lists every way through a node, but may list a way that no longer has it, after a crash between the
192    /// database's commit and the index's: check the ways against their node lists in `osm.ways`. After an update
193    /// fails, it may also miss ways until the next update succeeds.
194    pub fn ways_through(&self, nodes: &[i64]) -> Result<Vec<NodeWay>, SyncError> {
195        let nodes = nodes.iter().filter_map(|&n| u64::try_from(n).ok());
196        Ok(self
197            .index
198            .ways_of(nodes)?
199            .into_iter()
200            .map(|(node, way)| NodeWay {
201                node: node.cast_signed(),
202                way: way.cast_signed(),
203            })
204            .collect())
205    }
206}
207
208/// The connections an import copies on by default: half the cores, from 1 to 8.
209fn default_connections() -> usize {
210    (thread::available_parallelism().map_or(1, usize::from) / 2).clamp(1, 8)
211}