1use std::io::Write as _;
4use std::thread::{self, JoinHandle};
5
6use crossbeam_channel::{Receiver, Sender, bounded};
7use osmflow::Timestamp;
8use postgres::{CopyInWriter, GenericClient};
9
10use crate::SyncError;
11use crate::copy::{HEADER, Rows, TRAILER};
12pub(crate) use crate::tls::connect;
13
14pub(crate) const SCHEMA_VERSION: i32 = 2;
16
17#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct DbState {
20 pub id: i64,
22 pub rev: i64,
24 pub url: Option<String>,
26 pub sequence: i64,
28 pub timestamp: Option<Timestamp>,
30 pub geometry: GeometryFormat,
32}
33
34#[derive(
41 Debug,
42 Clone,
43 Copy,
44 Default,
45 PartialEq,
46 Eq,
47 Hash,
48 strum::AsRefStr,
49 strum::Display,
50 strum::EnumString,
51 strum::VariantNames,
52)]
53#[strum(serialize_all = "lowercase")]
54pub enum GeometryFormat {
55 #[default]
58 Twkb,
59 Wkb,
61}
62
63impl GeometryFormat {
64 pub(crate) fn sql(self, postgis: &str) -> (&'static str, &'static str, String) {
69 let s = format!("\"{}\"", postgis.replace('"', "\"\""));
70 match self {
71 Self::Twkb => (
72 "bytea",
73 "bytea",
74 format!(
75 "CREATE FUNCTION osm.geom(g bytea) RETURNS {s}.geometry LANGUAGE sql IMMUTABLE PARALLEL SAFE \
76 AS $$ SELECT {s}.ST_SetSRID({s}.ST_GeomFromTWKB(g), 4326) $$;"
77 ),
78 ),
79 Self::Wkb => (
80 "geometry(Point, 4326)",
81 "geometry(LineString, 4326)",
82 format!(
83 "CREATE FUNCTION osm.geom(g {s}.geometry) RETURNS {s}.geometry LANGUAGE sql IMMUTABLE \
84 PARALLEL SAFE AS $$ SELECT g $$;"
85 ),
86 ),
87 }
88 }
89}
90
91impl DbState {
92 pub(crate) fn read(client: &mut impl GenericClient) -> Result<Self, SyncError> {
94 let exists: bool = client
95 .query_one("SELECT to_regclass('osm.state') IS NOT NULL", &[])?
96 .get(0);
97 if !exists {
98 return Err(SyncError::state(
99 "the database has no osm schema: import a PBF file first",
100 ));
101 }
102 let row = client
103 .query_opt(
104 "SELECT id, version, rev, url, sequence, (extract(epoch FROM timestamp) * 1000)::int8, geometry \
105 FROM osm.state",
106 &[],
107 )?
108 .ok_or_else(|| SyncError::state("the import did not finish: run it again, replacing the osm schema"))?;
109 let version: i32 = row.get(1);
110 if version != SCHEMA_VERSION {
111 return Err(SyncError::state(format!(
112 "the osm schema has format {version}, but this osmflow-sync reads {SCHEMA_VERSION}"
113 )));
114 }
115 Ok(Self {
116 id: row.get(0),
117 rev: row.get(2),
118 url: row.get(3),
119 sequence: row.get(4),
120 timestamp: row.get::<_, Option<i64>>(5).map(Timestamp::from_millis),
121 geometry: {
122 let name: &str = row.get(6);
123 name.parse().map_err(|_| {
124 SyncError::state(format!("unknown geometry format {name:?} in osm.state"))
125 })?
126 },
127 })
128 }
129}
130
131#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::Display, strum::IntoStaticStr)]
133#[strum(serialize_all = "lowercase", prefix = "osm.")]
134pub(crate) enum Table {
135 Nodes,
136 Ways,
137 Relations,
138}
139
140impl Table {
141 pub(crate) fn columns(self) -> &'static str {
143 match self {
144 Self::Nodes => "id, version, changeset, ts, rev, tags, geom",
145 Self::Ways => "id, version, changeset, ts, minor, rev, tags, nodes, geom",
146 Self::Relations => {
147 "id, version, changeset, ts, rev, tags, member_types, member_ids, member_roles"
148 }
149 }
150 }
151}
152
153pub(crate) fn copy(
155 client: &mut impl GenericClient,
156 table: &str,
157 columns: &str,
158 rows: &Rows,
159) -> Result<(), SyncError> {
160 let mut w = copy_in(client, table, columns)?;
161 w.write_all(&rows.buf)?;
162 copy_end(w)
163}
164
165fn copy_in<'a>(
167 client: &'a mut impl GenericClient,
168 table: &str,
169 columns: &str,
170) -> Result<CopyInWriter<'a>, SyncError> {
171 let mut w = client.copy_in(&format!(
172 "COPY {table} ({columns}) FROM STDIN (FORMAT binary)"
173 ))?;
174 w.write_all(HEADER)?;
175 Ok(w)
176}
177
178fn copy_end(mut w: CopyInWriter<'_>) -> Result<(), SyncError> {
179 w.write_all(TRAILER)?;
180 w.finish()?;
181 Ok(())
182}
183
184pub(crate) struct Writers {
186 tx: Sender<(Table, Vec<u8>)>,
187 threads: Vec<JoinHandle<Result<(), SyncError>>>,
188}
189
190impl Writers {
191 pub(crate) fn start(url: &str, connections: usize) -> Result<Self, SyncError> {
192 let (tx, rx) = bounded(connections * 4);
193 let threads = (0..connections.max(1))
194 .map(|i| {
195 let (url, rx) = (url.to_owned(), rx.clone());
196 thread::Builder::new()
197 .name(format!("osmflow-copy-{i}"))
198 .spawn(move || write(&url, &rx))
199 })
200 .collect::<Result<_, _>>()?;
201 Ok(Self { tx, threads })
202 }
203
204 pub(crate) fn send(&self, table: Table, rows: Rows) -> bool {
207 rows.buf.is_empty() || self.tx.send((table, rows.buf)).is_ok()
208 }
209
210 pub(crate) fn finish(self) -> Result<(), SyncError> {
212 drop(self.tx);
213 let mut result = Ok(());
214 for t in self.threads {
215 let r = t
216 .join()
217 .unwrap_or_else(|_| Err(SyncError::state("a COPY thread panicked")));
218 result = result.and(r);
219 }
220 result
221 }
222}
223
224fn write(url: &str, rx: &Receiver<(Table, Vec<u8>)>) -> Result<(), SyncError> {
226 let mut client = connect(url)?;
227 client.batch_execute("SET synchronous_commit = off; SET default_toast_compression = lz4")?;
228 let mut next = rx.recv().ok();
229 while let Some((table, buf)) = next {
230 let mut w = copy_in(&mut client, table.into(), table.columns())?;
231 w.write_all(&buf)?;
232 loop {
233 next = rx.recv().ok();
234 match &next {
235 Some((t, buf)) if *t == table => w.write_all(buf)?,
236 _ => break,
237 }
238 }
239 copy_end(w)?;
240 }
241 Ok(())
242}