| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | pub mod admin; |
| 10 | pub mod audit; |
| 11 | pub mod backchannel; |
| 12 | pub mod clients; |
| 13 | pub mod directory; |
| 14 | pub mod invites; |
| 15 | pub mod keys; |
| 16 | pub mod links; |
| 17 | pub mod mail; |
| 18 | pub mod migrate; |
| 19 | pub mod oidc; |
| 20 | pub mod services; |
| 21 | pub mod sessions; |
| 22 | pub mod snapshot; |
| 23 | pub mod users; |
| 24 | |
| 25 | use std::path::Path; |
| 26 | use std::sync::Arc; |
| 27 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 28 | use std::time::Duration; |
| 29 | |
| 30 | use tokio::sync::{Mutex, MutexGuard, watch}; |
| 31 | use turso::transaction::Transaction; |
| 32 | use turso::{Builder, Connection, Database, IntoParams, Row, Value}; |
| 33 | |
| 34 | use crate::error::{Error, Result}; |
| 35 | use crate::time::now_stamp; |
| 36 | |
| 37 | |
| 38 | const BUSY_TIMEOUT: Duration = Duration::from_millis(5000); |
| 39 | |
| 40 | |
| 41 | const READER_COUNT: usize = 4; |
| 42 | |
| 43 | |
| 44 | |
| 45 | |
| 46 | |
| 47 | |
| 48 | #[derive(Clone)] |
| 49 | pub struct Store { |
| 50 | inner: Arc<Inner>, |
| 51 | } |
| 52 | |
| 53 | struct Inner { |
| 54 | |
| 55 | _db: Database, |
| 56 | |
| 57 | conn: Mutex<Connection>, |
| 58 | |
| 59 | readers: Vec<Mutex<Connection>>, |
| 60 | |
| 61 | next_reader: AtomicUsize, |
| 62 | |
| 63 | directory: watch::Sender<u64>, |
| 64 | } |
| 65 | |
| 66 | impl Store { |
| 67 | |
| 68 | |
| 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 | |
| 99 | |
| 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 | |
| 113 | |
| 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 | |
| 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 | |
| 134 | |
| 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 | |
| 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 | |
| 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 | |
| 175 | |
| 176 | fn 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 | |
| 197 | |
| 198 | |
| 199 | fn 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 | |
| 214 | |
| 215 | pub 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 | |
| 229 | |
| 230 | pub fn new_id() -> String { |
| 231 | ulid::Ulid::generate().to_string() |
| 232 | } |
| 233 | |
| 234 | |
| 235 | pub(crate) fn db_err(e: turso::Error) -> Error { |
| 236 | Error::Database(e.to_string()) |
| 237 | } |
| 238 | |
| 239 | pub(crate) fn missing_row() -> Error { |
| 240 | Error::Database("expected a row that is not there".into()) |
| 241 | } |
| 242 | |
| 243 | |
| 244 | |
| 245 | async 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 | |
| 255 | |
| 256 | |
| 257 | async 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 | |
| 297 | pub(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>> |
| 303 | where |
| 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 | |
| 315 | pub(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>> |
| 321 | where |
| 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 | |
| 332 | pub(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 | |
| 340 | pub(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 | |
| 348 | pub(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 | |
| 357 | pub(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 | |
| 366 | |
| 367 | pub(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)] |
| 378 | mod 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 | } |