//! Turso-backed storage. All persistent state lives in this database; the key file and photos sit //! beside it in `data_dir`. //! //! Connections: one writer behind a tokio mutex, and a pool of read-only connections. Writes, //! transactions and read-then-write sequences use the writer; a pure SELECT may use a reader. Every //! connection gets WAL, `synchronous = FULL`, `foreign_keys = ON` and a busy timeout, and the values //! in effect are logged at boot. pub mod admin; pub mod audit; pub mod backchannel; pub mod clients; pub mod directory; pub mod invites; pub mod keys; pub mod links; pub mod mail; pub mod migrate; pub mod oidc; pub mod services; pub mod sessions; pub mod snapshot; pub mod users; use std::path::Path; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::Duration; use tokio::sync::{Mutex, MutexGuard, watch}; use turso::transaction::Transaction; use turso::{Builder, Connection, Database, IntoParams, Row, Value}; use crate::error::{Error, Result}; use crate::time::now_stamp; /// How long a statement waits for a lock held by another connection before it fails. const BUSY_TIMEOUT: Duration = Duration::from_millis(5000); /// Number of read-only connections in the pool. const READER_COUNT: usize = 4; /// Handle to the database. Cheap to clone; every clone shares the same connections. /// /// Rule for [`Store::read_conn`]: use it only for a function that is a pure SELECT and does not /// need to see a write made in the same call. Anything in a transaction, any write, and any /// read-then-write sequence goes through the writer. #[derive(Clone)] pub struct Store { inner: Arc, } struct Inner { /// Kept alive for as long as the connections are in use. _db: Database, /// The single writer. conn: Mutex, /// Read-only connections, each with `PRAGMA query_only = 1`. readers: Vec>, /// Round-robin start index for `read_conn`. next_reader: AtomicUsize, /// Counts the committed changes of the people directory. A stream waits on a receiver of it. directory: watch::Sender, } impl Store { /// Opens (creating if needed) the database at `path`, applies the connection pragmas and runs /// any pending migrations. Readers are opened after migrations so their schema view is current. pub async fn open(path: &Path) -> Result { let path_str = path.to_str().ok_or_else(|| { Error::Config(format!("database path is not UTF-8: {}", path.display())) })?; create_private_files(path)?; let db = Builder::new_local(path_str).build().await.map_err(db_err)?; let conn = db.connect().map_err(db_err)?; apply_pragmas(&conn).await?; migrate::migrate(&conn).await?; let mut readers = Vec::with_capacity(READER_COUNT); for _ in 0..READER_COUNT { let reader = db.connect().map_err(db_err)?; apply_pragmas(&reader).await?; apply_query_only(&reader).await?; readers.push(Mutex::new(reader)); } restrict_database_files(path)?; Ok(Store { inner: Arc::new(Inner { _db: db, conn: Mutex::new(conn), readers, next_reader: AtomicUsize::new(0), directory: watch::channel(0).0, }), }) } /// Returns a read-only pooled connection. It tries each reader without waiting, starting at the /// round-robin index, and falls back to waiting on the start reader when all are busy. pub async fn read_conn(&self) -> MutexGuard<'_, Connection> { let len = self.inner.readers.len(); let start = self.inner.next_reader.fetch_add(1, Ordering::Relaxed) % len; for offset in 0..len { let idx = (start + offset) % len; if let Some(guard) = self.inner.readers.get(idx).and_then(|m| m.try_lock().ok()) { return guard; } } self.inner.readers[start].lock().await } /// Runs `SELECT 1` on a pooled reader and fails when the database does not answer. The health /// route calls it with a deadline, so a stuck lock shows up as a failed probe. pub async fn ping(&self) -> Result<()> { let conn = self.read_conn().await; fetch_opt(&conn, "SELECT 1", (), |row| col_int(row, 0)) .await? .ok_or_else(missing_row) .map(|_| ()) } /// Number of user rows. Used to decide whether first-run setup is still open. pub async fn user_count(&self) -> Result { let conn = self.read_conn().await; let row = fetch_opt(&conn, "SELECT COUNT(*) FROM users", (), |row| { col_int(row, 0) }) .await? .ok_or_else(missing_row)?; u64::try_from(row).map_err(|_| Error::Database("negative count".into())) } /// Whether the database holds an account or a signing key. Both are sealed with the instance key, so /// a database like this one cannot be used with a different key. Used at boot before a key is created. pub async fn holds_sealed_data(&self) -> Result { let conn = self.read_conn().await; let count = fetch_opt( &conn, "SELECT (SELECT COUNT(*) FROM users) + (SELECT COUNT(*) FROM signing_keys)", (), |row| col_int(row, 0), ) .await? .ok_or_else(missing_row)?; Ok(count > 0) } /// The stored value of a runtime setting, or `None` when it has no override. pub async fn setting(&self, key: &str) -> Result> { let conn = self.read_conn().await; fetch_opt( &conn, "SELECT value FROM settings WHERE key = ?1", (key.to_string(),), |row| col_text(row, 0), ) .await } /// Stores (or replaces) a runtime setting. Writes through the writer connection. pub async fn set_setting(&self, key: &str, value: &str) -> Result<()> { let conn = self.inner.conn.lock().await; conn.execute( "INSERT INTO settings (key, value, updated_at) VALUES (?1, ?2, ?3) \ ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at", (key.to_string(), value.to_string(), now_stamp()), ) .await .map_err(db_err)?; Ok(()) } } /// Creates the database file and its `-wal` and `-shm` sidecars as empty 0600 files when they do not exist, /// so turso never creates them with the umask default. A file that exists is left alone here. fn create_private_files(path: &Path) -> Result<()> { use std::os::unix::fs::OpenOptionsExt; for suffix in ["", "-wal", "-shm"] { let mut name = path.as_os_str().to_owned(); name.push(suffix); match std::fs::OpenOptions::new() .write(true) .create_new(true) .mode(0o600) .open(std::path::PathBuf::from(name)) { Ok(_) => {} Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {} Err(e) => return Err(e.into()), } } Ok(()) } /// Makes the database file and its `-wal` and `-shm` sidecars private (mode 0600). They hold every row, /// including sealed secrets, so no other local user may read them whatever the process umask was. Runs /// after the connections are open, when the sidecars exist. fn restrict_database_files(path: &Path) -> Result<()> { use std::os::unix::fs::PermissionsExt; for suffix in ["", "-wal", "-shm"] { let mut name = path.as_os_str().to_owned(); name.push(suffix); let file = std::path::PathBuf::from(name); if std::fs::symlink_metadata(&file).is_ok_and(|meta| meta.file_type().is_file()) { std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600))?; } } Ok(()) } /// Ends a transaction: commits when `outcome` is `Ok`, rolls back otherwise, and returns the /// outcome. Every multi-statement write ends with this, so no path leaves a transaction open. pub async fn finish(tx: Transaction<'_>, outcome: Result) -> Result { match outcome { Ok(value) => { tx.commit().await.map_err(db_err)?; Ok(value) } Err(e) => { let _ = tx.rollback().await; Err(e) } } } /// A fresh ULID as text. Ids are ULIDs everywhere, so their text order is their creation order /// within a millisecond. pub fn new_id() -> String { ulid::Ulid::generate().to_string() } /// Converts a Turso error to the crate error. pub(crate) fn db_err(e: turso::Error) -> Error { Error::Database(e.to_string()) } pub(crate) fn missing_row() -> Error { Error::Database("expected a row that is not there".into()) } /// Makes a connection refuse writes. Turso takes `1`, not `ON`. Failure is fatal: a reader that /// could write would break the pool's rule. async fn apply_query_only(conn: &Connection) -> Result<()> { let mut rows = conn .query("PRAGMA query_only = 1", ()) .await .map_err(db_err)?; while rows.next().await.map_err(db_err)?.is_some() {} Ok(()) } /// Applies the connection pragmas. A pragma the driver refuses is logged, and the values actually in effect /// are logged afterwards. `foreign_keys` is read back and must be on: with it off, the cascades that remove a /// person's sessions, recovery codes and links would silently not run, so the start fails instead. async fn apply_pragmas(conn: &Connection) -> Result<()> { for sql in [ "PRAGMA journal_mode = WAL", "PRAGMA synchronous = FULL", "PRAGMA foreign_keys = ON", ] { let applied = async { let mut rows = conn.query(sql, ()).await?; while rows.next().await?.is_some() {} Ok::<(), turso::Error>(()) } .await; if let Err(e) = applied { tracing::warn!(pragma = sql, error = %e, "database pragma not applied"); } } if let Err(e) = conn.busy_timeout(BUSY_TIMEOUT) { tracing::warn!(error = %e, "busy_timeout not applied"); } for name in ["journal_mode", "synchronous", "foreign_keys"] { match fetch_opt(conn, &format!("PRAGMA {name}"), (), |row| { col_to_string(row, 0) }) .await { Ok(value) => tracing::info!(pragma = name, value = ?value, "database pragma in effect"), Err(e) => tracing::warn!(pragma = name, error = %e, "could not read database pragma"), } } let foreign_keys = fetch_opt(conn, "PRAGMA foreign_keys", (), |row| col_to_string(row, 0)).await?; if foreign_keys.as_deref() != Some("1") { return Err(Error::Database(format!( "foreign_keys is {foreign_keys:?} after the pragma, expected 1" ))); } Ok(()) } /// Runs a query and maps every row. Returns an empty vector for no rows. pub(crate) async fn fetch_all( conn: &Connection, sql: &str, params: P, map: impl Fn(&Row) -> Result, ) -> Result> where P: IntoParams, { let mut rows = conn.query(sql, params).await.map_err(db_err)?; let mut out = Vec::new(); while let Some(row) = rows.next().await.map_err(db_err)? { out.push(map(&row)?); } Ok(out) } /// Runs a query and maps its first row, or returns `None` when there is none. pub(crate) async fn fetch_opt( conn: &Connection, sql: &str, params: P, map: impl Fn(&Row) -> Result, ) -> Result> where P: IntoParams, { let mut rows = conn.query(sql, params).await.map_err(db_err)?; match rows.next().await.map_err(db_err)? { Some(row) => Ok(Some(map(&row)?)), None => Ok(None), } } /// Reads a text column. Any other type is a database error. pub(crate) fn col_text(row: &Row, i: usize) -> Result { match row.get_value(i).map_err(db_err)? { Value::Text(s) => Ok(s), _ => Err(Error::Database(format!("column {i} is not text"))), } } /// Reads an integer column. Any other type is a database error. pub(crate) fn col_int(row: &Row, i: usize) -> Result { match row.get_value(i).map_err(db_err)? { Value::Integer(n) => Ok(n), _ => Err(Error::Database(format!("column {i} is not an integer"))), } } /// Reads a nullable text column. SQL NULL is `None`. pub(crate) fn col_opt_text(row: &Row, i: usize) -> Result> { match row.get_value(i).map_err(db_err)? { Value::Null => Ok(None), Value::Text(s) => Ok(Some(s)), _ => Err(Error::Database(format!("column {i} is not text"))), } } /// Reads a nullable integer column. SQL NULL is `None`. pub(crate) fn col_opt_int(row: &Row, i: usize) -> Result> { match row.get_value(i).map_err(db_err)? { Value::Null => Ok(None), Value::Integer(n) => Ok(Some(n)), _ => Err(Error::Database(format!("column {i} is not an integer"))), } } /// Reads a column as text, accepting integers too. Used for PRAGMA results, which are text for /// some pragmas and integers for others. pub(crate) fn col_to_string(row: &Row, i: usize) -> Result { match row.get_value(i).map_err(db_err)? { Value::Text(s) => Ok(s), Value::Integer(n) => Ok(n.to_string()), _ => Err(Error::Database(format!( "column {i} is not text or integer" ))), } } #[cfg(test)] mod tests { use super::*; #[tokio::test] async fn open_twice_applies_migrations_once_and_keeps_data() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("im.db"); { let store = Store::open(&path).await.unwrap(); store.set_setting("invite_days", "7").await.unwrap(); } let store = Store::open(&path).await.unwrap(); assert_eq!(store.user_count().await.unwrap(), 0); assert_eq!( store.setting("invite_days").await.unwrap().as_deref(), Some("7") ); assert_eq!(store.setting("missing").await.unwrap(), None); let conn = store.read_conn().await; let applied = fetch_all(&conn, "SELECT version FROM schema_migrations", (), |row| { col_int(row, 0) }) .await .unwrap(); let expected: Vec = migrate::MIGRATIONS .iter() .map(|&(version, _)| i64::from(version)) .collect(); assert_eq!(applied, expected); } }