diff options
Diffstat (limited to 'src/db/mod.rs')
| -rw-r--r-- | src/db/mod.rs | 272 |
1 files changed, 272 insertions, 0 deletions
diff --git a/src/db/mod.rs b/src/db/mod.rs new file mode 100644 index 0000000..c11bf5a --- /dev/null +++ b/src/db/mod.rs @@ -0,0 +1,272 @@ +//! SQLite access (DESIGN.md §11a). +//! +//! The app is multi-threaded and SQLite has one writer at a time, so there is +//! exactly **one writer thread** owning the write connection. Everything that +//! mutates is sent to it over a channel as a closure and answered with a +//! `Result`. That makes "who can write" a compile-time fact (only [`Writer`] +//! hands out `&mut`-equivalent access) and removes `SQLITE_BUSY` from the +//! design entirely. Readers are thread-local, read-only connections; WAL lets +//! them proceed concurrently with the writer. + +mod migrations; +mod model; +mod queries; + +pub use migrations::MIGRATIONS; +pub use model::*; +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}; + +/// Open a connection with the pragmas every connection needs. +fn open(path: &Path, read_only: bool) -> Result<Connection> { + 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 { + // Durability of the approval trail is worth the fsync (§11a). + conn.pragma_update(None, "synchronous", "FULL") + .map_err(|e| Error::db(e.to_string()))?; + } + Ok(()) +} + +/// Apply pending migrations. Must run before the writer actor starts. +pub fn migrate(path: &Path) -> Result<u32> { + 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<dyn FnOnce(&mut Connection) + Send>; + +enum Msg { + Call(BoxedCall), + Shutdown, +} + +/// Handle on the single writer thread. +/// +/// Cheap to clone; every clone talks to the same actor. +pub struct Writer { + tx: Sender<Msg>, + path: PathBuf, + alive: Arc<AtomicBool>, +} + +impl Writer { + /// Spawn the writer actor thread. + pub fn start(path: &Path) -> Result<Self> { + let conn = open(path, false)?; + let (tx, rx) = unbounded::<Msg>(); + 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, + } + } + // Best-effort WAL checkpoint on the way out. + 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) + } + + /// Run `f` on the write connection and wait for its result. + /// + /// No transaction may span a build step: `f` should be short. Use + /// [`Writer::tx`] for atomic multi-statement mutations. + pub fn call<T>(&self, f: impl FnOnce(&mut Connection) -> Result<T> + Send + 'static) -> Result<T> + where + T: Send + 'static, + { + let (reply_tx, reply_rx) = bounded::<Result<T>>(1); + self.send(Box::new(move |conn| { + let _ = reply_tx.send(f(conn)); + }))?; + reply_rx + .recv() + .map_err(|_| Error::db("writer actor gone"))? + } + + /// Run `f` inside a single `BEGIN IMMEDIATE` transaction on the write + /// connection. This is how every multi-statement mutation is expressed. + pub fn tx<T>( + &self, + f: impl FnOnce(&mut rusqlite::Transaction<'_>) -> Result<T> + Send + 'static, + ) -> Result<T> + 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) + }) + } + + /// Fire-and-forget write (audit rows, bookkeeping where the result is unused). + pub 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); + } +} + +/// Thread-local read-only connection pool. +/// +/// One connection per thread per database file, opened read-only. HTTP handlers +/// and watchers use this; they never touch the write connection. +pub struct Readers { + path: PathBuf, +} + +thread_local! { + static POOL: std::cell::RefCell<Vec<(PathBuf, Connection)>> = const { std::cell::RefCell::new(Vec::new()) }; +} + +impl Readers { + pub fn new(path: &Path) -> Self { + Self { path: path.to_path_buf() } + } + + /// Run `f` against this thread's read-only connection. + pub fn with<T>(&self, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> { + 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"))?; + // Safety of the borrow: we only ever use one connection at a time + // per thread and `f` cannot re-enter this function for the same pool + // (it receives &Connection, not &Readers). + let conn = &pool[idx].1; + f(conn) + }) + } +} + +/// A handle bundling the writer with a reader factory; passed around as `App`. +#[derive(Clone)] +pub struct Db { + pub writer: Arc<Writer>, + pub readers: Arc<Readers>, +} + +impl Db { + pub fn open(cfg: &Config) -> Result<Self> { + let path = cfg.db_path(); + migrate(&path)?; + Self::open_migrated(&path) + } + + pub fn open_migrated(path: &Path) -> Result<Self> { + Ok(Self { + writer: Arc::new(Writer::start(path)?), + readers: Arc::new(Readers::new(path)), + }) + } + + /// Convenience: read-only query against the shared reader pool. + pub fn read<T>(&self, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> { + self.readers.with(f) + } +} + +/// Consistent snapshot for backups: `VACUUM INTO`, never `cp` of a live WAL db. +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(()) + }) +} + +/// WAL size + checkpoint lag, surfaced on the Ops page and in metrics. +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) +} |
