kubi/kubi-udp/src/server.rs

267 lines
8.9 KiB
Rust
Raw Normal View History

2023-02-07 18:55:50 -06:00
use std::{
net::{UdpSocket, SocketAddr},
2023-02-12 18:53:55 -06:00
time::{Instant, Duration},
2023-02-07 18:55:50 -06:00
marker::PhantomData,
2023-02-11 19:56:50 -06:00
collections::{VecDeque, vec_deque::Drain as DrainDeque},
io::ErrorKind
2023-02-07 18:55:50 -06:00
};
use anyhow::{Result, Error, bail};
2023-02-05 19:15:19 -06:00
use hashbrown::HashMap;
use nohash_hasher::BuildNoHashHasher;
2023-02-07 18:55:50 -06:00
use crate::{
BINCODE_CONFIG,
2023-02-12 18:53:55 -06:00
common::{ClientId, ClientIdRepr, MAX_CLIENTS, PROTOCOL_ID, DEFAULT_USER_PROTOCOL_ID},
packet::{IdClientPacket, ClientPacket, ServerPacket, IdServerPacket, Message}
2023-02-07 18:55:50 -06:00
};
//i was feeling a bit sick while writing most of this please excuse me for my terrible code :3
2023-02-05 19:15:19 -06:00
pub struct ConnectedClient {
id: ClientId,
addr: SocketAddr,
timeout: Instant,
}
2023-01-31 20:16:23 -06:00
2023-02-05 20:48:43 -06:00
#[derive(Clone, Copy, Debug)]
pub struct ServerConfig {
pub max_clients: usize,
2023-02-12 18:53:55 -06:00
pub client_timeout: Duration,
pub protocol_id: u16,
2023-02-05 20:48:43 -06:00
}
impl Default for ServerConfig {
fn default() -> Self {
Self {
max_clients: MAX_CLIENTS,
2023-02-12 18:53:55 -06:00
client_timeout: Duration::from_secs(5),
protocol_id: DEFAULT_USER_PROTOCOL_ID,
2023-02-05 20:48:43 -06:00
}
}
}
2023-02-12 18:53:55 -06:00
pub enum ServerEvent<T> where T: Message {
2023-02-07 18:55:50 -06:00
Connected(ClientId),
Disconnected(ClientId),
MessageReceived {
from: ClientId,
message: T
}
}
2023-02-12 18:53:55 -06:00
pub struct Server<S, R> where S: Message, R: Message {
2023-01-31 20:16:23 -06:00
socket: UdpSocket,
clients: HashMap<ClientId, ConnectedClient, BuildNoHashHasher<ClientIdRepr>>,
2023-02-05 20:48:43 -06:00
config: ServerConfig,
2023-02-07 18:55:50 -06:00
event_queue: VecDeque<ServerEvent<R>>,
2023-02-10 13:36:58 -06:00
_s: PhantomData<S>,
2023-01-31 20:16:23 -06:00
}
2023-02-12 18:53:55 -06:00
impl<S, R> Server<S, R> where S: Message, R: Message {
2023-02-12 13:37:06 -06:00
pub fn bind(addr: SocketAddr, config: ServerConfig) -> anyhow::Result<Self> {
2023-02-12 18:53:55 -06:00
assert!(config.max_clients <= MAX_CLIENTS, "max_clients value exceeds the maximum allowed amount of clients");
if config.protocol_id == 0 {
log::warn!("Warning: using 0 as protocol_id is not recommended");
}
if config.protocol_id == DEFAULT_USER_PROTOCOL_ID {
log::warn!("Warning: using default protocol_id is not recommended");
}
2023-02-12 13:37:06 -06:00
let socket = UdpSocket::bind(addr)?;
socket.set_nonblocking(true)?;
Ok(Self {
config,
socket,
clients: HashMap::with_capacity_and_hasher(MAX_CLIENTS, BuildNoHashHasher::default()),
event_queue: VecDeque::new(),
_s: PhantomData,
})
}
2023-02-12 19:30:33 -06:00
fn send_to_addr_inner(socket: &UdpSocket, addr: SocketAddr, packet: IdServerPacket<S>) -> Result<()> {
2023-02-07 18:55:50 -06:00
let bytes = bincode::encode_to_vec(packet, BINCODE_CONFIG)?;
2023-02-12 19:30:33 -06:00
socket.send_to(&bytes, addr)?;
2023-02-07 18:55:50 -06:00
Ok(())
}
2023-02-12 13:37:06 -06:00
2023-02-12 19:30:33 -06:00
fn send_to_addr(&self, addr: SocketAddr, packet: IdServerPacket<S>) -> Result<()> {
Self::send_to_addr_inner(&self.socket, addr, packet)
}
2023-02-07 18:55:50 -06:00
fn send_packet(&self, packet: IdServerPacket<S>) -> Result<()> {
let Some(id) = packet.0 else {
bail!("send_to_client call without id")
};
let Some(client) = self.clients.get(&id) else {
bail!("client with id {id} doesn't exist")
};
self.send_to_addr(client.addr, packet)?;
Ok(())
2023-01-31 20:16:23 -06:00
}
2023-02-12 13:37:06 -06:00
2023-02-06 12:30:26 -06:00
fn add_client(&mut self, addr: SocketAddr) -> Result<ClientId> {
2023-02-06 12:19:02 -06:00
let Some(id) = (1..=self.config.max_clients)
2023-02-05 20:48:43 -06:00
.map(|x| ClientId::new(x as _).unwrap())
2023-02-11 20:22:42 -06:00
.find(|i| !self.clients.contains_key(i)) else {
2023-02-06 12:19:02 -06:00
bail!("Server full");
};
if self.clients.iter().any(|x| x.1.addr == addr) {
bail!("Already connected from the same address");
}
2023-02-05 20:48:43 -06:00
self.clients.insert(id, ConnectedClient {
id,
2023-02-06 12:19:02 -06:00
addr,
2023-02-05 20:48:43 -06:00
timeout: Instant::now(),
});
2023-02-06 12:19:02 -06:00
Ok(id)
2023-02-05 20:48:43 -06:00
}
2023-02-12 13:37:06 -06:00
2023-02-07 18:55:50 -06:00
fn disconnect_client_inner(&mut self, id: ClientId, reason: String) -> Result<()> {
let result = self.send_packet(IdServerPacket(
Some(id), ServerPacket::Disconnected(reason)
));
self.clients.remove(&id);
result
}
pub fn kick_client(&mut self, id: ClientId, reason: String) -> Result<()> {
if !self.clients.contains_key(&id) {
bail!("Already disconnected")
}
self.disconnect_client_inner(id, reason)?;
Ok(())
}
2023-02-12 13:37:06 -06:00
2023-02-07 18:55:50 -06:00
pub fn shutdown(mut self) -> Result<()> {
let clients = self.clients.keys().copied().collect::<Vec<ClientId>>();
for id in clients {
self.kick_client(id, "Server is shutting down".into())?;
}
Ok(())
}
2023-02-12 13:37:06 -06:00
pub fn send_message(&mut self, id: ClientId, message: S) -> Result<()> {
self.send_packet(IdServerPacket(Some(id), ServerPacket::Data(message)))?;
Ok(())
2023-02-07 18:55:50 -06:00
}
pub fn multicast_message(&mut self, clients: impl IntoIterator<Item = ClientId>, message: S) -> Vec<Error> {
//TODO use actual udp multicast
let mut errors = Vec::with_capacity(0);
for client in clients {
if let Err(error) = self.send_message(client, message.clone()) {
log::error!("Message broadcast failed for id {client}");
errors.push(error);
}
}
errors
}
pub fn broadcast_message(&mut self, message: S) -> Vec<Error> {
let ids = self.clients.keys().copied().collect::<Vec<ClientId>>();
self.multicast_message(ids, message)
2023-02-12 18:53:55 -06:00
}
pub fn broadcast_message_except(&mut self, except: ClientId, message: S) -> Vec<Error> {
let ids = self.clients.keys().copied().filter(|&k| k != except).collect::<Vec<ClientId>>();
self.multicast_message(ids, message)
2023-02-12 18:53:55 -06:00
}
2023-02-07 18:55:50 -06:00
pub fn update(&mut self) -> Result<()> {
2023-02-12 19:30:33 -06:00
//kick inactive clients
self.clients.retain(|&id, client| {
if client.timeout.elapsed() > self.config.client_timeout {
if let Err(_) = Self::send_to_addr_inner(&self.socket, client.addr, IdServerPacket(
Some(id), ServerPacket::Disconnected("Timed out".into())
)) {
log::warn!("Client {id} timed out and we failed to send the kick packet. This shouldn't reaally matter")
} else {
log::info!("Client {id} timed out");
}
return false
}
true
});
2023-02-11 20:22:42 -06:00
let mut buf = [0; u16::MAX as usize];
2023-02-12 13:37:06 -06:00
loop {
match self.socket.recv_from(&mut buf) {
Ok((len, addr)) => {
if let Ok(packet) = bincode::decode_from_slice(&buf[..len], BINCODE_CONFIG) {
let (packet, _): (IdClientPacket<R>, _) = packet;
let IdClientPacket(id, packet) = packet;
match id {
Some(id) => {
if !self.clients.contains_key(&id) {
bail!("Client with id {id} doesn't exist");
2023-02-12 18:53:55 -06:00
}
if self.clients.get(&id).unwrap().addr != addr {
bail!("Client addr doesn't match");
}
2023-02-12 13:37:06 -06:00
match packet {
ClientPacket::Data(data) => {
self.event_queue.push_back(ServerEvent::MessageReceived {
from: id,
message: data,
});
}
ClientPacket::Disconnect => {
log::info!("Client {id} disconnected");
self.event_queue.push_back(ServerEvent::Disconnected(id));
self.disconnect_client_inner(id, "Disconnected".into())?;
},
ClientPacket::Heartbeat => {
2023-02-12 18:53:55 -06:00
self.clients.get_mut(&id).unwrap().timeout = Instant::now();
self.send_packet(IdServerPacket(Some(id), ServerPacket::Heartbeat))?;
2023-02-12 13:37:06 -06:00
},
2023-02-12 18:53:55 -06:00
ClientPacket::Connect{..} => bail!("Client already connected"),
2023-02-07 18:55:50 -06:00
}
2023-02-12 13:37:06 -06:00
},
None => {
match packet {
2023-02-12 18:53:55 -06:00
ClientPacket::Connect { user_protocol, inner_protocol } => {
if (inner_protocol != PROTOCOL_ID) || (user_protocol != self.config.protocol_id ) {
log::error!("Client conenction refused: Invalid protocol id");
self.send_to_addr(addr,
IdServerPacket(None, ServerPacket::ProtoDisconnect)
)?;
continue;
}
2023-02-12 13:37:06 -06:00
match self.add_client(addr) {
Ok(id) => {
log::info!("Client with id {id} connected");
self.event_queue.push_back(ServerEvent::Connected(id));
self.send_to_addr(addr,
2023-02-12 18:53:55 -06:00
IdServerPacket(None, ServerPacket::Connected(id))
)?;
2023-02-12 13:37:06 -06:00
},
Err(error) => {
let reason = error.to_string();
log::error!("Client connection failed: {reason}");
self.send_to_addr(addr, IdServerPacket(
None, ServerPacket::Disconnected(reason)
))?;
}
2023-02-07 18:55:50 -06:00
}
2023-02-12 13:37:06 -06:00
},
_ => bail!("Invalid packet type for non-id packet")
}
2023-02-07 18:55:50 -06:00
}
}
2023-02-12 13:37:06 -06:00
} else {
bail!("Corrupted packet received");
2023-02-07 18:55:50 -06:00
}
2023-02-12 13:37:06 -06:00
},
Err(error) if error.kind() != ErrorKind::WouldBlock => {
2023-02-12 15:28:44 -06:00
log::error!("IO error {}", error);
2023-02-12 14:31:21 -06:00
// return Err(error.into());
2023-02-12 13:37:06 -06:00
},
_ => break,
}
2023-02-05 19:40:45 -06:00
}
2023-02-07 18:55:50 -06:00
Ok(())
2023-02-05 19:40:45 -06:00
}
2023-02-12 13:37:06 -06:00
pub fn pop_event(&mut self) -> Option<ServerEvent<R>> {
self.event_queue.pop_front()
}
pub fn process_events(&mut self) -> DrainDeque<ServerEvent<R>> {
self.event_queue.drain(..)
}
2023-01-31 20:16:23 -06:00
}