use std::collections::HashMap;
use parking_lot::RwLock;
pub struct ClientRegistry {
clients: RwLock<HashMap<String, ClientInfo>>,
}
#[derive(Debug, Clone)]
pub struct ClientInfo {
pub client_id: String,
pub connected_at: i64,
pub last_heartbeat: i64,
}
impl ClientRegistry {
pub fn new() -> Self {
Self {
clients: RwLock::new(HashMap::new()),
}
}
pub fn register(&self, client_id: &str) {
let mut clients = self.clients.write();
clients.insert(
client_id.to_string(),
ClientInfo {
client_id: client_id.to_string(),
connected_at: chrono::Utc::now().timestamp(),
last_heartbeat: chrono::Utc::now().timestamp(),
},
);
tracing::info!("Client registered: {}", client_id);
}
pub fn heartbeat(&self, client_id: &str) {
let mut clients = self.clients.write();
if let Some(info) = clients.get_mut(client_id) {
info.last_heartbeat = chrono::Utc::now().timestamp();
}
}
pub fn unregister(&self, client_id: &str) {
let mut clients = self.clients.write();
clients.remove(client_id);
tracing::info!("Client unregistered: {}", client_id);
}
pub fn is_registered(&self, client_id: &str) -> bool {
self.clients.read().contains_key(client_id)
}
pub fn get_all(&self) -> Vec<ClientInfo> {
self.clients.read().values().cloned().collect()
}
}
impl Default for ClientRegistry {
fn default() -> Self {
Self::new()
}
}