use std::error::Error;
use std::io::Write as _;
use std::thread::{self, JoinHandle};
use crossbeam_channel::{Receiver, Sender, bounded};
use osmflow::Timestamp;
use postgres::types::{FromSql, Type};
use postgres::{CopyInWriter, GenericClient};
use crate::SyncError;
use crate::copy::{HEADER, Rows, TRAILER};
pub(crate) use crate::tls::connect;
use crate::varint::unpack_ids;
pub(crate) const SCHEMA_VERSION: i32 = 3;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DbState {
pub id: i64,
pub rev: i64,
pub url: Option<String>,
pub sequence: i64,
pub timestamp: Option<Timestamp>,
pub tables: TableLayout,
}
#[derive(
Debug,
Clone,
Copy,
Default,
PartialEq,
Eq,
Hash,
strum::AsRefStr,
strum::Display,
strum::EnumString,
strum::VariantNames,
)]
#[strum(serialize_all = "lowercase")]
pub enum TableLayout {
#[default]
Packed,
Plain,
}
pub(crate) struct LayoutSql {
pub(crate) point: &'static str,
pub(crate) line: &'static str,
pub(crate) ids: &'static str,
pub(crate) after: String,
}
impl TableLayout {
pub(crate) fn sql(self, postgis: &str) -> LayoutSql {
let s = format!("\"{}\"", postgis.replace('"', "\"\""));
match self {
Self::Packed => {
let view = |t: Table| {
let columns = t
.columns()
.split(", ")
.map(|c| match (t, c) {
(Table::Ways, "nodes") => "osm.node_ids(nodes) AS nodes",
(_, "geom") => "osm.geom(geom) AS geom",
_ => c,
})
.collect::<Vec<_>>()
.join(", ");
format!(
"CREATE VIEW {} AS SELECT {columns} FROM {};",
<&str>::from(t),
t.name(self)
)
};
LayoutSql {
point: "bytea",
line: "bytea",
ids: "bytea",
after: format!(
"CREATE FUNCTION osm.geom(g bytea) RETURNS {s}.geometry LANGUAGE sql IMMUTABLE PARALLEL SAFE \
AS $$ SELECT {s}.ST_SetSRID({s}.ST_GeomFromTWKB(g), 4326) $$;\n{}\n{}\n{}",
include_str!("node_ids.sql"),
view(Table::Nodes),
view(Table::Ways)
),
}
}
Self::Plain => LayoutSql {
point: "geometry(Point, 4326)",
line: "geometry(LineString, 4326)",
ids: "int8[]",
after: String::new(),
},
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct NodeIds(pub Vec<i64>);
impl<'a> FromSql<'a> for NodeIds {
fn from_sql(ty: &Type, raw: &'a [u8]) -> Result<Self, Box<dyn Error + Sync + Send>> {
if *ty == Type::BYTEA {
Ok(Self(unpack_ids(raw)))
} else {
Vec::from_sql(ty, raw).map(Self)
}
}
fn accepts(ty: &Type) -> bool {
*ty == Type::BYTEA || *ty == Type::INT8_ARRAY
}
}
impl DbState {
pub(crate) fn read(client: &mut impl GenericClient) -> Result<Self, SyncError> {
let exists: bool = client
.query_one("SELECT to_regclass('osm.state') IS NOT NULL", &[])?
.get(0);
if !exists {
return Err(SyncError::state(
"the database has no osm schema: import a PBF file first",
));
}
let row = client
.query_opt(
"SELECT id, version, rev, url, sequence, (extract(epoch FROM timestamp) * 1000)::int8, tables \
FROM osm.state",
&[],
)?
.ok_or_else(|| SyncError::state("the import did not finish: run it again, replacing the osm schema"))?;
let version: i32 = row.get(1);
if version != SCHEMA_VERSION {
return Err(SyncError::state(format!(
"the osm schema has format {version}, but this osmflow-sync reads {SCHEMA_VERSION}: import again, \
replacing the osm schema"
)));
}
Ok(Self {
id: row.get(0),
rev: row.get::<_, i32>(2).into(),
url: row.get(3),
sequence: row.get(4),
timestamp: row.get::<_, Option<i64>>(5).map(Timestamp::from_millis),
tables: {
let name: &str = row.get(6);
name.parse().map_err(|_| {
SyncError::state(format!("unknown table layout {name:?} in osm.state"))
})?
},
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::IntoStaticStr)]
#[strum(serialize_all = "lowercase", prefix = "osm.")]
pub(crate) enum Table {
Nodes,
Ways,
Relations,
}
impl Table {
pub(crate) fn name(self, layout: TableLayout) -> &'static str {
match (self, layout) {
(Self::Nodes, TableLayout::Packed) => "osm.nodes_packed",
(Self::Ways, TableLayout::Packed) => "osm.ways_packed",
_ => self.into(),
}
}
pub(crate) fn columns(self) -> &'static str {
match self {
Self::Nodes => "id, changeset, ts, version, rev, tags, geom",
Self::Ways => "id, changeset, ts, version, minor, rev, tags, nodes, geom",
Self::Relations => {
"id, changeset, ts, version, rev, tags, member_types, member_ids, member_roles"
}
}
}
}
pub(crate) fn copy(
client: &mut impl GenericClient,
table: &str,
columns: &str,
rows: &Rows,
) -> Result<(), SyncError> {
let mut w = copy_in(client, table, columns)?;
w.write_all(&rows.buf)?;
copy_end(w)
}
fn copy_in<'a>(
client: &'a mut impl GenericClient,
table: &str,
columns: &str,
) -> Result<CopyInWriter<'a>, SyncError> {
let mut w = client.copy_in(&format!(
"COPY {table} ({columns}) FROM STDIN (FORMAT binary)"
))?;
w.write_all(HEADER)?;
Ok(w)
}
fn copy_end(mut w: CopyInWriter<'_>) -> Result<(), SyncError> {
w.write_all(TRAILER)?;
w.finish()?;
Ok(())
}
pub(crate) struct Writers {
tx: Sender<(Table, Vec<u8>)>,
threads: Vec<JoinHandle<Result<(), SyncError>>>,
}
impl Writers {
pub(crate) fn start(
url: &str,
connections: usize,
layout: TableLayout,
) -> Result<Self, SyncError> {
let (tx, rx) = bounded(connections * 4);
let threads = (0..connections.max(1))
.map(|i| {
let (url, rx) = (url.to_owned(), rx.clone());
thread::Builder::new()
.name(format!("osmflow-copy-{i}"))
.spawn(move || write(&url, &rx, layout))
})
.collect::<Result<_, _>>()?;
Ok(Self { tx, threads })
}
pub(crate) fn send(&self, table: Table, rows: Rows) -> bool {
rows.buf.is_empty() || self.tx.send((table, rows.buf)).is_ok()
}
pub(crate) fn finish(self) -> Result<(), SyncError> {
drop(self.tx);
let mut result = Ok(());
for t in self.threads {
let r = t
.join()
.unwrap_or_else(|_| Err(SyncError::state("a COPY thread panicked")));
result = result.and(r);
}
result
}
}
fn write(url: &str, rx: &Receiver<(Table, Vec<u8>)>, layout: TableLayout) -> Result<(), SyncError> {
let mut client = connect(url)?;
client.batch_execute("SET synchronous_commit = off; SET default_toast_compression = lz4")?;
let mut next = rx.recv().ok();
while let Some((table, buf)) = next {
let mut w = copy_in(&mut client, table.name(layout), table.columns())?;
w.write_all(&buf)?;
loop {
next = rx.recv().ok();
match &next {
Some((t, buf)) if *t == table => w.write_all(buf)?,
_ => break,
}
}
copy_end(w)?;
}
Ok(())
}