1use anyhow::Context;
2use futures::{channel::oneshot, Future, FutureExt};
3use lazy_static::lazy_static;
4use parking_lot::{Mutex, RwLock};
5use std::{collections::HashMap, marker::PhantomData, ops::Deref, sync::Arc, thread};
6use thread_local::ThreadLocal;
7
8use crate::{connection::Connection, domain::Migrator, util::UnboundedSyncSender};
9
10const MIGRATION_RETRIES: usize = 10;
11
12type QueuedWrite = Box<dyn 'static + Send + FnOnce()>;
13type WriteQueueConstructor =
14 Box<dyn 'static + Send + FnMut() -> Box<dyn 'static + Send + Sync + Fn(QueuedWrite)>>;
15lazy_static! {
16 /// List of queues of tasks by database uri. This lets us serialize writes to the database
17 /// and have a single worker thread per db file. This means many thread safe connections
18 /// (possibly with different migrations) could all be communicating with the same background
19 /// thread.
20 static ref QUEUES: RwLock<HashMap<Arc<str>, Box<dyn 'static + Send + Sync + Fn(QueuedWrite)>>> =
21 Default::default();
22}
23
24/// Thread safe connection to a given database file or in memory db. This can be cloned, shared, static,
25/// whatever. It derefs to a synchronous connection by thread that is read only. A write capable connection
26/// may be accessed by passing a callback to the `write` function which will queue the callback
27pub struct ThreadSafeConnection<M: Migrator + 'static = ()> {
28 uri: Arc<str>,
29 persistent: bool,
30 connection_initialize_query: Option<&'static str>,
31 connections: Arc<ThreadLocal<Connection>>,
32 _migrator: PhantomData<*mut M>,
33}
34
35unsafe impl<M: Migrator> Send for ThreadSafeConnection<M> {}
36unsafe impl<M: Migrator> Sync for ThreadSafeConnection<M> {}
37
38pub struct ThreadSafeConnectionBuilder<M: Migrator + 'static = ()> {
39 db_initialize_query: Option<&'static str>,
40 write_queue_constructor: Option<WriteQueueConstructor>,
41 connection: ThreadSafeConnection<M>,
42}
43
44impl<M: Migrator> ThreadSafeConnectionBuilder<M> {
45 /// Sets the query to run every time a connection is opened. This must
46 /// be infallible (EG only use pragma statements) and not cause writes.
47 /// to the db or it will panic.
48 pub fn with_connection_initialize_query(mut self, initialize_query: &'static str) -> Self {
49 self.connection.connection_initialize_query = Some(initialize_query);
50 self
51 }
52
53 /// Queues an initialization query for the database file. This must be infallible
54 /// but may cause changes to the database file such as with `PRAGMA journal_mode`
55 pub fn with_db_initialization_query(mut self, initialize_query: &'static str) -> Self {
56 self.db_initialize_query = Some(initialize_query);
57 self
58 }
59
60 /// Specifies how the thread safe connection should serialize writes. If provided
61 /// the connection will call the write_queue_constructor for each database file in
62 /// this process. The constructor is responsible for setting up a background thread or
63 /// async task which handles queued writes with the provided connection.
64 pub fn with_write_queue_constructor(
65 mut self,
66 write_queue_constructor: WriteQueueConstructor,
67 ) -> Self {
68 self.write_queue_constructor = Some(write_queue_constructor);
69 self
70 }
71
72 pub async fn build(self) -> anyhow::Result<ThreadSafeConnection<M>> {
73 self.connection
74 .initialize_queues(self.write_queue_constructor);
75
76 let db_initialize_query = self.db_initialize_query;
77
78 self.connection
79 .write(move |connection| {
80 if let Some(db_initialize_query) = db_initialize_query {
81 connection.exec(db_initialize_query).with_context(|| {
82 format!(
83 "Db initialize query failed to execute: {}",
84 db_initialize_query
85 )
86 })?()?;
87 }
88
89 // Retry failed migrations in case they were run in parallel from different
90 // processes. This gives a best attempt at migrating before bailing
91 let mut migration_result =
92 anyhow::Result::<()>::Err(anyhow::anyhow!("Migration never run"));
93
94 for _ in 0..MIGRATION_RETRIES {
95 migration_result = connection
96 .with_savepoint("thread_safe_multi_migration", || M::migrate(connection));
97
98 if migration_result.is_ok() {
99 break;
100 }
101 }
102
103 migration_result
104 })
105 .await?;
106
107 Ok(self.connection)
108 }
109}
110
111impl<M: Migrator> ThreadSafeConnection<M> {
112 fn initialize_queues(&self, write_queue_constructor: Option<WriteQueueConstructor>) -> bool {
113 if !QUEUES.read().contains_key(&self.uri) {
114 let mut queues = QUEUES.write();
115 if !queues.contains_key(&self.uri) {
116 let mut write_queue_constructor =
117 write_queue_constructor.unwrap_or(background_thread_queue());
118 queues.insert(self.uri.clone(), write_queue_constructor());
119 return true;
120 }
121 }
122 return false;
123 }
124
125 pub fn builder(uri: &str, persistent: bool) -> ThreadSafeConnectionBuilder<M> {
126 ThreadSafeConnectionBuilder::<M> {
127 db_initialize_query: None,
128 write_queue_constructor: None,
129 connection: Self {
130 uri: Arc::from(uri),
131 persistent,
132 connection_initialize_query: None,
133 connections: Default::default(),
134 _migrator: PhantomData,
135 },
136 }
137 }
138
139 /// Opens a new db connection with the initialized file path. This is internal and only
140 /// called from the deref function.
141 fn open_file(uri: &str) -> Connection {
142 Connection::open_file(uri)
143 }
144
145 /// Opens a shared memory connection using the file path as the identifier. This is internal
146 /// and only called from the deref function.
147 fn open_shared_memory(uri: &str) -> Connection {
148 Connection::open_memory(Some(uri))
149 }
150
151 pub fn write<T: 'static + Send + Sync>(
152 &self,
153 callback: impl 'static + Send + FnOnce(&Connection) -> T,
154 ) -> impl Future<Output = T> {
155 // Check and invalidate queue and maybe recreate queue
156 let queues = QUEUES.read();
157 let write_channel = queues
158 .get(&self.uri)
159 .expect("Queues are inserted when build is called. This should always succeed");
160
161 // Create a one shot channel for the result of the queued write
162 // so we can await on the result
163 let (sender, reciever) = oneshot::channel();
164
165 let thread_safe_connection = (*self).clone();
166 write_channel(Box::new(move || {
167 let connection = thread_safe_connection.deref();
168 let result = connection.with_write(|connection| callback(connection));
169 sender.send(result).ok();
170 }));
171 reciever.map(|response| response.expect("Write queue unexpectedly closed"))
172 }
173
174 pub(crate) fn create_connection(
175 persistent: bool,
176 uri: &str,
177 connection_initialize_query: Option<&'static str>,
178 ) -> Connection {
179 let mut connection = if persistent {
180 Self::open_file(uri)
181 } else {
182 Self::open_shared_memory(uri)
183 };
184
185 // Disallow writes on the connection. The only writes allowed for thread safe connections
186 // are from the background thread that can serialize them.
187 *connection.write.get_mut() = false;
188
189 if let Some(initialize_query) = connection_initialize_query {
190 connection.exec(initialize_query).expect(&format!(
191 "Initialize query failed to execute: {}",
192 initialize_query
193 ))()
194 .unwrap()
195 }
196
197 connection
198 }
199}
200
201impl ThreadSafeConnection<()> {
202 /// Special constructor for ThreadSafeConnection which disallows db initialization and migrations.
203 /// This allows construction to be infallible and not write to the db.
204 pub fn new(
205 uri: &str,
206 persistent: bool,
207 connection_initialize_query: Option<&'static str>,
208 write_queue_constructor: Option<WriteQueueConstructor>,
209 ) -> Self {
210 let connection = Self {
211 uri: Arc::from(uri),
212 persistent,
213 connection_initialize_query,
214 connections: Default::default(),
215 _migrator: PhantomData,
216 };
217
218 connection.initialize_queues(write_queue_constructor);
219 connection
220 }
221}
222
223impl<M: Migrator> Clone for ThreadSafeConnection<M> {
224 fn clone(&self) -> Self {
225 Self {
226 uri: self.uri.clone(),
227 persistent: self.persistent,
228 connection_initialize_query: self.connection_initialize_query.clone(),
229 connections: self.connections.clone(),
230 _migrator: PhantomData,
231 }
232 }
233}
234
235impl<M: Migrator> Deref for ThreadSafeConnection<M> {
236 type Target = Connection;
237
238 fn deref(&self) -> &Self::Target {
239 self.connections.get_or(|| {
240 Self::create_connection(self.persistent, &self.uri, self.connection_initialize_query)
241 })
242 }
243}
244
245pub fn background_thread_queue() -> WriteQueueConstructor {
246 use std::sync::mpsc::channel;
247
248 Box::new(|| {
249 let (sender, reciever) = channel::<QueuedWrite>();
250
251 thread::spawn(move || {
252 while let Ok(write) = reciever.recv() {
253 write()
254 }
255 });
256
257 let sender = UnboundedSyncSender::new(sender);
258 Box::new(move |queued_write| {
259 sender
260 .send(queued_write)
261 .expect("Could not send write action to background thread");
262 })
263 })
264}
265
266pub fn locking_queue() -> WriteQueueConstructor {
267 Box::new(|| {
268 let write_mutex = Mutex::new(());
269 Box::new(move |queued_write| {
270 let _lock = write_mutex.lock();
271 queued_write();
272 })
273 })
274}
275
276#[cfg(test)]
277mod test {
278 use indoc::indoc;
279 use lazy_static::__Deref;
280
281 use std::thread;
282
283 use crate::{domain::Domain, thread_safe_connection::ThreadSafeConnection};
284
285 #[test]
286 fn many_initialize_and_migrate_queries_at_once() {
287 let mut handles = vec![];
288
289 enum TestDomain {}
290 impl Domain for TestDomain {
291 fn name() -> &'static str {
292 "test"
293 }
294 fn migrations() -> &'static [&'static str] {
295 &["CREATE TABLE test(col1 TEXT, col2 TEXT) STRICT;"]
296 }
297 }
298
299 for _ in 0..100 {
300 handles.push(thread::spawn(|| {
301 let builder =
302 ThreadSafeConnection::<TestDomain>::builder("annoying-test.db", false)
303 .with_db_initialization_query("PRAGMA journal_mode=WAL")
304 .with_connection_initialize_query(indoc! {"
305 PRAGMA synchronous=NORMAL;
306 PRAGMA busy_timeout=1;
307 PRAGMA foreign_keys=TRUE;
308 PRAGMA case_sensitive_like=TRUE;
309 "});
310
311 let _ = smol::block_on(builder.build()).unwrap().deref();
312 }));
313 }
314
315 for handle in handles {
316 let _ = handle.join();
317 }
318 }
319
320 #[test]
321 #[should_panic]
322 fn wild_zed_lost_failure() {
323 enum TestWorkspace {}
324 impl Domain for TestWorkspace {
325 fn name() -> &'static str {
326 "workspace"
327 }
328
329 fn migrations() -> &'static [&'static str] {
330 &["
331 CREATE TABLE workspaces(
332 workspace_id INTEGER PRIMARY KEY,
333 dock_visible INTEGER, -- Boolean
334 dock_anchor TEXT, -- Enum: 'Bottom' / 'Right' / 'Expanded'
335 dock_pane INTEGER, -- NULL indicates that we don't have a dock pane yet
336 timestamp TEXT DEFAULT CURRENT_TIMESTAMP NOT NULL,
337 FOREIGN KEY(dock_pane) REFERENCES panes(pane_id),
338 FOREIGN KEY(active_pane) REFERENCES panes(pane_id)
339 ) STRICT;
340
341 CREATE TABLE panes(
342 pane_id INTEGER PRIMARY KEY,
343 workspace_id INTEGER NOT NULL,
344 active INTEGER NOT NULL, -- Boolean
345 FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
346 ON DELETE CASCADE
347 ON UPDATE CASCADE
348 ) STRICT;
349 "]
350 }
351 }
352
353 let builder =
354 ThreadSafeConnection::<TestWorkspace>::builder("wild_zed_lost_failure", false)
355 .with_connection_initialize_query("PRAGMA FOREIGN_KEYS=true");
356
357 smol::block_on(builder.build()).unwrap();
358 }
359}