pub mod approvals; pub mod builds; pub mod candidates; pub mod migrations; pub mod model; pub mod queries; pub use migrations::MIGRATIONS; pub use model::*; pub(crate) fn state_col(col: usize, text: &str) -> rusqlite::Result { T::parse(text).ok_or_else(|| { rusqlite::Error::FromSqlConversionFailure( col, rusqlite::types::Type::Text, Box::new(std::io::Error::new( std::io::ErrorKind::InvalidData, format!("{} has a state outside the state machine: {text:?}", T::KIND), )), ) }) } pub use queries::*; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use crossbeam_channel::{bounded, unbounded, Sender}; use rusqlite::Connection; use crate::config::Config; use crate::error::{Error, Result}; fn open(path: &Path, read_only: bool) -> Result { let conn = if read_only { Connection::open_with_flags( path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX, ) } else { Connection::open(path) } .map_err(|e| Error::db(format!("open {}: {e}", path.display())))?; configure(&conn, read_only)?; Ok(conn) } fn configure(conn: &Connection, read_only: bool) -> Result<()> { conn.pragma_update(None, "journal_mode", "WAL") .and_then(|_| conn.pragma_update(None, "busy_timeout", 5000)) .and_then(|_| conn.pragma_update(None, "foreign_keys", "ON")) .map_err(|e| Error::db(e.to_string()))?; if !read_only { conn.pragma_update(None, "synchronous", "FULL") .map_err(|e| Error::db(e.to_string()))?; } Ok(()) } pub fn migrate(path: &Path) -> Result { let mut conn = open(path, false)?; let mut applied = 0u32; let current: u32 = conn .pragma_query_value(None, "user_version", |r| r.get(0)) .map_err(|e| Error::db(e.to_string()))?; for m in migrations::MIGRATIONS { if m.version > current { let tx = conn .transaction() .map_err(|e| Error::db(e.to_string()))?; tx.execute_batch(m.sql) .map_err(|e| Error::db(format!("migration {} ({}): {e}", m.version, m.name)))?; tx.pragma_update(None, "user_version", m.version) .map_err(|e| Error::db(e.to_string()))?; tx.commit().map_err(|e| Error::db(e.to_string()))?; applied += 1; } } if applied > 0 { let mut stmt = conn .prepare("INSERT OR IGNORE INTO settings (key, value) VALUES (?1, ?2)") .map_err(|e| Error::db(e.to_string()))?; for (k, v) in migrations::DEFAULT_SETTINGS { let _ = stmt.execute(rusqlite::params![k, *v]); } } Ok(applied) } type BoxedCall = Box; enum Msg { Call(BoxedCall), Shutdown, } pub struct Writer { tx: Sender, path: PathBuf, alive: Arc, } impl Writer { pub fn start(path: &Path) -> Result { let conn = open(path, false)?; let (tx, rx) = unbounded::(); let alive = Arc::new(AtomicBool::new(true)); let alive_thread = alive.clone(); let thread_path = path.to_path_buf(); std::thread::Builder::new() .name("db-writer".into()) .spawn(move || { let mut conn = conn; alive_thread.store(true, Ordering::SeqCst); for msg in rx.iter() { match msg { Msg::Call(f) => f(&mut conn), Msg::Shutdown => break, } } let _ = conn.pragma_update(None, "wal_checkpoint", "TRUNCATE"); alive_thread.store(false, Ordering::SeqCst); }) .map_err(|e| Error::db(format!("spawn writer: {e}")))?; Ok(Self { tx, path: thread_path, alive }) } pub fn path(&self) -> &Path { &self.path } pub fn is_alive(&self) -> bool { self.alive.load(Ordering::SeqCst) } pub(crate) fn call(&self, f: impl FnOnce(&mut Connection) -> Result + Send + 'static) -> Result where T: Send + 'static, { let (reply_tx, reply_rx) = bounded::>(1); self.send(Box::new(move |conn| { let _ = reply_tx.send(f(conn)); }))?; reply_rx .recv() .map_err(|_| Error::db("writer actor gone"))? } pub(crate) fn tx( &self, f: impl FnOnce(&mut rusqlite::Transaction<'_>) -> Result + Send + 'static, ) -> Result where T: Send + 'static, { self.call(move |conn| { let mut tx = conn .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate) .map_err(|e| Error::db(e.to_string()))?; let out = f(&mut tx)?; tx.commit().map_err(|e| Error::db(e.to_string()))?; Ok(out) }) } pub(crate) fn send(&self, f: BoxedCall) -> Result<()> { if !self.is_alive() { return Err(Error::db("writer actor gone")); } self.tx .send(Msg::Call(f)) .map_err(|_| Error::db("writer actor gone")) } pub fn shutdown(&self) { let _ = self.tx.send(Msg::Shutdown); } } #[cfg(feature = "test-support")] impl Writer { pub fn tx_for_tests( &self, f: impl FnOnce(&mut rusqlite::Transaction<'_>) -> Result + Send + 'static, ) -> Result where T: Send + 'static, { self.tx(f) } pub fn call_for_tests(&self, f: impl FnOnce(&mut Connection) -> Result + Send + 'static) -> Result where T: Send + 'static, { self.call(f) } } pub struct Readers { path: PathBuf, } thread_local! { static POOL: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; } impl Readers { pub fn new(path: &Path) -> Self { Self { path: path.to_path_buf() } } pub fn with(&self, f: impl FnOnce(&Connection) -> Result) -> Result { let path = self.path.clone(); POOL.with(|pool| { let mut pool = pool.borrow_mut(); if pool.iter().position(|(p, _)| p == &path).is_none() { pool.push((path.clone(), open(&path, true)?)); } let idx = pool .iter() .position(|(p, _)| p == &path) .ok_or_else(|| Error::db("reader pool lost entry"))?; // We only ever use one connection at a time per thread, and `f` // receives &Connection rather than &Readers, so it cannot re-enter. let conn = &pool[idx].1; f(conn) }) } } #[derive(Clone)] pub struct Db { pub writer: Arc, pub readers: Arc, } impl Db { pub fn open(cfg: &Config) -> Result { let path = cfg.db_path(); migrate(&path)?; Self::open_migrated(&path) } pub fn open_migrated(path: &Path) -> Result { Ok(Self { writer: Arc::new(Writer::start(path)?), readers: Arc::new(Readers::new(path)), }) } pub fn read(&self, f: impl FnOnce(&Connection) -> Result) -> Result { self.readers.with(f) } } pub fn backup_to(writer: &Writer, dest: &Path) -> Result<()> { let dest_s = dest.display().to_string(); writer.call(move |conn| { conn.execute("VACUUM INTO ?1", rusqlite::params![dest_s]) .map_err(|e| Error::db(e.to_string()))?; Ok(()) }) } pub fn schema_version(path: &Path) -> Result { let conn = rusqlite::Connection::open(path) .map_err(|e| Error::db(format!("{} does not open: {e}", path.display())))?; conn.query_row("PRAGMA user_version", [], |r| r.get(0)) .map_err(|e| Error::db(format!("{} has no schema version: {e}", path.display()))) } pub fn wal_stats(db: &Db) -> (u64, u64) { let db_file = std::fs::metadata(db.writer.path()).map(|m| m.len()).unwrap_or(0); let mut wal = db.writer.path().as_os_str().to_os_string(); wal.push("-wal"); let wal_file = std::fs::metadata(&wal).map(|m| m.len()).unwrap_or(0); (db_file, wal_file) }