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