refactor: Replace remaining std Mutexes

This commit is contained in:
Jade Ellis 2025-07-19 22:05:43 +01:00
commit 374fb2745c
No known key found for this signature in database
GPG key ID: 8705A2A3EBF77BD2
11 changed files with 83 additions and 117 deletions

View file

@ -1,11 +1,8 @@
#![cfg(feature = "console")]
use std::{
collections::VecDeque,
sync::{Arc, Mutex},
};
use std::{collections::VecDeque, sync::Arc};
use conduwuit::{Server, debug, defer, error, log, log::is_systemd_mode};
use conduwuit::{Server, SyncMutex, debug, defer, error, log, log::is_systemd_mode};
use futures::future::{AbortHandle, Abortable};
use ruma::events::room::message::RoomMessageEventContent;
use rustyline_async::{Readline, ReadlineError, ReadlineEvent};
@ -17,10 +14,10 @@ use crate::{Dep, admin};
pub struct Console {
server: Arc<Server>,
admin: Dep<admin::Service>,
worker_join: Mutex<Option<JoinHandle<()>>>,
input_abort: Mutex<Option<AbortHandle>>,
command_abort: Mutex<Option<AbortHandle>>,
history: Mutex<VecDeque<String>>,
worker_join: SyncMutex<Option<JoinHandle<()>>>,
input_abort: SyncMutex<Option<AbortHandle>>,
command_abort: SyncMutex<Option<AbortHandle>>,
history: SyncMutex<VecDeque<String>>,
output: MadSkin,
}
@ -50,7 +47,7 @@ impl Console {
}
pub async fn start(self: &Arc<Self>) {
let mut worker_join = self.worker_join.lock().expect("locked");
let mut worker_join = self.worker_join.lock();
if worker_join.is_none() {
let self_ = Arc::clone(self);
_ = worker_join.insert(self.server.runtime().spawn(self_.worker()));
@ -60,7 +57,7 @@ impl Console {
pub async fn close(self: &Arc<Self>) {
self.interrupt();
let Some(worker_join) = self.worker_join.lock().expect("locked").take() else {
let Some(worker_join) = self.worker_join.lock().take() else {
return;
};
@ -70,22 +67,18 @@ impl Console {
pub fn interrupt(self: &Arc<Self>) {
self.interrupt_command();
self.interrupt_readline();
self.worker_join
.lock()
.expect("locked")
.as_ref()
.map(JoinHandle::abort);
self.worker_join.lock().as_ref().map(JoinHandle::abort);
}
pub fn interrupt_readline(self: &Arc<Self>) {
if let Some(input_abort) = self.input_abort.lock().expect("locked").take() {
if let Some(input_abort) = self.input_abort.lock().take() {
debug!("Interrupting console readline...");
input_abort.abort();
}
}
pub fn interrupt_command(self: &Arc<Self>) {
if let Some(command_abort) = self.command_abort.lock().expect("locked").take() {
if let Some(command_abort) = self.command_abort.lock().take() {
debug!("Interrupting console command...");
command_abort.abort();
}
@ -120,7 +113,7 @@ impl Console {
}
debug!("session ending");
self.worker_join.lock().expect("locked").take();
self.worker_join.lock().take();
}
async fn readline(self: &Arc<Self>) -> Result<ReadlineEvent, ReadlineError> {
@ -135,9 +128,9 @@ impl Console {
let (abort, abort_reg) = AbortHandle::new_pair();
let future = Abortable::new(future, abort_reg);
_ = self.input_abort.lock().expect("locked").insert(abort);
_ = self.input_abort.lock().insert(abort);
defer! {{
_ = self.input_abort.lock().expect("locked").take();
_ = self.input_abort.lock().take();
}}
let Ok(result) = future.await else {
@ -158,9 +151,9 @@ impl Console {
let (abort, abort_reg) = AbortHandle::new_pair();
let future = Abortable::new(future, abort_reg);
_ = self.command_abort.lock().expect("locked").insert(abort);
_ = self.command_abort.lock().insert(abort);
defer! {{
_ = self.command_abort.lock().expect("locked").take();
_ = self.command_abort.lock().take();
}}
_ = future.await;
@ -184,20 +177,15 @@ impl Console {
}
fn set_history(&self, readline: &mut Readline) {
self.history
.lock()
.expect("locked")
.iter()
.rev()
.for_each(|entry| {
readline
.add_history_entry(entry.clone())
.expect("added history entry");
});
self.history.lock().iter().rev().for_each(|entry| {
readline
.add_history_entry(entry.clone())
.expect("added history entry");
});
}
fn add_history(&self, line: String) {
let mut history = self.history.lock().expect("locked");
let mut history = self.history.lock();
history.push_front(line);
history.truncate(HISTORY_LIMIT);
}

View file

@ -1,9 +1,6 @@
use std::{
mem::size_of,
sync::{Arc, Mutex},
};
use std::{mem::size_of, sync::Arc};
use conduwuit::{Err, Result, err, utils, utils::math::usize_from_f64};
use conduwuit::{Err, Result, SyncMutex, err, utils, utils::math::usize_from_f64};
use database::Map;
use lru_cache::LruCache;
@ -11,7 +8,7 @@ use crate::rooms::short::ShortEventId;
pub(super) struct Data {
shorteventid_authchain: Arc<Map>,
pub(super) auth_chain_cache: Mutex<LruCache<Vec<u64>, Arc<[ShortEventId]>>>,
pub(super) auth_chain_cache: SyncMutex<LruCache<Vec<u64>, Arc<[ShortEventId]>>>,
}
impl Data {
@ -23,7 +20,7 @@ impl Data {
.expect("valid cache size");
Self {
shorteventid_authchain: db["shorteventid_authchain"].clone(),
auth_chain_cache: Mutex::new(LruCache::new(cache_size)),
auth_chain_cache: SyncMutex::new(LruCache::new(cache_size)),
}
}
@ -34,12 +31,7 @@ impl Data {
debug_assert!(!key.is_empty(), "auth_chain key must not be empty");
// Check RAM cache
if let Some(result) = self
.auth_chain_cache
.lock()
.expect("cache locked")
.get_mut(key)
{
if let Some(result) = self.auth_chain_cache.lock().get_mut(key) {
return Ok(Arc::clone(result));
}
@ -63,7 +55,6 @@ impl Data {
// Cache in RAM
self.auth_chain_cache
.lock()
.expect("cache locked")
.insert(vec![key[0]], Arc::clone(&chain));
Ok(chain)
@ -84,9 +75,6 @@ impl Data {
}
// Cache in RAM
self.auth_chain_cache
.lock()
.expect("cache locked")
.insert(key, auth_chain);
self.auth_chain_cache.lock().insert(key, auth_chain);
}
}

View file

@ -248,10 +248,10 @@ pub fn cache_auth_chain_vec(&self, key: Vec<u64>, auth_chain: &[ShortEventId]) {
#[implement(Service)]
pub fn get_cache_usage(&self) -> (usize, usize) {
let cache = self.db.auth_chain_cache.lock().expect("locked");
let cache = self.db.auth_chain_cache.lock();
(cache.len(), cache.capacity())
}
#[implement(Service)]
pub fn clear_cache(&self) { self.db.auth_chain_cache.lock().expect("locked").clear(); }
pub fn clear_cache(&self) { self.db.auth_chain_cache.lock().clear(); }

View file

@ -2,12 +2,12 @@ use std::{
collections::{BTreeSet, HashMap},
fmt::{Debug, Write},
mem::size_of,
sync::{Arc, Mutex},
sync::Arc,
};
use async_trait::async_trait;
use conduwuit::{
Result,
Result, SyncMutex,
arrayvec::ArrayVec,
at, checked, err, expected, implement, utils,
utils::{bytes, math::usize_from_f64, stream::IterStream},
@ -23,7 +23,7 @@ use crate::{
};
pub struct Service {
pub stateinfo_cache: Mutex<StateInfoLruCache>,
pub stateinfo_cache: SyncMutex<StateInfoLruCache>,
db: Data,
services: Services,
}
@ -86,7 +86,7 @@ impl crate::Service for Service {
async fn memory_usage(&self, out: &mut (dyn Write + Send)) -> Result {
let (cache_len, ents) = {
let cache = self.stateinfo_cache.lock().expect("locked");
let cache = self.stateinfo_cache.lock();
let ents = cache.iter().map(at!(1)).flat_map(|vec| vec.iter()).fold(
HashMap::new(),
|mut ents, ssi| {
@ -110,7 +110,7 @@ impl crate::Service for Service {
Ok(())
}
async fn clear_cache(&self) { self.stateinfo_cache.lock().expect("locked").clear(); }
async fn clear_cache(&self) { self.stateinfo_cache.lock().clear(); }
fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
}
@ -123,7 +123,7 @@ pub async fn load_shortstatehash_info(
&self,
shortstatehash: ShortStateHash,
) -> Result<ShortStateInfoVec> {
if let Some(r) = self.stateinfo_cache.lock()?.get_mut(&shortstatehash) {
if let Some(r) = self.stateinfo_cache.lock().get_mut(&shortstatehash) {
return Ok(r.clone());
}
@ -152,7 +152,7 @@ async fn cache_shortstatehash_info(
shortstatehash: ShortStateHash,
stack: ShortStateInfoVec,
) -> Result {
self.stateinfo_cache.lock()?.insert(shortstatehash, stack);
self.stateinfo_cache.lock().insert(shortstatehash, stack);
Ok(())
}

View file

@ -2,10 +2,10 @@ mod watch;
use std::{
collections::{BTreeMap, BTreeSet},
sync::{Arc, Mutex, Mutex as StdMutex},
sync::Arc,
};
use conduwuit::{Result, Server};
use conduwuit::{Result, Server, SyncMutex};
use database::Map;
use ruma::{
OwnedDeviceId, OwnedRoomId, OwnedUserId,
@ -62,11 +62,11 @@ struct SnakeSyncCache {
extensions: v5::request::Extensions,
}
type DbConnections<K, V> = Mutex<BTreeMap<K, V>>;
type DbConnections<K, V> = SyncMutex<BTreeMap<K, V>>;
type DbConnectionsKey = (OwnedUserId, OwnedDeviceId, String);
type DbConnectionsVal = Arc<Mutex<SlidingSyncCache>>;
type DbConnectionsVal = Arc<SyncMutex<SlidingSyncCache>>;
type SnakeConnectionsKey = (OwnedUserId, OwnedDeviceId, Option<String>);
type SnakeConnectionsVal = Arc<Mutex<SnakeSyncCache>>;
type SnakeConnectionsVal = Arc<SyncMutex<SnakeSyncCache>>;
impl crate::Service for Service {
fn build(args: crate::Args<'_>) -> Result<Arc<Self>> {
@ -90,8 +90,8 @@ impl crate::Service for Service {
state_cache: args.depend::<rooms::state_cache::Service>("rooms::state_cache"),
typing: args.depend::<rooms::typing::Service>("rooms::typing"),
},
connections: StdMutex::new(BTreeMap::new()),
snake_connections: StdMutex::new(BTreeMap::new()),
connections: SyncMutex::new(BTreeMap::new()),
snake_connections: SyncMutex::new(BTreeMap::new()),
}))
}
@ -100,22 +100,19 @@ impl crate::Service for Service {
impl Service {
pub fn snake_connection_cached(&self, key: &SnakeConnectionsKey) -> bool {
self.snake_connections
.lock()
.expect("locked")
.contains_key(key)
self.snake_connections.lock().contains_key(key)
}
pub fn forget_snake_sync_connection(&self, key: &SnakeConnectionsKey) {
self.snake_connections.lock().expect("locked").remove(key);
self.snake_connections.lock().remove(key);
}
pub fn remembered(&self, key: &DbConnectionsKey) -> bool {
self.connections.lock().expect("locked").contains_key(key)
self.connections.lock().contains_key(key)
}
pub fn forget_sync_request_connection(&self, key: &DbConnectionsKey) {
self.connections.lock().expect("locked").remove(key);
self.connections.lock().remove(key);
}
pub fn update_snake_sync_request_with_cache(
@ -123,13 +120,13 @@ impl Service {
snake_key: &SnakeConnectionsKey,
request: &mut v5::Request,
) -> BTreeMap<String, BTreeMap<OwnedRoomId, u64>> {
let mut cache = self.snake_connections.lock().expect("locked");
let mut cache = self.snake_connections.lock();
let cached = Arc::clone(
cache
.entry(snake_key.clone())
.or_insert_with(|| Arc::new(Mutex::new(SnakeSyncCache::default()))),
.or_insert_with(|| Arc::new(SyncMutex::new(SnakeSyncCache::default()))),
);
let cached = &mut cached.lock().expect("locked");
let cached = &mut cached.lock();
drop(cache);
//v5::Request::try_from_http_request(req, path_args);
@ -232,16 +229,16 @@ impl Service {
};
let key = into_db_key(key.0.clone(), key.1.clone(), conn_id);
let mut cache = self.connections.lock().expect("locked");
let mut cache = self.connections.lock();
let cached = Arc::clone(cache.entry(key).or_insert_with(|| {
Arc::new(Mutex::new(SlidingSyncCache {
Arc::new(SyncMutex::new(SlidingSyncCache {
lists: BTreeMap::new(),
subscriptions: BTreeMap::new(),
known_rooms: BTreeMap::new(),
extensions: ExtensionsConfig::default(),
}))
}));
let cached = &mut cached.lock().expect("locked");
let cached = &mut cached.lock();
drop(cache);
for (list_id, list) in &mut request.lists {
@ -328,16 +325,16 @@ impl Service {
key: &DbConnectionsKey,
subscriptions: BTreeMap<OwnedRoomId, sync_events::v4::RoomSubscription>,
) {
let mut cache = self.connections.lock().expect("locked");
let mut cache = self.connections.lock();
let cached = Arc::clone(cache.entry(key.clone()).or_insert_with(|| {
Arc::new(Mutex::new(SlidingSyncCache {
Arc::new(SyncMutex::new(SlidingSyncCache {
lists: BTreeMap::new(),
subscriptions: BTreeMap::new(),
known_rooms: BTreeMap::new(),
extensions: ExtensionsConfig::default(),
}))
}));
let cached = &mut cached.lock().expect("locked");
let cached = &mut cached.lock();
drop(cache);
cached.subscriptions = subscriptions;
@ -350,16 +347,16 @@ impl Service {
new_cached_rooms: BTreeSet<OwnedRoomId>,
globalsince: u64,
) {
let mut cache = self.connections.lock().expect("locked");
let mut cache = self.connections.lock();
let cached = Arc::clone(cache.entry(key.clone()).or_insert_with(|| {
Arc::new(Mutex::new(SlidingSyncCache {
Arc::new(SyncMutex::new(SlidingSyncCache {
lists: BTreeMap::new(),
subscriptions: BTreeMap::new(),
known_rooms: BTreeMap::new(),
extensions: ExtensionsConfig::default(),
}))
}));
let cached = &mut cached.lock().expect("locked");
let cached = &mut cached.lock();
drop(cache);
for (room_id, lastsince) in cached
@ -386,13 +383,13 @@ impl Service {
globalsince: u64,
) {
assert!(key.2.is_some(), "Some(conn_id) required for this call");
let mut cache = self.snake_connections.lock().expect("locked");
let mut cache = self.snake_connections.lock();
let cached = Arc::clone(
cache
.entry(key.clone())
.or_insert_with(|| Arc::new(Mutex::new(SnakeSyncCache::default()))),
.or_insert_with(|| Arc::new(SyncMutex::new(SnakeSyncCache::default()))),
);
let cached = &mut cached.lock().expect("locked");
let cached = &mut cached.lock();
drop(cache);
for (room_id, lastsince) in cached
@ -416,13 +413,13 @@ impl Service {
key: &SnakeConnectionsKey,
subscriptions: BTreeMap<OwnedRoomId, v5::request::RoomSubscription>,
) {
let mut cache = self.snake_connections.lock().expect("locked");
let mut cache = self.snake_connections.lock();
let cached = Arc::clone(
cache
.entry(key.clone())
.or_insert_with(|| Arc::new(Mutex::new(SnakeSyncCache::default()))),
.or_insert_with(|| Arc::new(SyncMutex::new(SnakeSyncCache::default()))),
);
let cached = &mut cached.lock().expect("locked");
let cached = &mut cached.lock();
drop(cache);
cached.subscriptions = subscriptions;