Skip to content

Commit f94bbe8

Browse files
committed
Implement Suggestions
1 parent cfeec4d commit f94bbe8

File tree

5 files changed

+79
-66
lines changed

5 files changed

+79
-66
lines changed

Diff for: src/bin/src/systems/keep_alive_system.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use ferrumc_net::connection::{ConnectionState, StreamWriter};
55
use ferrumc_net::packets::incoming::keep_alive::IncomingKeepAlivePacket;
66
use ferrumc_net::packets::outgoing::keep_alive::OutgoingKeepAlivePacket;
77
use ferrumc_net::utils::broadcast::{BroadcastOptions, BroadcastToAll};
8-
use ferrumc_net::utils::state::terminate_connection;
8+
use ferrumc_net::utils::state::TerminateConnectionPlayerExt;
99
use ferrumc_state::GlobalState;
1010
use std::sync::atomic::{AtomicBool, Ordering};
1111
use std::sync::Arc;
@@ -76,9 +76,8 @@ impl System for KeepAliveSystem {
7676

7777
if (current_time - keep_alive.timestamp) >= 30000 {
7878
// two iterations missed
79-
if let Err(e) = terminate_connection(
79+
if let Err(e) = entity.terminate_connection(
8080
state.clone(),
81-
*entity,
8281
"Keep alive timeout".to_string(),
8382
)
8483
.await

Diff for: src/lib/net/crates/codec/src/net_types/length_prefixed_vec.rs

+12-9
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use crate::decode::{NetDecode, NetDecodeOpts, NetDecodeResult};
22
use crate::encode::{NetEncode, NetEncodeOpts, NetEncodeResult};
33
use crate::net_types::var_int::VarInt;
4+
use std::ops::{Deref, DerefMut};
45
use std::io::{Read, Write};
56
use tokio::io::AsyncWrite;
67

@@ -13,17 +14,19 @@ impl<T> LengthPrefixedVec<T> {
1314
pub fn new(data: Vec<T>) -> Self {
1415
Self { data }
1516
}
17+
}
1618

17-
pub fn push(&mut self, value: T) {
18-
self.data.push(value);
19-
}
19+
impl<T> Deref for LengthPrefixedVec<T> {
20+
type Target = Vec<T>;
2021

21-
pub fn pop(&mut self) -> Option<T> {
22-
self.data.pop()
22+
fn deref(&self) -> &Self::Target {
23+
&self.data
2324
}
25+
}
2426

25-
pub fn length(&self) -> usize {
26-
self.data.len()
27+
impl<T> DerefMut for LengthPrefixedVec<T> {
28+
fn deref_mut(&mut self) -> &mut Self::Target {
29+
&mut self.data
2730
}
2831
}
2932

@@ -32,7 +35,7 @@ where
3235
T: NetEncode,
3336
{
3437
fn encode<W: Write>(&self, writer: &mut W, opts: &NetEncodeOpts) -> NetEncodeResult<()> {
35-
VarInt::from(self.length()).encode(writer, opts)?;
38+
VarInt::from(self.len()).encode(writer, opts)?;
3639

3740
for item in &self.data {
3841
item.encode(writer, opts)?;
@@ -46,7 +49,7 @@ where
4649
writer: &mut W,
4750
opts: &NetEncodeOpts,
4851
) -> NetEncodeResult<()> {
49-
VarInt::from(self.length()).encode_async(writer, opts).await?;
52+
VarInt::from(self.len()).encode_async(writer, opts).await?;
5053

5154
for item in &self.data {
5255
item.encode_async(writer, opts).await?;

Diff for: src/lib/net/src/connection.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use crate::packets::incoming::packet_skeleton::PacketSkeleton;
2-
use crate::utils::state::terminate_connection;
2+
use crate::utils::state::TerminateConnectionPlayerExt;
33
use crate::{handle_packet, NetResult, packets::outgoing::disconnect::DISCONNECT_STRING};
44
use crate::errors::NetError;
55
use ferrumc_net_codec::encode::NetEncode;
@@ -164,7 +164,7 @@ pub async fn handle_connection(state: Arc<ServerState>, tcp_stream: TcpStream) -
164164
{
165165
match e {
166166
NetError::Kick(msg) => {
167-
terminate_connection(state.clone(), entity, msg.clone())
167+
entity.terminate_connection(state.clone(), msg.clone())
168168
.await?;
169169
},
170170
_ => {
@@ -174,7 +174,7 @@ pub async fn handle_connection(state: Arc<ServerState>, tcp_stream: TcpStream) -
174174
packet_skele.id,
175175
conn_state.as_str()
176176
);
177-
terminate_connection(state.clone(), entity, DISCONNECT_STRING.to_string())
177+
entity.terminate_connection(state.clone(), DISCONNECT_STRING.to_string())
178178
.await?;
179179
}
180180
}

Diff for: src/lib/net/src/packets/incoming/keep_alive.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use crate::packets::outgoing::keep_alive::OutgoingKeepAlivePacket;
22
use crate::packets::IncomingPacket;
3-
use crate::utils::state::terminate_connection;
3+
use crate::utils::state::TerminateConnectionPlayerExt;
44
use crate::NetResult;
55
use ferrumc_macros::{packet, NetDecode};
66
use ferrumc_state::ServerState;
@@ -22,7 +22,7 @@ impl IncomingPacket for IncomingKeepAlivePacket {
2222
conn_id, self.timestamp, last_sent_keep_alive.timestamp
2323
);
2424
if let Err(e) =
25-
terminate_connection(state, conn_id, "Invalid keep alive packet".to_string()).await
25+
conn_id.terminate_connection(state, "Invalid keep alive packet".to_string()).await
2626
{
2727
debug!("Error terminating connection: {:?}", e);
2828
}

Diff for: src/lib/net/src/utils/state.rs

+60-49
Original file line numberDiff line numberDiff line change
@@ -10,61 +10,72 @@ use tracing::{trace, warn};
1010

1111
use super::ecs_helpers::EntityExt;
1212

13-
// used codium for this function comment, very useful
13+
pub trait TerminateConnectionPlayerExt {
14+
#[allow(async_fn_in_trait)]
15+
async fn terminate_connection(
16+
&self,
17+
state: GlobalState,
18+
reason: impl Into<ferrumc_text::TextComponent>,
19+
) -> NetResult<()>;
20+
}
1421

15-
/// Terminates the connection of an entity with the given `conn_id`.
16-
///
17-
/// Sends a disconnect packet with the given `reason` to the client, and marks the connection as
18-
/// terminated. This will cause the connection to be dropped on the next tick of the
19-
/// `ConnectionSystem`.
20-
///
21-
/// # Errors
22-
///
23-
/// Returns an error if the stream writer or connection control component cannot be accessed for
24-
/// the given `conn_id`.
25-
pub async fn terminate_connection(
26-
state: GlobalState,
27-
conn_id: usize,
28-
reason: impl Into<ferrumc_text::TextComponent>,
29-
) -> NetResult<()> {
30-
let mut writer = match conn_id.get_mut::<StreamWriter>(&state.clone()) {
31-
Ok(writer) => writer,
32-
Err(e) => {
33-
warn!("Failed to get stream writer for entity {}: {}", conn_id, e);
34-
return Err(NetError::ECSError(e));
35-
}
36-
};
22+
impl TerminateConnectionPlayerExt for usize {
23+
// used codium for this function comment, very useful
3724

38-
let conn_state = conn_id.get::<ConnectionState>(&state.clone())?;
25+
/// Terminates the connection of an entity with the given `conn_id`.
26+
///
27+
/// Sends a disconnect packet with the given `reason` to the client, and marks the connection as
28+
/// terminated. This will cause the connection to be dropped on the next tick of the
29+
/// `ConnectionSystem`.
30+
///
31+
/// # Errors
32+
///
33+
/// Returns an error if the stream writer or connection control component cannot be accessed for
34+
/// the given `conn_id`.
35+
async fn terminate_connection(
36+
&self,
37+
state: GlobalState,
38+
reason: impl Into<ferrumc_text::TextComponent>,
39+
) -> NetResult<()> {
40+
let mut writer = match self.get_mut::<StreamWriter>(&state.clone()) {
41+
Ok(writer) => writer,
42+
Err(e) => {
43+
warn!("Failed to get stream writer for entity {}: {}", self, e);
44+
return Err(NetError::ECSError(e));
45+
}
46+
};
3947

40-
if let Err(e) = writer
41-
.send_packet(
42-
&DisconnectPacket::from(&conn_state, reason)?,
43-
&NetEncodeOpts::WithLength,
44-
)
45-
.await
46-
{
47-
warn!(
48-
"Failed to send disconnect packet to entity {}: {}",
49-
conn_id, e
50-
);
51-
return Err(e);
52-
}
48+
let conn_state = self.get::<ConnectionState>(&state.clone())?;
5349

54-
match conn_id.get_mut::<ConnectionControl>(&state.clone()) {
55-
Ok(mut control) => {
56-
control.should_disconnect = true;
57-
58-
trace!("Set should_disconnect to true for entity {}", conn_id);
59-
}
60-
Err(e) => {
50+
if let Err(e) = writer
51+
.send_packet(
52+
&DisconnectPacket::from(&conn_state, reason)?,
53+
&NetEncodeOpts::WithLength,
54+
)
55+
.await
56+
{
6157
warn!(
62-
"Failed to get connection control for entity {}: {}",
63-
conn_id, e
58+
"Failed to send disconnect packet to entity {}: {}",
59+
self, e
6460
);
65-
return Err(NetError::ECSError(e));
61+
return Err(e);
6662
}
67-
}
6863

69-
Ok(())
64+
match self.get_mut::<ConnectionControl>(&state.clone()) {
65+
Ok(mut control) => {
66+
control.should_disconnect = true;
67+
68+
trace!("Set should_disconnect to true for entity {}", self);
69+
}
70+
Err(e) => {
71+
warn!(
72+
"Failed to get connection control for entity {}: {}",
73+
self, e
74+
);
75+
return Err(NetError::ECSError(e));
76+
}
77+
}
78+
79+
Ok(())
80+
}
7081
}

0 commit comments

Comments
 (0)