let user handler own user lookup map

This commit is contained in:
Adam 2024-11-19 21:38:35 -05:00
parent 7e18d5e1c1
commit 3900ec55d4
3 changed files with 10 additions and 12 deletions

View file

@ -74,7 +74,6 @@ pub struct AppState {
pub tx_game_handler: mpsc::Sender<GameHandlerMessage>,
pub tx_incoming_message_handler: mpsc::Sender<(SocketAddr, Message)>,
pub tx_user_handler: mpsc::Sender<UserHandlerMessage>,
pub users_by_id: RwLock<HashMap<String, Arc<RwLock<User>>>>,
pub white_cards_by_id: HashMap<String, Arc<CardWhiteWithID>>,
}

View file

@ -79,7 +79,6 @@ async fn main() -> Result<()> {
let offline_users = RwLock::new(HashMap::<String, Arc<RwLock<User>>>::new());
let online_users = RwLock::new(HashMap::<SocketAddr, Arc<RwLock<User>>>::new());
let reserved_names = RwLock::new(HashSet::<String>::new());
let users_by_id = RwLock::new(HashMap::<String, Arc<RwLock<User>>>::new());
let app_state = Arc::new(AppState {
first_names,
@ -94,7 +93,6 @@ async fn main() -> Result<()> {
tx_game_handler,
tx_incoming_message_handler,
tx_user_handler,
users_by_id,
white_cards_by_id,
});
@ -113,7 +111,7 @@ async fn main() -> Result<()> {
// TODO: Make an outgoing message handler?
// Spawn task to handle User things
let user_handler = UserHandler::new(app_state.clone());
let mut user_handler = UserHandler::new(app_state.clone());
tokio::task::Builder::new()
.name("User Handler")
.spawn(async move {

View file

@ -14,6 +14,7 @@ use std::sync::{Arc, RwLock};
pub struct UserHandler {
/// Pointer to global state
state: Arc<AppState>,
users_by_id: HashMap<String, Arc<RwLock<User>>>,
}
pub enum DmUserMethod {
@ -40,11 +41,14 @@ pub enum SendUserMessage {
impl UserHandler {
/// Returns new UserHandler
pub fn new(state: Arc<AppState>) -> Self {
UserHandler { state }
UserHandler {
state,
users_by_id: HashMap::<String, Arc<RwLock<User>>>::new(),
}
}
/// Handles incoming messages
pub async fn handle(&self, message: UserHandlerMessage) {
pub async fn handle(&mut self, message: UserHandlerMessage) {
match message {
NewUser(user, addr) => {
// TODO: make this not async
@ -63,7 +67,7 @@ impl UserHandler {
// Determine lookup method
match method {
Id(id) => {
if let Some(user) = self.state.users_by_id.read().unwrap().get(&id) {
if let Some(user) = self.users_by_id.get(&id) {
tx = user.read().unwrap().tx.clone();
} else {
tracing::error!("Attempted to send message to invalid user id!");
@ -113,7 +117,7 @@ impl UserHandler {
}
/// Create, register, and hydrate new user
async fn set_up_new_user(&self, user: User, addr: SocketAddr) {
async fn set_up_new_user(&mut self, user: User, addr: SocketAddr) {
let user_tx = user.tx.clone();
let new_user = Arc::new(RwLock::new(user));
@ -123,10 +127,7 @@ impl UserHandler {
tokio::spawn(async move { tx.send(msg).await });
// Register uuid
self.state
.users_by_id
.write()
.unwrap()
self.users_by_id
.insert(new_user.read().unwrap().uuid.clone(), new_user.clone());
// Register online using `addr` as key until something longer lived exists