| 1 | use std::ops::{Deref, DerefMut}; |
| 2 | use std::panic::Location; |
| 3 | use std::path::{Path, PathBuf}; |
| 4 | use std::sync::{Mutex, MutexGuard, OnceLock}; |
| 5 | use std::time::{Duration, Instant}; |
| 6 | |
| 7 | use directories::ProjectDirs; |
| 8 | use rusqlite::{Connection, OpenFlags}; |
| 9 | |
| 10 | use crate::error::{Error, Result}; |
| 11 | use crate::migrations; |
| 12 | |
| 13 | pub const DATA_DIR_NAME: &str = "ms-teams-linux"; |
| 14 | const DATABASE_FILE: &str = "cache.sqlite3"; |
| 15 | const SLOW_WAIT: Duration = Duration::from_millis(50); |
| 16 | const SLOW_HOLD: Duration = Duration::from_millis(100); |
| 17 | const READERS: usize = 3; |
| 18 | |
| 19 | static SLOW_LOCK_REPORTER: OnceLock<fn(String)> = OnceLock::new(); |
| 20 | |
| 21 | pub fn report_slow_locks_to(reporter: fn(String)) { |
| 22 | let _ = SLOW_LOCK_REPORTER.set(reporter); |
| 23 | } |
| 24 | |
| 25 | fn report_slow_lock(message: String) { |
| 26 | if let Some(reporter) = SLOW_LOCK_REPORTER.get() { |
| 27 | reporter(message); |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | pub fn default_database_path() -> Result<PathBuf> { |
| 32 | let directories = ProjectDirs::from("", "", DATA_DIR_NAME).ok_or(Error::NoDataDirectory)?; |
| 33 | Ok(directories.data_dir().join(DATABASE_FILE)) |
| 34 | } |
| 35 | |
| 36 | pub struct Store { |
| 37 | connection: Mutex<Connection>, |
| 38 | /// WAL lets these read while the writer holds `connection`; empty for an in-memory store. |
| 39 | readers: Vec<Mutex<Connection>>, |
| 40 | } |
| 41 | |
| 42 | impl Store { |
| 43 | pub fn open_default() -> Result<Self> { |
| 44 | Self::open(&default_database_path()?) |
| 45 | } |
| 46 | |
| 47 | pub fn open(path: &Path) -> Result<Self> { |
| 48 | if let Some(parent) = path |
| 49 | .parent() |
| 50 | .filter(|parent| !parent.as_os_str().is_empty()) |
| 51 | { |
| 52 | std::fs::create_dir_all(parent).map_err(|source| Error::DataDirectory { |
| 53 | path: parent.display().to_string(), |
| 54 | source, |
| 55 | })?; |
| 56 | } |
| 57 | let connection = Connection::open(path)?; |
| 58 | connection.pragma_update(None, "journal_mode", "WAL")?; |
| 59 | let mut store = Self::from_connection(connection)?; |
| 60 | store.readers = (0..READERS) |
| 61 | .map(|_| open_reader(path).map(Mutex::new)) |
| 62 | .collect::<Result<_>>()?; |
| 63 | Ok(store) |
| 64 | } |
| 65 | |
| 66 | pub fn open_in_memory() -> Result<Self> { |
| 67 | Self::from_connection(Connection::open_in_memory()?) |
| 68 | } |
| 69 | |
| 70 | fn from_connection(mut connection: Connection) -> Result<Self> { |
| 71 | connection.pragma_update(None, "foreign_keys", "ON")?; |
| 72 | connection.pragma_update(None, "synchronous", "NORMAL")?; |
| 73 | migrations::migrate(&mut connection)?; |
| 74 | Ok(Store { |
| 75 | connection: Mutex::new(connection), |
| 76 | readers: Vec::new(), |
| 77 | }) |
| 78 | } |
| 79 | |
| 80 | pub fn schema_version(&self) -> Result<i64> { |
| 81 | Ok(self |
| 82 | .lock()? |
| 83 | .pragma_query_value(None, "user_version", |row| row.get(0))?) |
| 84 | } |
| 85 | |
| 86 | #[track_caller] |
| 87 | pub(crate) fn lock(&self) -> Result<StoreGuard<'_>> { |
| 88 | let location = Location::caller(); |
| 89 | let asked = Instant::now(); |
| 90 | let connection = self.connection.lock().map_err(|_| Error::Poisoned)?; |
| 91 | guard(connection, location, asked) |
| 92 | } |
| 93 | |
| 94 | /// A read-only connection, so a long write elsewhere does not block the caller. |
| 95 | #[track_caller] |
| 96 | pub(crate) fn read(&self) -> Result<StoreGuard<'_>> { |
| 97 | let location = Location::caller(); |
| 98 | let asked = Instant::now(); |
| 99 | let Some(first) = self.readers.first() else { |
| 100 | let connection = self.connection.lock().map_err(|_| Error::Poisoned)?; |
| 101 | return guard(connection, location, asked); |
| 102 | }; |
| 103 | let free = self |
| 104 | .readers |
| 105 | .iter() |
| 106 | .find_map(|reader| reader.try_lock().ok()); |
| 107 | let connection = match free { |
| 108 | Some(connection) => connection, |
| 109 | None => first.lock().map_err(|_| Error::Poisoned)?, |
| 110 | }; |
| 111 | guard(connection, location, asked) |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | fn open_reader(path: &Path) -> Result<Connection> { |
| 116 | let connection = Connection::open_with_flags( |
| 117 | path, |
| 118 | OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX, |
| 119 | )?; |
| 120 | connection.busy_timeout(Duration::from_secs(5))?; |
| 121 | Ok(connection) |
| 122 | } |
| 123 | |
| 124 | fn guard<'a>( |
| 125 | connection: MutexGuard<'a, Connection>, |
| 126 | location: &'static Location<'static>, |
| 127 | asked: Instant, |
| 128 | ) -> Result<StoreGuard<'a>> { |
| 129 | let waited = asked.elapsed(); |
| 130 | if waited >= SLOW_WAIT { |
| 131 | report_slow_lock(format!( |
| 132 | "store lock waited {} ms at {location} on {}", |
| 133 | waited.as_millis(), |
| 134 | thread_label() |
| 135 | )); |
| 136 | } |
| 137 | Ok(StoreGuard { |
| 138 | connection, |
| 139 | location, |
| 140 | taken: Instant::now(), |
| 141 | }) |
| 142 | } |
| 143 | |
| 144 | pub(crate) struct StoreGuard<'a> { |
| 145 | connection: MutexGuard<'a, Connection>, |
| 146 | location: &'static Location<'static>, |
| 147 | taken: Instant, |
| 148 | } |
| 149 | |
| 150 | impl Deref for StoreGuard<'_> { |
| 151 | type Target = Connection; |
| 152 | |
| 153 | fn deref(&self) -> &Connection { |
| 154 | &self.connection |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | impl DerefMut for StoreGuard<'_> { |
| 159 | fn deref_mut(&mut self) -> &mut Connection { |
| 160 | &mut self.connection |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | impl Drop for StoreGuard<'_> { |
| 165 | fn drop(&mut self) { |
| 166 | let held = self.taken.elapsed(); |
| 167 | if held >= SLOW_HOLD { |
| 168 | report_slow_lock(format!( |
| 169 | "store lock held {} ms at {} on {}", |
| 170 | held.as_millis(), |
| 171 | self.location, |
| 172 | thread_label() |
| 173 | )); |
| 174 | } |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | fn thread_label() -> String { |
| 179 | let thread = std::thread::current(); |
| 180 | thread |
| 181 | .name() |
| 182 | .map_or_else(|| format!("{:?}", thread.id()), str::to_owned) |
| 183 | } |
| 184 | |
| 185 | pub(crate) fn json_ids(ids: &[String]) -> String { |
| 186 | serde_json::to_string(ids).unwrap_or_else(|_| "[]".to_owned()) |
| 187 | } |
| 188 | |
| 189 | #[cfg(test)] |
| 190 | mod tests { |
| 191 | use super::Store; |
| 192 | |
| 193 | #[test] |
| 194 | fn a_read_does_not_wait_for_a_held_write_lock() { |
| 195 | let directory = tempfile::tempdir().unwrap(); |
| 196 | let store = Store::open(&directory.path().join("cache.sqlite3")).unwrap(); |
| 197 | store.set_meta("key", "before").unwrap(); |
| 198 | let writer = store.lock().unwrap(); |
| 199 | writer |
| 200 | .execute_batch("BEGIN IMMEDIATE; UPDATE meta SET value = 'during' WHERE key = 'key';") |
| 201 | .unwrap(); |
| 202 | assert_eq!(store.meta("key").unwrap().as_deref(), Some("before")); |
| 203 | writer.execute_batch("COMMIT;").unwrap(); |
| 204 | drop(writer); |
| 205 | assert_eq!(store.meta("key").unwrap().as_deref(), Some("during")); |
| 206 | } |
| 207 | } |