Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added a 100ms sleep to the keep alive system to prevent it from having excessive cpu usage #117

Merged
merged 5 commits into from
Nov 10, 2024
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions src/bin/src/systems/keep_alive_system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ use async_trait::async_trait;
use ferrumc_core::identity::player_identity::PlayerIdentity;
use ferrumc_net::connection::{ConnectionState, StreamWriter};
use ferrumc_net::packets::outgoing::keep_alive::{KeepAlive, KeepAlivePacket};
use ferrumc_net::utils::broadcast::{BroadcastOptions, BroadcastToAll};
use ferrumc_net::GlobalState;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use tracing::{error, info, trace, warn};
use ferrumc_net::utils::broadcast::{BroadcastOptions, BroadcastToAll};

pub struct KeepAliveSystem {
shutdown: AtomicBool,
Expand All @@ -24,6 +24,7 @@ impl KeepAliveSystem {
#[async_trait]
impl System for KeepAliveSystem {
async fn start(self: Arc<Self>, state: GlobalState) {
info!("Started keep_alive");
let mut last_time = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("Time went backwards")
Expand Down Expand Up @@ -71,7 +72,8 @@ impl System for KeepAliveSystem {

let packet = KeepAlivePacket::default();

let broadcast_opts = BroadcastOptions::default().only(entities)
let broadcast_opts = BroadcastOptions::default()
.only(entities)
.with_sync_callback(move |entity, state| {
let Ok(mut keep_alive) = state.universe.get_mut::<KeepAlive>(entity) else {
warn!("Failed to get <KeepAlive> component for entity {}", entity);
Expand All @@ -84,7 +86,8 @@ impl System for KeepAliveSystem {
if let Err(e) = state.broadcast(&packet, broadcast_opts).await {
error!("Error sending keep alive packet: {}", e);
};

// TODO, this should be configurable as some people may have bad network so the clients may end up disconnecting from the server moments before the keep alive is sent
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

15 seconds delay means the client gets 2 chances. The default timeout for keepalive is 30 seconds.

tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;
}
}

Expand Down