mirror of
https://github.com/BeamMP/BeamMP-Server.git
synced 2026-10-25 21:40:09 +00:00
closing tui no longer crashes + onShutdown event
This commit is contained in:
1 parent
669e061fdf
commit
6ed714b863
7 files changed
+39
-33
No files matched your search
@@ -5,6 +5,10 @@ function onPluginLoaded()
|
|||||||
print("HI!")
|
print("HI!")
|
||||||
end
|
end
|
||||||
|
|
||||||
|
function onShutdown()
|
||||||
|
print("BYE!")
|
||||||
|
end
|
||||||
|
|
||||||
function onPlayerAuthenticated(joined_name, role, is_guest, identifiers)
|
function onPlayerAuthenticated(joined_name, role, is_guest, identifiers)
|
||||||
print("hi welcome mista " .. joined_name)
|
print("hi welcome mista " .. joined_name)
|
||||||
print("u a guest? " .. tostring(is_guest))
|
print("u a guest? " .. tostring(is_guest))
|
||||||
@@ -36,5 +40,6 @@ function onPlayerDisconnect(pid, name, identifiers)
|
|||||||
end
|
end
|
||||||
|
|
||||||
MP.RegisterEventHandler("onInit", "onPluginLoaded")
|
MP.RegisterEventHandler("onInit", "onPluginLoaded")
|
||||||
|
MP.RegisterEventHandler("onShutdown", "onShutdown")
|
||||||
MP.RegisterEventHandler("onPlayerAuth", "onPlayerAuthenticated")
|
MP.RegisterEventHandler("onPlayerAuth", "onPlayerAuthenticated")
|
||||||
MP.RegisterEventHandler("onPlayerDisconnect", "onPlayerDisconnect")
|
MP.RegisterEventHandler("onPlayerDisconnect", "onPlayerDisconnect")
|
||||||
+5
-2
@@ -72,7 +72,7 @@ async fn server_main(user_config: Arc<config::Config>, mut cmd_rx: mpsc::Receive
|
|||||||
|
|
||||||
let mut status = server.get_server_status();
|
let mut status = server.get_server_status();
|
||||||
hb_tx.send(status.clone()).await;
|
hb_tx.send(status.clone()).await;
|
||||||
loop {
|
'server: loop {
|
||||||
// TODO: Error handling
|
// TODO: Error handling
|
||||||
if server.clients.len() > 0 {
|
if server.clients.len() > 0 {
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
@@ -111,7 +111,10 @@ async fn server_main(user_config: Arc<config::Config>, mut cmd_rx: mpsc::Receive
|
|||||||
match cmd_rx.try_recv() {
|
match cmd_rx.try_recv() {
|
||||||
Ok(cmd) => if cmd.len() > 0 {
|
Ok(cmd) => if cmd.len() > 0 {
|
||||||
match cmd[0].as_str() {
|
match cmd[0].as_str() {
|
||||||
"exit" => break,
|
"exit" => {
|
||||||
|
server.close().await;
|
||||||
|
break 'server;
|
||||||
|
},
|
||||||
_ => info!("Unknown command!"),
|
_ => info!("Unknown command!"),
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -212,14 +212,14 @@ impl Client {
|
|||||||
Some(v) => "/".to_string() + v.to_str().unwrap(),
|
Some(v) => "/".to_string() + v.to_str().unwrap(),
|
||||||
None => {
|
None => {
|
||||||
error!("Client requests invalid mod. Disconnecting");
|
error!("Client requests invalid mod. Disconnecting");
|
||||||
self.kick("Invalid mod request");
|
self.kick("Invalid mod request").await;
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}, // client requested path (fResources/Client/) or nothing at all (f) - invalid
|
}, // client requested path (fResources/Client/) or nothing at all (f) - invalid
|
||||||
};
|
};
|
||||||
let mod_path = format!("Resources/Client{mod_name}");
|
let mod_path = format!("Resources/Client{mod_name}");
|
||||||
if !std::path::Path::new(&mod_path).exists() {
|
if !std::path::Path::new(&mod_path).exists() {
|
||||||
error!("Client requests inexistent mod. Disconnecting");
|
error!("Client requests inexistent mod. Disconnecting");
|
||||||
self.kick("Invalid mod request");
|
self.kick("Invalid mod request").await;
|
||||||
return Ok(()) // client requested mod that doesnt exists within "Resources/Client/*"
|
return Ok(()) // client requested mod that doesnt exists within "Resources/Client/*"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+11
-22
@@ -327,29 +327,18 @@ impl Server {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn process_tcp(&mut self, index: usize, raw_packet: RawPacket) -> anyhow::Result<()> {
|
pub async fn close(mut self) {
|
||||||
// if self.clients.len() > 0 {
|
self.connect_runtime_handle.abort();
|
||||||
// let (result, index, _) = futures::future::select_all(
|
for mut client in self.clients.drain(..) {
|
||||||
// self.clients.iter_mut().map(|client| Box::pin(client.process_blocking()))
|
client.kick("Server is closing!").await;
|
||||||
// ).await;
|
}
|
||||||
//
|
// TODO: We can probably race these with futures::future::select_all?
|
||||||
// match result {
|
for plugin in self.plugins.drain(..) {
|
||||||
// Ok(packet_opt) => {
|
plugin.close().await;
|
||||||
// if let Some(raw_packet) = packet_opt {
|
}
|
||||||
// self.parse_packet(index, raw_packet).await?;
|
}
|
||||||
// }
|
|
||||||
// },
|
|
||||||
// Err(e) => {
|
|
||||||
// if let Some(client) = self.clients.get_mut(index) {
|
|
||||||
// client.kick(&format!("Kicked: {:?}", e)).await;
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// } else {
|
|
||||||
// // TODO: Find a better solution than this lol
|
|
||||||
// tokio::time::sleep(tokio::time::Duration::from_millis(20)).await;
|
|
||||||
// }
|
|
||||||
|
|
||||||
|
pub async fn process_tcp(&mut self, index: usize, raw_packet: RawPacket) -> anyhow::Result<()> {
|
||||||
self.parse_packet(index, raw_packet).await?;
|
self.parse_packet(index, raw_packet).await?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@@ -137,6 +137,7 @@ impl Backend for BackendLua {
|
|||||||
fn call_event_handler(&mut self, event: ScriptEvent, resp: Option<oneshot::Sender<Argument>>) {
|
fn call_event_handler(&mut self, event: ScriptEvent, resp: Option<oneshot::Sender<Argument>>) {
|
||||||
let (event_name, args) = match event {
|
let (event_name, args) = match event {
|
||||||
ScriptEvent::OnPluginLoaded => ("onInit", vec![]),
|
ScriptEvent::OnPluginLoaded => ("onInit", vec![]),
|
||||||
|
ScriptEvent::OnShutdown => ("onShutdown", vec![]),
|
||||||
ScriptEvent::OnPlayerAuthenticated { name, role, is_guest, identifiers } => ("onPlayerAuth", vec![Argument::String(name), Argument::String(role), Argument::Boolean(is_guest), Argument::Table(identifiers.to_map())]),
|
ScriptEvent::OnPlayerAuthenticated { name, role, is_guest, identifiers } => ("onPlayerAuth", vec![Argument::String(name), Argument::String(role), Argument::Boolean(is_guest), Argument::Table(identifiers.to_map())]),
|
||||||
ScriptEvent::OnPlayerDisconnect { pid, name } => ("onPlayerDisconnect", vec![Argument::Number(pid as f32), Argument::String(name)]),
|
ScriptEvent::OnPlayerDisconnect { pid, name } => ("onPlayerDisconnect", vec![Argument::Number(pid as f32), Argument::String(name)]),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -45,6 +45,7 @@ impl PlayerIdentifiers {
|
|||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum ScriptEvent {
|
pub enum ScriptEvent {
|
||||||
OnPluginLoaded,
|
OnPluginLoaded,
|
||||||
|
OnShutdown,
|
||||||
|
|
||||||
OnPlayerAuthenticated { name: String, role: String, is_guest: bool, identifiers: PlayerIdentifiers },
|
OnPlayerAuthenticated { name: String, role: String, is_guest: bool, identifiers: PlayerIdentifiers },
|
||||||
|
|
||||||
@@ -114,6 +115,13 @@ impl Plugin {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn close(mut self) {
|
||||||
|
let (tx, mut rx) = oneshot::channel();
|
||||||
|
self.send_event(PluginBoundPluginEvent::CallEventHandler((ScriptEvent::OnShutdown, Some(tx)))).await;
|
||||||
|
let _ = rx.await; // We just wait for it to finish shutting down
|
||||||
|
self.runtime.shutdown_background();
|
||||||
|
}
|
||||||
|
|
||||||
// TODO: For performance I think we can turn this into an iterator instead of first allocating
|
// TODO: For performance I think we can turn this into an iterator instead of first allocating
|
||||||
// a full vector?
|
// a full vector?
|
||||||
pub fn get_events(&mut self) -> Vec<ServerBoundPluginEvent> {
|
pub fn get_events(&mut self) -> Vec<ServerBoundPluginEvent> {
|
||||||
|
|||||||
+7
-7
@@ -109,17 +109,17 @@ impl Tui {
|
|||||||
let mut lines = Vec::new();
|
let mut lines = Vec::new();
|
||||||
for (i, (level, msg)) in self.log_buffer.iter().enumerate() {
|
for (i, (level, msg)) in self.log_buffer.iter().enumerate() {
|
||||||
if i >= (area.height as usize - 5) { break; }
|
if i >= (area.height as usize - 5) { break; }
|
||||||
let level_style = match level {
|
let (level_style, spacer) = match level {
|
||||||
Level::Info => Style::default().green(),
|
Level::Info => (Style::default().green(), " "),
|
||||||
Level::Warn => Style::default().yellow(),
|
Level::Warn => (Style::default().yellow(), " "),
|
||||||
Level::Error => Style::default().red(),
|
Level::Error => (Style::default().red(), ""),
|
||||||
Level::Debug => Style::default().gray(),
|
Level::Debug => (Style::default().gray(), ""),
|
||||||
Level::Trace => Style::default().cyan(),
|
Level::Trace => (Style::default().cyan(), ""),
|
||||||
};
|
};
|
||||||
lines.push(Line::from(vec![
|
lines.push(Line::from(vec![
|
||||||
Span::styled("[", Style::default()),
|
Span::styled("[", Style::default()),
|
||||||
Span::styled(format!("{}", level), level_style),
|
Span::styled(format!("{}", level), level_style),
|
||||||
Span::styled(format!("] {}", msg), Style::default()),
|
Span::styled(format!("]{} {}", spacer, msg), Style::default()),
|
||||||
]));
|
]));
|
||||||
}
|
}
|
||||||
lines.reverse();
|
lines.reverse();
|
||||||
|
|||||||
Reference in new issue
Block a user