use std::{ collections::{HashMap, HashSet}, sync::{ Arc, Mutex, atomic::{AtomicBool, AtomicU64, Ordering}, }, }; use bytes::Bytes; use common::{model::Id, transport::Close, update::Install}; use quinn::Connection; use tokio::sync::mpsc::{self, error::TrySendError}; use tracing::warn; pub type ConnId = u64; const QUEUE_LENGTH: usize = 256; static NEXT_ID: AtomicU64 = AtomicU64::new(1); pub struct Signed { pub user_id: Id, pub session_id: Id, } pub struct Client { pub id: ConnId, pub conn: Option, pub me: Option, pub install: Install, tx: mpsc::Sender, pub closed: AtomicBool, watching: Mutex>, ghost_logged: Mutex>, } impl Client { pub fn new( conn: Option, me: Option, install: Install, ) -> (Arc, mpsc::Receiver) { let (tx, rx) = mpsc::channel(QUEUE_LENGTH); let client = Arc::new(Self { id: NEXT_ID.fetch_add(1, Ordering::Relaxed), conn, me, install, tx, closed: AtomicBool::new(false), watching: Mutex::new(None), ghost_logged: Mutex::new(HashSet::new()), }); (client, rx) } #[cfg(test)] pub fn detached(me: Option) -> Arc { Self::new(None, me, Install::default()).0 } pub fn user_id(&self) -> Option { self.me.as_ref().map(|me| me.user_id) } pub fn close(&self, close: Close) { if let Some(conn) = &self.conn { close.on(conn); } } pub fn first_visit(&self, community_id: Id) -> bool { self.ghost_logged.lock().unwrap().insert(community_id) } pub fn watch(&self, community_id: Option) { *self.watching.lock().unwrap() = community_id; } } #[derive(Clone, Default)] pub struct Hub(Arc>>>); impl Hub { pub fn add(&self, client: Arc) -> Option { let mut clients = self.0.lock().unwrap(); let user_id = client.user_id(); let was_online = user_id.is_some_and(|user_id| Self::online_in(&clients, user_id)); clients.insert(client.id, client); user_id.filter(|_| !was_online) } pub fn remove(&self, id: ConnId) -> Option { let mut clients = self.0.lock().unwrap(); let user_id = clients.remove(&id)?.user_id()?; (!Self::online_in(&clients, user_id)).then_some(user_id) } fn online_in(clients: &HashMap>, user_id: Id) -> bool { clients .values() .any(|client| client.user_id() == Some(user_id)) } pub fn is_online(&self, user_id: Id) -> bool { Self::online_in(&self.0.lock().unwrap(), user_id) } pub fn online(&self) -> usize { let clients = self.0.lock().unwrap(); let ids: HashSet = clients .values() .filter_map(|client| client.user_id()) .collect(); ids.len() } pub fn conns_of(&self, user_ids: &[Id]) -> Vec { self.0 .lock() .unwrap() .values() .filter(|client| client.user_id().is_some_and(|id| user_ids.contains(&id))) .map(|client| client.id) .collect() } pub fn watchers(&self, community_id: Id) -> Vec { self.0 .lock() .unwrap() .values() .filter(|client| *client.watching.lock().unwrap() == Some(community_id)) .map(|client| client.id) .collect() } pub fn bytes(&self) -> (u64, u64) { let clients = self.0.lock().unwrap(); let mut total = (0, 0); for conn in clients.values().filter_map(|client| client.conn.as_ref()) { let stats = conn.stats(); total.0 += stats.udp_tx.bytes; total.1 += stats.udp_rx.bytes; } total } pub fn installs(&self) -> Vec { self.0 .lock() .unwrap() .values() .map(|client| client.install) .collect() } pub fn all(&self) -> Vec { self.0.lock().unwrap().keys().copied().collect() } pub fn send(&self, ids: &[ConnId], bytes: &Bytes, droppable: bool) { let clients = self.0.lock().unwrap(); for id in ids { let Some(client) = clients.get(id) else { continue; }; match client.tx.try_send(bytes.clone()) { Ok(()) | Err(TrySendError::Closed(_)) => {} Err(TrySendError::Full(_)) if droppable => {} Err(TrySendError::Full(_)) => { warn!("client {} too slow", client.id); client.close(Close::Slow); } } } } fn kick_where(&self, matches: impl Fn(&Signed) -> bool, close: Close) { let targets: Vec> = self .0 .lock() .unwrap() .values() .filter(|client| client.me.as_ref().is_some_and(&matches)) .cloned() .collect(); for client in targets { client.close(close); } } pub fn kick_user(&self, user_id: Id, close: Close) { self.kick_where(|me| me.user_id == user_id, close); } pub fn kick_session(&self, session_id: Id, close: Close) { self.kick_where(|me| me.session_id == session_id, close); } pub fn kick_all_except(&self, keep: &[Id], close: Close) { self.kick_where(|me| !keep.contains(&me.user_id), close); } }