BlueGit

ict rusty-teams

Files

rusty-teams / crates / store / src / store.rs

store.rs

store.rs 6.1 KiB Download Raw
1use std::ops::{Deref, DerefMut};
2use std::panic::Location;
3use std::path::{Path, PathBuf};
4use std::sync::{Mutex, MutexGuard, OnceLock};
5use std::time::{Duration, Instant};
6
7use directories::ProjectDirs;
8use rusqlite::{Connection, OpenFlags};
9
10use crate::error::{Error, Result};
11use crate::migrations;
12
13pub const DATA_DIR_NAME: &str = "ms-teams-linux";
14const DATABASE_FILE: &str = "cache.sqlite3";
15const SLOW_WAIT: Duration = Duration::from_millis(50);
16const SLOW_HOLD: Duration = Duration::from_millis(100);
17const READERS: usize = 3;
18
19static SLOW_LOCK_REPORTER: OnceLock<fn(String)> = OnceLock::new();
20
21pub fn report_slow_locks_to(reporter: fn(String)) {
22 let _ = SLOW_LOCK_REPORTER.set(reporter);
23}
24
25fn report_slow_lock(message: String) {
26 if let Some(reporter) = SLOW_LOCK_REPORTER.get() {
27 reporter(message);
28 }
29}
30
31pub 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
36pub 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
42impl 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
115fn 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
124fn 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
144pub(crate) struct StoreGuard<'a> {
145 connection: MutexGuard<'a, Connection>,
146 location: &'static Location<'static>,
147 taken: Instant,
148}
149
150impl Deref for StoreGuard<'_> {
151 type Target = Connection;
152
153 fn deref(&self) -> &Connection {
154 &self.connection
155 }
156}
157
158impl DerefMut for StoreGuard<'_> {
159 fn deref_mut(&mut self) -> &mut Connection {
160 &mut self.connection
161 }
162}
163
164impl 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
178fn 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
185pub(crate) fn json_ids(ids: &[String]) -> String {
186 serde_json::to_string(ids).unwrap_or_else(|_| "[]".to_owned())
187}
188
189#[cfg(test)]
190mod 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}