use rwlock for command handler.

Signed-off-by: Jason Volk <jason@zemos.net>
This commit is contained in:
Jason Volk 2024-07-05 08:39:37 +00:00
parent 5254eb4f72
commit a3638dbb15
2 changed files with 14 additions and 6 deletions

View file

@ -36,13 +36,18 @@ pub async fn init() {
.write() .write()
.expect("locked for writing") .expect("locked for writing")
.insert(handler::complete); .insert(handler::complete);
_ = services().admin.handle.lock().await.insert(handler::handle); _ = services()
.admin
.handle
.write()
.await
.insert(handler::handle);
} }
/// Uninstall the admin command handler /// Uninstall the admin command handler
#[allow(clippy::let_underscore_must_use)] #[allow(clippy::let_underscore_must_use)]
pub async fn fini() { pub async fn fini() {
_ = services().admin.handle.lock().await.take(); _ = services().admin.handle.write().await.take();
_ = services() _ = services()
.admin .admin
.complete .complete

View file

@ -21,7 +21,10 @@ use ruma::{
OwnedEventId, OwnedRoomId, RoomId, UserId, OwnedEventId, OwnedRoomId, RoomId, UserId,
}; };
use serde_json::value::to_raw_value; use serde_json::value::to_raw_value;
use tokio::{sync::Mutex, task::JoinHandle}; use tokio::{
sync::{Mutex, RwLock},
task::JoinHandle,
};
use crate::{pdu::PduBuilder, services, user_is_local, PduEvent}; use crate::{pdu::PduBuilder, services, user_is_local, PduEvent};
@ -37,7 +40,7 @@ pub struct Service {
sender: Sender<Command>, sender: Sender<Command>,
receiver: Mutex<Receiver<Command>>, receiver: Mutex<Receiver<Command>>,
handler_join: Mutex<Option<JoinHandle<()>>>, handler_join: Mutex<Option<JoinHandle<()>>>,
pub handle: Mutex<Option<Handler>>, pub handle: RwLock<Option<Handler>>,
pub complete: StdRwLock<Option<Completer>>, pub complete: StdRwLock<Option<Completer>>,
#[cfg(feature = "console")] #[cfg(feature = "console")]
pub console: Arc<console::Console>, pub console: Arc<console::Console>,
@ -57,7 +60,7 @@ impl crate::Service for Service {
sender, sender,
receiver: Mutex::new(receiver), receiver: Mutex::new(receiver),
handler_join: Mutex::new(None), handler_join: Mutex::new(None),
handle: Mutex::new(None), handle: RwLock::new(None),
complete: StdRwLock::new(None), complete: StdRwLock::new(None),
#[cfg(feature = "console")] #[cfg(feature = "console")]
console: console::Console::new(), console: console::Console::new(),
@ -175,7 +178,7 @@ impl Service {
} }
async fn process_command(&self, command: Command) -> CommandResult { async fn process_command(&self, command: Command) -> CommandResult {
if let Some(handle) = self.handle.lock().await.as_ref() { if let Some(handle) = self.handle.read().await.as_ref() {
handle(command).await handle(command).await
} else { } else {
Err(Error::Err("Admin module is not loaded.".into())) Err(Error::Err("Admin module is not loaded.".into()))