forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

mod.rs409 lines, 14.3 KiBHistoryRawDownload
1//! Turso-backed storage. All persistent state lives in this database; the key file and photos sit
2//! beside it in `data_dir`.
3//!
4//! Connections: one writer behind a tokio mutex, and a pool of read-only connections. Writes,
5//! transactions and read-then-write sequences use the writer; a pure SELECT may use a reader. Every
6//! connection gets WAL, `synchronous = FULL`, `foreign_keys = ON` and a busy timeout, and the values
7//! in effect are logged at boot.
8
9pub mod admin;
10pub mod audit;
11pub mod backchannel;
12pub mod clients;
13pub mod directory;
14pub mod invites;
15pub mod keys;
16pub mod links;
17pub mod mail;
18pub mod migrate;
19pub mod oidc;
20pub mod services;
21pub mod sessions;
22pub mod snapshot;
23pub mod users;
24
25use std::path::Path;
26use std::sync::Arc;
27use std::sync::atomic::{AtomicUsize, Ordering};
28use std::time::Duration;
29
30use tokio::sync::{Mutex, MutexGuard, watch};
31use turso::transaction::Transaction;
32use turso::{Builder, Connection, Database, IntoParams, Row, Value};
33
34use crate::error::{Error, Result};
35use crate::time::now_stamp;
36
37/// How long a statement waits for a lock held by another connection before it fails.
38const BUSY_TIMEOUT: Duration = Duration::from_millis(5000);
39
40/// Number of read-only connections in the pool.
41const READER_COUNT: usize = 4;
42
43/// Handle to the database. Cheap to clone; every clone shares the same connections.
44///
45/// Rule for [`Store::read_conn`]: use it only for a function that is a pure SELECT and does not
46/// need to see a write made in the same call. Anything in a transaction, any write, and any
47/// read-then-write sequence goes through the writer.
48#[derive(Clone)]
49pub struct Store {
50 inner: Arc<Inner>,
51}
52
53struct Inner {
54 /// Kept alive for as long as the connections are in use.
55 _db: Database,
56 /// The single writer.
57 conn: Mutex<Connection>,
58 /// Read-only connections, each with `PRAGMA query_only = 1`.
59 readers: Vec<Mutex<Connection>>,
60 /// Round-robin start index for `read_conn`.
61 next_reader: AtomicUsize,
62 /// Counts the committed changes of the people directory. A stream waits on a receiver of it.
63 directory: watch::Sender<u64>,
64}
65
66impl Store {
67 /// Opens (creating if needed) the database at `path`, applies the connection pragmas and runs
68 /// any pending migrations. Readers are opened after migrations so their schema view is current.
69 pub async fn open(path: &Path) -> Result<Store> {
70 let path_str = path.to_str().ok_or_else(|| {
71 Error::Config(format!("database path is not UTF-8: {}", path.display()))
72 })?;
73 create_private_files(path)?;
74 let db = Builder::new_local(path_str).build().await.map_err(db_err)?;
75 let conn = db.connect().map_err(db_err)?;
76 apply_pragmas(&conn).await?;
77 migrate::migrate(&conn).await?;
78
79 let mut readers = Vec::with_capacity(READER_COUNT);
80 for _ in 0..READER_COUNT {
81 let reader = db.connect().map_err(db_err)?;
82 apply_pragmas(&reader).await?;
83 apply_query_only(&reader).await?;
84 readers.push(Mutex::new(reader));
85 }
86 restrict_database_files(path)?;
87 Ok(Store {
88 inner: Arc::new(Inner {
89 _db: db,
90 conn: Mutex::new(conn),
91 readers,
92 next_reader: AtomicUsize::new(0),
93 directory: watch::channel(0).0,
94 }),
95 })
96 }
97
98 /// Returns a read-only pooled connection. It tries each reader without waiting, starting at the
99 /// round-robin index, and falls back to waiting on the start reader when all are busy.
100 pub async fn read_conn(&self) -> MutexGuard<'_, Connection> {
101 let len = self.inner.readers.len();
102 let start = self.inner.next_reader.fetch_add(1, Ordering::Relaxed) % len;
103 for offset in 0..len {
104 let idx = (start + offset) % len;
105 if let Some(guard) = self.inner.readers.get(idx).and_then(|m| m.try_lock().ok()) {
106 return guard;
107 }
108 }
109 self.inner.readers[start].lock().await
110 }
111
112 /// Runs `SELECT 1` on a pooled reader and fails when the database does not answer. The health
113 /// route calls it with a deadline, so a stuck lock shows up as a failed probe.
114 pub async fn ping(&self) -> Result<()> {
115 let conn = self.read_conn().await;
116 fetch_opt(&conn, "SELECT 1", (), |row| col_int(row, 0))
117 .await?
118 .ok_or_else(missing_row)
119 .map(|_| ())
120 }
121
122 /// Number of user rows. Used to decide whether first-run setup is still open.
123 pub async fn user_count(&self) -> Result<u64> {
124 let conn = self.read_conn().await;
125 let row = fetch_opt(&conn, "SELECT COUNT(*) FROM users", (), |row| {
126 col_int(row, 0)
127 })
128 .await?
129 .ok_or_else(missing_row)?;
130 u64::try_from(row).map_err(|_| Error::Database("negative count".into()))
131 }
132
133 /// Whether the database holds an account or a signing key. Both are sealed with the instance key, so
134 /// a database like this one cannot be used with a different key. Used at boot before a key is created.
135 pub async fn holds_sealed_data(&self) -> Result<bool> {
136 let conn = self.read_conn().await;
137 let count = fetch_opt(
138 &conn,
139 "SELECT (SELECT COUNT(*) FROM users) + (SELECT COUNT(*) FROM signing_keys)",
140 (),
141 |row| col_int(row, 0),
142 )
143 .await?
144 .ok_or_else(missing_row)?;
145 Ok(count > 0)
146 }
147
148 /// The stored value of a runtime setting, or `None` when it has no override.
149 pub async fn setting(&self, key: &str) -> Result<Option<String>> {
150 let conn = self.read_conn().await;
151 fetch_opt(
152 &conn,
153 "SELECT value FROM settings WHERE key = ?1",
154 (key.to_string(),),
155 |row| col_text(row, 0),
156 )
157 .await
158 }
159
160 /// Stores (or replaces) a runtime setting. Writes through the writer connection.
161 pub async fn set_setting(&self, key: &str, value: &str) -> Result<()> {
162 let conn = self.inner.conn.lock().await;
163 conn.execute(
164 "INSERT INTO settings (key, value, updated_at) VALUES (?1, ?2, ?3) \
165 ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at",
166 (key.to_string(), value.to_string(), now_stamp()),
167 )
168 .await
169 .map_err(db_err)?;
170 Ok(())
171 }
172}
173
174/// Creates the database file and its `-wal` and `-shm` sidecars as empty 0600 files when they do not exist,
175/// so turso never creates them with the umask default. A file that exists is left alone here.
176fn create_private_files(path: &Path) -> Result<()> {
177 use std::os::unix::fs::OpenOptionsExt;
178
179 for suffix in ["", "-wal", "-shm"] {
180 let mut name = path.as_os_str().to_owned();
181 name.push(suffix);
182 match std::fs::OpenOptions::new()
183 .write(true)
184 .create_new(true)
185 .mode(0o600)
186 .open(std::path::PathBuf::from(name))
187 {
188 Ok(_) => {}
189 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
190 Err(e) => return Err(e.into()),
191 }
192 }
193 Ok(())
194}
195
196/// Makes the database file and its `-wal` and `-shm` sidecars private (mode 0600). They hold every row,
197/// including sealed secrets, so no other local user may read them whatever the process umask was. Runs
198/// after the connections are open, when the sidecars exist.
199fn restrict_database_files(path: &Path) -> Result<()> {
200 use std::os::unix::fs::PermissionsExt;
201
202 for suffix in ["", "-wal", "-shm"] {
203 let mut name = path.as_os_str().to_owned();
204 name.push(suffix);
205 let file = std::path::PathBuf::from(name);
206 if std::fs::symlink_metadata(&file).is_ok_and(|meta| meta.file_type().is_file()) {
207 std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600))?;
208 }
209 }
210 Ok(())
211}
212
213/// Ends a transaction: commits when `outcome` is `Ok`, rolls back otherwise, and returns the
214/// outcome. Every multi-statement write ends with this, so no path leaves a transaction open.
215pub async fn finish<T>(tx: Transaction<'_>, outcome: Result<T>) -> Result<T> {
216 match outcome {
217 Ok(value) => {
218 tx.commit().await.map_err(db_err)?;
219 Ok(value)
220 }
221 Err(e) => {
222 let _ = tx.rollback().await;
223 Err(e)
224 }
225 }
226}
227
228/// A fresh ULID as text. Ids are ULIDs everywhere, so their text order is their creation order
229/// within a millisecond.
230pub fn new_id() -> String {
231 ulid::Ulid::generate().to_string()
232}
233
234/// Converts a Turso error to the crate error.
235pub(crate) fn db_err(e: turso::Error) -> Error {
236 Error::Database(e.to_string())
237}
238
239pub(crate) fn missing_row() -> Error {
240 Error::Database("expected a row that is not there".into())
241}
242
243/// Makes a connection refuse writes. Turso takes `1`, not `ON`. Failure is fatal: a reader that
244/// could write would break the pool's rule.
245async fn apply_query_only(conn: &Connection) -> Result<()> {
246 let mut rows = conn
247 .query("PRAGMA query_only = 1", ())
248 .await
249 .map_err(db_err)?;
250 while rows.next().await.map_err(db_err)?.is_some() {}
251 Ok(())
252}
253
254/// Applies the connection pragmas. A pragma the driver refuses is logged, and the values actually in effect
255/// are logged afterwards. `foreign_keys` is read back and must be on: with it off, the cascades that remove a
256/// person's sessions, recovery codes and links would silently not run, so the start fails instead.
257async fn apply_pragmas(conn: &Connection) -> Result<()> {
258 for sql in [
259 "PRAGMA journal_mode = WAL",
260 "PRAGMA synchronous = FULL",
261 "PRAGMA foreign_keys = ON",
262 ] {
263 let applied = async {
264 let mut rows = conn.query(sql, ()).await?;
265 while rows.next().await?.is_some() {}
266 Ok::<(), turso::Error>(())
267 }
268 .await;
269 if let Err(e) = applied {
270 tracing::warn!(pragma = sql, error = %e, "database pragma not applied");
271 }
272 }
273 if let Err(e) = conn.busy_timeout(BUSY_TIMEOUT) {
274 tracing::warn!(error = %e, "busy_timeout not applied");
275 }
276 for name in ["journal_mode", "synchronous", "foreign_keys"] {
277 match fetch_opt(conn, &format!("PRAGMA {name}"), (), |row| {
278 col_to_string(row, 0)
279 })
280 .await
281 {
282 Ok(value) => tracing::info!(pragma = name, value = ?value, "database pragma in effect"),
283 Err(e) => tracing::warn!(pragma = name, error = %e, "could not read database pragma"),
284 }
285 }
286 let foreign_keys =
287 fetch_opt(conn, "PRAGMA foreign_keys", (), |row| col_to_string(row, 0)).await?;
288 if foreign_keys.as_deref() != Some("1") {
289 return Err(Error::Database(format!(
290 "foreign_keys is {foreign_keys:?} after the pragma, expected 1"
291 )));
292 }
293 Ok(())
294}
295
296/// Runs a query and maps every row. Returns an empty vector for no rows.
297pub(crate) async fn fetch_all<T, P>(
298 conn: &Connection,
299 sql: &str,
300 params: P,
301 map: impl Fn(&Row) -> Result<T>,
302) -> Result<Vec<T>>
303where
304 P: IntoParams,
305{
306 let mut rows = conn.query(sql, params).await.map_err(db_err)?;
307 let mut out = Vec::new();
308 while let Some(row) = rows.next().await.map_err(db_err)? {
309 out.push(map(&row)?);
310 }
311 Ok(out)
312}
313
314/// Runs a query and maps its first row, or returns `None` when there is none.
315pub(crate) async fn fetch_opt<T, P>(
316 conn: &Connection,
317 sql: &str,
318 params: P,
319 map: impl Fn(&Row) -> Result<T>,
320) -> Result<Option<T>>
321where
322 P: IntoParams,
323{
324 let mut rows = conn.query(sql, params).await.map_err(db_err)?;
325 match rows.next().await.map_err(db_err)? {
326 Some(row) => Ok(Some(map(&row)?)),
327 None => Ok(None),
328 }
329}
330
331/// Reads a text column. Any other type is a database error.
332pub(crate) fn col_text(row: &Row, i: usize) -> Result<String> {
333 match row.get_value(i).map_err(db_err)? {
334 Value::Text(s) => Ok(s),
335 _ => Err(Error::Database(format!("column {i} is not text"))),
336 }
337}
338
339/// Reads an integer column. Any other type is a database error.
340pub(crate) fn col_int(row: &Row, i: usize) -> Result<i64> {
341 match row.get_value(i).map_err(db_err)? {
342 Value::Integer(n) => Ok(n),
343 _ => Err(Error::Database(format!("column {i} is not an integer"))),
344 }
345}
346
347/// Reads a nullable text column. SQL NULL is `None`.
348pub(crate) fn col_opt_text(row: &Row, i: usize) -> Result<Option<String>> {
349 match row.get_value(i).map_err(db_err)? {
350 Value::Null => Ok(None),
351 Value::Text(s) => Ok(Some(s)),
352 _ => Err(Error::Database(format!("column {i} is not text"))),
353 }
354}
355
356/// Reads a nullable integer column. SQL NULL is `None`.
357pub(crate) fn col_opt_int(row: &Row, i: usize) -> Result<Option<i64>> {
358 match row.get_value(i).map_err(db_err)? {
359 Value::Null => Ok(None),
360 Value::Integer(n) => Ok(Some(n)),
361 _ => Err(Error::Database(format!("column {i} is not an integer"))),
362 }
363}
364
365/// Reads a column as text, accepting integers too. Used for PRAGMA results, which are text for
366/// some pragmas and integers for others.
367pub(crate) fn col_to_string(row: &Row, i: usize) -> Result<String> {
368 match row.get_value(i).map_err(db_err)? {
369 Value::Text(s) => Ok(s),
370 Value::Integer(n) => Ok(n.to_string()),
371 _ => Err(Error::Database(format!(
372 "column {i} is not text or integer"
373 ))),
374 }
375}
376
377#[cfg(test)]
378mod tests {
379 use super::*;
380
381 #[tokio::test]
382 async fn open_twice_applies_migrations_once_and_keeps_data() {
383 let dir = tempfile::tempdir().unwrap();
384 let path = dir.path().join("im.db");
385 {
386 let store = Store::open(&path).await.unwrap();
387 store.set_setting("invite_days", "7").await.unwrap();
388 }
389 let store = Store::open(&path).await.unwrap();
390 assert_eq!(store.user_count().await.unwrap(), 0);
391 assert_eq!(
392 store.setting("invite_days").await.unwrap().as_deref(),
393 Some("7")
394 );
395 assert_eq!(store.setting("missing").await.unwrap(), None);
396
397 let conn = store.read_conn().await;
398 let applied = fetch_all(&conn, "SELECT version FROM schema_migrations", (), |row| {
399 col_int(row, 0)
400 })
401 .await
402 .unwrap();
403 let expected: Vec<i64> = migrate::MIGRATIONS
404 .iter()
405 .map(|&(version, _)| i64::from(version))
406 .collect();
407 assert_eq!(applied, expected);
408 }
409}