Skip to content

Commit

Permalink
Switch from RefCell to Mutex
Browse files Browse the repository at this point in the history
  • Loading branch information
richardhuaaa committed Dec 5, 2023
1 parent bfae528 commit 600ea7e
Showing 1 changed file with 16 additions and 5 deletions.
21 changes: 16 additions & 5 deletions xmtp_mls/src/storage/encrypted_store/db_connection.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::storage::RawDbConnection;
use std::{cell::RefCell, fmt};
use std::{cell::RefCell, fmt, sync::Mutex};

// Re-implementation of Cow without ToOwned requirement
enum RefOrValue<'a, T> {
Expand All @@ -12,26 +12,37 @@ enum RefOrValue<'a, T> {
/// and transaction state can be shared between the OpenMLS Provider and
/// native XMTP operations
pub struct DbConnection<'a> {
wrapped_conn: RefCell<RefOrValue<'a, RawDbConnection>>,
wrapped_conn: Mutex<RefOrValue<'a, RawDbConnection>>,
}

impl<'a> DbConnection<'a> {
pub(crate) fn new(conn: &'a mut RawDbConnection) -> Self {
Self {
wrapped_conn: RefCell::new(RefOrValue::Ref(conn)),
wrapped_conn: Mutex::new(RefOrValue::Ref(conn)),
}
}
pub(crate) fn held(conn: RawDbConnection) -> Self {
Self {
wrapped_conn: RefCell::new(RefOrValue::Value(conn)),
wrapped_conn: Mutex::new(RefOrValue::Value(conn)),
}
}

// Note: F is a synchronous fn. If it ever becomes async, we need to use
// tokio::sync::mutex instead of std::sync::Mutex
pub(crate) fn raw_query<T, F>(&self, fun: F) -> Result<T, diesel::result::Error>
where
F: FnOnce(&mut RawDbConnection) -> Result<T, diesel::result::Error>,
{
match *self.wrapped_conn.borrow_mut() {
let mut lock = self.wrapped_conn.lock().map_or_else(
|err| {
log::error!(
"Recovering from poisoned mutex - a thread has previously panicked holding this lock"
);
err.into_inner()
},
|guard| guard,
);
match *lock {
RefOrValue::Ref(ref mut conn_ref) => fun(conn_ref),
RefOrValue::Value(ref mut conn) => fun(conn),
}
Expand Down

0 comments on commit 600ea7e

Please sign in to comment.