kubi/kubi-server/src/server.rs

66 lines
1.9 KiB
Rust
Raw Normal View History

2023-03-08 13:26:51 -06:00
use shipyard::{AllStoragesView, Unique, UniqueView, UniqueViewMut, NonSendSync};
use uflow::{server::{Server, Event as ServerEvent, Config as ServerConfig}, EndpointConfig};
2023-02-11 17:37:24 -06:00
use crate::config::ConfigTable;
#[derive(Unique)]
#[repr(transparent)]
2023-03-08 13:26:51 -06:00
pub struct UdpServer(pub Server);
2023-02-13 21:27:27 -06:00
#[derive(Unique, Default)]
2023-03-08 13:26:51 -06:00
pub struct ServerEvents(pub Vec<ServerEvent>);
pub trait IsMessageOfType {
///Checks if postcard-encoded message has a type
fn is_message_of_type<const T: u8>(&self) -> bool;
}
impl IsMessageOfType for ServerEvent {
fn is_message_of_type<const T: u8>(&self) -> bool {
let ServerEvent::Receive(_, data) = &self else { return false };
if data.len() == 0 { return false }
data[0] == T
}
}
2023-02-11 17:37:24 -06:00
pub fn bind_server(
storages: AllStoragesView,
) {
log::info!("Creating server...");
let config = storages.borrow::<UniqueView<ConfigTable>>().unwrap();
2023-03-08 13:26:51 -06:00
let server = Server::bind(
2023-02-11 17:37:24 -06:00
config.server.address,
2023-03-08 13:26:51 -06:00
ServerConfig {
max_total_connections: config.server.max_clients,
max_active_connections: config.server.max_clients,
enable_handshake_errors: true,
endpoint_config: EndpointConfig {
active_timeout_ms: config.server.timeout_ms,
2023-03-12 20:34:09 -05:00
keepalive: true,
keepalive_interval_ms: 1000,
2023-03-08 13:26:51 -06:00
..Default::default()
},
2023-02-12 18:53:55 -06:00
..Default::default()
}
2023-03-08 13:26:51 -06:00
).expect("Failed to create the server");
storages.add_unique_non_send_sync(UdpServer(server));
2023-02-13 21:27:27 -06:00
storages.add_unique(ServerEvents::default());
2023-02-11 17:37:24 -06:00
}
pub fn update_server(
2023-03-08 13:26:51 -06:00
mut server: NonSendSync<UniqueViewMut<UdpServer>>,
mut events: UniqueViewMut<ServerEvents>,
2023-02-11 17:37:24 -06:00
) {
2023-03-12 11:58:24 -05:00
server.0.flush();
2023-03-08 13:26:51 -06:00
events.0.clear();
events.0.extend(server.0.step());
2023-02-11 17:37:24 -06:00
}
2023-02-13 21:27:27 -06:00
2023-03-08 13:26:51 -06:00
pub fn log_server_errors(
events: UniqueView<ServerEvents>,
2023-02-13 21:27:27 -06:00
) {
2023-03-08 13:26:51 -06:00
for event in &events.0 {
if let ServerEvent::Error(addr, error) = event {
log::error!("Server error addr: {addr} error: {error:?}");
}
}
2023-02-13 21:27:27 -06:00
}