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