use std::sync::Arc;
use rusqlite::{OptionalExtension, params};
use super::message::{In, Out};
use crate::sqlite::{Config, File, sql_error};
use crate::{Error, Result, Store};
pub(crate) const FILE: &str = "catalog.db";
const SCHEMA: &str = "create table if not exists homes (
file text primary key,
node text not null,
address text not null,
epoch integer not null
) strict, without rowid";
const CLAIM: &str = "insert into homes (file, node, address, epoch) values (?1, ?2, ?3, ?4)
on conflict (file) do update
set node = excluded.node, address = excluded.address, epoch = max(homes.epoch, excluded.epoch)
where homes.node = excluded.node or excluded.epoch > homes.epoch";
const HOME_OF: &str = "select node, address, epoch from homes where file = ?1";
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Home {
pub(crate) node: String,
pub(crate) address: String,
pub(crate) epoch: u64,
}
pub(crate) struct Catalog {
file: File,
}
impl Catalog {
pub(crate) fn open(store: &Store) -> Result<Catalog> {
let file = store.open_file(FILE, Config::default())?;
if !file.is_copy() {
let made =
|| file.transaction(|tx| tx.execute_batch(SCHEMA).map_err(|error| sql_error("the catalog", error)));
crate::sqlite::own_work(made)?;
}
Ok(Catalog { file })
}
pub(crate) fn home_of(&self, name: &str) -> Result<Option<Home>> {
self.file
.read(|connection| {
connection
.prepare_cached(HOME_OF)
.and_then(|mut select| select.query_row([name], read_home).optional())
.map_err(|error| sql_error("the catalog", error))
})
.map_err(|error| error.within(format!("catalog: {name}")))
}
pub(crate) fn claim(&self, store: &Store, claim: &Claim<'_>) -> Result<Home> {
if self.file.is_copy() {
let answer = super::forward::pass_on(store, FILE, claim_op(claim))?;
return decode_home(&answer).map_err(|error| error.within(format!("catalog: {}", claim.file)));
}
self.claim_here(claim)
}
fn claim_here(&self, claim: &Claim<'_>) -> Result<Home> {
let (name, node, address) = (claim.file.to_owned(), claim.node.to_owned(), claim.address.to_owned());
let epoch = i64::try_from(claim.epoch).map_err(|_| Error::invalid("an epoch past 2^63"))?;
let shown = format!("catalog: {name}");
let claimed = crate::sqlite::own_work(|| {
self.file.write(name.len() + address.len(), move |tx| {
tx.execute(CLAIM, params![name, node, address, epoch]).map_err(|error| sql_error("a claim", error))?;
tx.prepare_cached(HOME_OF)
.and_then(|mut select| select.query_row([&name], read_home))
.map_err(|error| sql_error("a claim", error))
})
});
claimed.map_err(|error| error.within(shown))
}
pub(crate) fn close(&self) {
let _ = self.file.close();
}
}
fn read_home(row: &rusqlite::Row<'_>) -> rusqlite::Result<Home> {
Ok(Home { node: row.get(0)?, address: row.get(1)?, epoch: row.get::<_, i64>(2)? as u64 })
}
pub(crate) struct Claim<'a> {
pub(crate) file: &'a str,
pub(crate) node: &'a str,
pub(crate) address: &'a str,
pub(crate) epoch: u64,
}
fn claim_op(claim: &Claim<'_>) -> Vec<u8> {
let mut out = Out(vec![super::forward::CATALOG]);
out.text(claim.file);
out.text(claim.node);
out.text(claim.address);
out.long(claim.epoch);
out.0
}
pub(crate) fn run(store: &Store, body: &[u8]) -> Result<(Vec<u8>, String)> {
let mut at = In { bytes: body, at: 0 };
let (file, node, address, epoch) = (at.text()?, at.text()?, at.text()?, at.long()?);
let catalog = store.node().ok_or_else(|| Error::invalid("a claim for the catalog of a store that is no node"))?;
let claim = Claim { file: &file, node: &node, address: &address, epoch };
let home = catalog.catalog(store)?.claim(store, &claim)?;
Ok((encode_home(&home), FILE.to_owned()))
}
fn encode_home(home: &Home) -> Vec<u8> {
let mut out = Out(Vec::new());
out.text(&home.node);
out.text(&home.address);
out.long(home.epoch);
out.0
}
fn decode_home(bytes: &[u8]) -> Result<Home> {
let mut at = In { bytes, at: 0 };
Ok(Home { node: at.text()?, address: at.text()?, epoch: at.long()? })
}
pub(crate) type Held = std::sync::Mutex<Option<Arc<Catalog>>>;