BlueGit

ict rusty-teams

Files

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

store.rs

store.rs 3.9 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;
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);
17
18static SLOW_LOCK_REPORTER: OnceLock<fn(String)> = OnceLock::new();
19
20pub fn report_slow_locks_to(reporter: fn(String)) {
21 let _ = SLOW_LOCK_REPORTER.set(reporter);
22}
23
24fn report_slow_lock(message: String) {
25 if let Some(reporter) = SLOW_LOCK_REPORTER.get() {
26 reporter(message);
27 }
28}
29
30pub fn default_database_path() -> Result<PathBuf> {
31 let directories = ProjectDirs::from("", "", DATA_DIR_NAME).ok_or(Error::NoDataDirectory)?;
32 Ok(directories.data_dir().join(DATABASE_FILE))
33}
34
35pub struct Store {
36 connection: Mutex<Connection>,
37}
38
39impl Store {
40 pub fn open_default() -> Result<Self> {
41 Self::open(&default_database_path()?)
42 }
43
44 pub fn open(path: &Path) -> Result<Self> {
45 if let Some(parent) = path
46 .parent()
47 .filter(|parent| !parent.as_os_str().is_empty())
48 {
49 std::fs::create_dir_all(parent).map_err(|source| Error::DataDirectory {
50 path: parent.display().to_string(),
51 source,
52 })?;
53 }
54 let connection = Connection::open(path)?;
55 connection.pragma_update(None, "journal_mode", "WAL")?;
56 Self::from_connection(connection)
57 }
58
59 pub fn open_in_memory() -> Result<Self> {
60 Self::from_connection(Connection::open_in_memory()?)
61 }
62
63 fn from_connection(mut connection: Connection) -> Result<Self> {
64 connection.pragma_update(None, "foreign_keys", "ON")?;
65 connection.pragma_update(None, "synchronous", "NORMAL")?;
66 migrations::migrate(&mut connection)?;
67 Ok(Store {
68 connection: Mutex::new(connection),
69 })
70 }
71
72 pub fn schema_version(&self) -> Result<i64> {
73 Ok(self
74 .lock()?
75 .pragma_query_value(None, "user_version", |row| row.get(0))?)
76 }
77
78 #[track_caller]
79 pub(crate) fn lock(&self) -> Result<StoreGuard<'_>> {
80 let location = Location::caller();
81 let asked = Instant::now();
82 let connection = self.connection.lock().map_err(|_| Error::Poisoned)?;
83 let waited = asked.elapsed();
84 if waited >= SLOW_WAIT {
85 report_slow_lock(format!(
86 "store lock waited {} ms at {location} on {}",
87 waited.as_millis(),
88 thread_label()
89 ));
90 }
91 Ok(StoreGuard {
92 connection,
93 location,
94 taken: Instant::now(),
95 })
96 }
97}
98
99pub(crate) struct StoreGuard<'a> {
100 connection: MutexGuard<'a, Connection>,
101 location: &'static Location<'static>,
102 taken: Instant,
103}
104
105impl Deref for StoreGuard<'_> {
106 type Target = Connection;
107
108 fn deref(&self) -> &Connection {
109 &self.connection
110 }
111}
112
113impl DerefMut for StoreGuard<'_> {
114 fn deref_mut(&mut self) -> &mut Connection {
115 &mut self.connection
116 }
117}
118
119impl Drop for StoreGuard<'_> {
120 fn drop(&mut self) {
121 let held = self.taken.elapsed();
122 if held >= SLOW_HOLD {
123 report_slow_lock(format!(
124 "store lock held {} ms at {} on {}",
125 held.as_millis(),
126 self.location,
127 thread_label()
128 ));
129 }
130 }
131}
132
133fn thread_label() -> String {
134 let thread = std::thread::current();
135 thread
136 .name()
137 .map_or_else(|| format!("{:?}", thread.id()), str::to_owned)
138}
139
140pub(crate) fn json_ids(ids: &[String]) -> String {
141 serde_json::to_string(ids).unwrap_or_else(|_| "[]".to_owned())
142}