Skip to content

Commit f08fcd5

Browse files
committed
fix compressing order
1 parent 88b1c61 commit f08fcd5

File tree

5 files changed

+85
-50
lines changed

5 files changed

+85
-50
lines changed

protocol/src/error.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,10 @@ pub enum Error {
2828
InvalidPacketId(i32),
2929
#[error("Packet send error: {_0:?}")]
3030
#[diagnostic(code(flume::error::send))]
31-
Send(#[from] flume::SendError<SerializedPacket>),
31+
Send(#[from] flume::SendError<(bool, SerializedPacket)>),
32+
#[error("Packet send error: {_0:?}")]
33+
#[diagnostic(code(flume::error::send))]
34+
SendSingle(#[from] flume::SendError<SerializedPacket>),
3235
#[error("Packet receive error: {_0:?}")]
3336
#[diagnostic(code(flume::error::recv))]
3437
Recv(#[from] flume::RecvError),

protocol/src/executor.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -208,10 +208,10 @@ impl TaskContext {
208208
let (output_tx, output_rx) = tokio::sync::oneshot::channel();
209209
if self.update_run_tx.send(Box::new(move |ctx| {
210210
if output_tx.send(runnable(ctx)).is_err() {
211-
panic!("Failed to sent output from operation run on main thread back to waiting task");
211+
tracing::error!("Failed to sent output from operation run on main thread back to waiting task");
212212
}
213213
})).is_err() {
214-
panic!("Failed to send operation to be run on main thread");
214+
tracing::error!("Failed to send operation to be run on main thread");
215215
}
216216
output_rx
217217
.await

protocol/src/lib.rs

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,10 @@ use std::{
131131
fmt::Debug,
132132
net::SocketAddr,
133133
ops::{Deref, DerefMut},
134-
sync::Arc,
134+
sync::{
135+
atomic::{AtomicBool, Ordering},
136+
Arc,
137+
},
135138
time::Duration,
136139
};
137140

@@ -156,13 +159,13 @@ use crate::{
156159

157160
#[derive(Debug)]
158161
pub struct PlayerNet {
159-
pub send: flume::Sender<SerializedPacket>,
162+
pub send: flume::Sender<(bool, SerializedPacket)>,
160163
pub recv: flume::Receiver<SerializedPacket>,
161164
pub peer_addr: SocketAddr,
162165
pub local_addr: SocketAddr,
163166
pub state: RwLock<State>,
164167
pub compression: Option<usize>,
165-
pub compressing: Arc<RwLock<bool>>,
168+
pub compressing: Arc<AtomicBool>,
166169
pub cancellator: CancellationToken,
167170
}
168171

@@ -186,14 +189,13 @@ impl PlayerNet {
186189
let (s_recv, recv) = flume::unbounded();
187190
let (send, r_send) = flume::unbounded();
188191

189-
let compressing = Arc::new(RwLock::new(false));
192+
let compressing = Arc::new(AtomicBool::new(false));
190193

191194
let compressing_ = compressing.clone();
192195
let send_task = tokio::spawn(async move {
193196
let Err::<!, _>(e) = async {
194197
loop {
195-
let packet: SerializedPacket = r_send.recv_async().await?;
196-
let compres = compressing_.get_copy().await;
198+
let (compres, packet): (bool, SerializedPacket) = r_send.recv_async().await?;
197199
let data = if compression.is_some_and(|_| compres) {
198200
trace!("[send]compressing");
199201
packet.serialize_compressing(compression)?
@@ -220,7 +222,7 @@ impl PlayerNet {
220222
loop {
221223
let bufslice = &buf[..];
222224
let mut input = Input::new(&bufslice);
223-
if let Some(packet) = match if compressing__.get_copy().await {
225+
if let Some(packet) = match if compressing__.load(Ordering::SeqCst) {
224226
SerializedPacketCompressed::deserialize
225227
.parse_with(&mut input)
226228
.map(SerializedPacket::from)
@@ -305,24 +307,32 @@ impl PlayerNet {
305307
}
306308

307309
/// Writes a packet.
308-
pub fn send_packet<T: Packet + Serialize + Debug>(&self, packet: T) -> Result<()> {
310+
pub async fn send_packet<T: Packet + Serialize + Debug>(&self, packet: T) -> Result<()> {
309311
if self.send.is_disconnected() {
310312
trace!(?packet, addr=%self.peer_addr, "sending packet failed - disconnected");
311313
return Err(crate::error::Error::ConnectionEnded);
312314
}
313315
let spack = SerializedPacket::new_ref(&packet)?;
314316
trace!(?packet, addr=%self.peer_addr, ?spack, "Sending packet");
315-
Ok(self.send.send(spack)?)
317+
Ok(self
318+
.send
319+
.send_async((self.compressing.load(Ordering::SeqCst), spack))
320+
.await?)
316321
}
317322

318323
/// Sends a plugin message.
319324
/// Equivalent to `self.send_packet(PluginMessage { channel, data: data.serialize() })`
320-
pub fn plugin_message<T: Serialize + Debug>(&self, channel: Identifier, data: T) -> Result<()> {
325+
pub async fn plugin_message<T: Serialize + Debug>(
326+
&self,
327+
channel: Identifier,
328+
data: T,
329+
) -> Result<()> {
321330
trace!(?channel, ?data, %self.peer_addr, "Sending plugin message");
322331
self.send_packet(PluginMessage {
323332
channel,
324333
data: data.serialize()?,
325334
})
335+
.await
326336
}
327337

328338
/// Receives a packet and tries to deserialize it.

protocol/src/model/packets.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ impl SerializedPacket {
9494
Zlib::encode(&self.data)?.len() + VarInt(maybe_data_length as i32).length_of(),
9595
)
9696
} else {
97+
trace!("packet was smaller than threshold {cmp}, sending uncompressed");
9798
(0, self.length)
9899
};
99100
let pack = SerializedPacketCompressed {
@@ -270,7 +271,11 @@ impl Serialize for SerializedPacketCompressed {
270271
.map_err(|_| Error::VarIntTooBig)?,
271272
);
272273
data_length.serialize_to(buf)?;
273-
Compress((&self.id, &self.data), Zlib).serialize_to(buf)?;
274+
if self.data_length > 0 {
275+
Compress((&self.id, &self.data), Zlib).serialize_to(buf)?
276+
} else {
277+
(&self.id, &self.data).serialize_to(buf)?
278+
}
274279
Ok(())
275280
}
276281
}

server/src/main.rs

Lines changed: 53 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,10 @@ use oxcr_protocol::{
3333
uuid::Uuid,
3434
AsyncSet, PlayerN, PlayerNet, ProtocolPlugin,
3535
};
36-
use std::{net::SocketAddr, sync::Arc};
36+
use std::{
37+
net::SocketAddr,
38+
sync::{atomic::Ordering, Arc},
39+
};
3740
use tokio::net::TcpListener;
3841
use tokio_util::sync::CancellationToken;
3942
use tracing::instrument;
@@ -84,15 +87,17 @@ async fn login(net: Arc<PlayerNet>, cx: Arc<TaskContext>, ent_id: Entity) -> Res
8487

8588
net.send_packet(SetCompression {
8689
threshold: VarInt::<i32>(threshold.try_into().unwrap()),
87-
})?;
90+
})
91+
.await?;
8892

89-
net.compressing.set(true).await;
93+
net.compressing.store(true, Ordering::SeqCst);
9094
}
9195

9296
net.send_packet(LoginSuccess {
9397
uuid,
9498
username: name.clone(),
95-
})?;
99+
})
100+
.await?;
96101

97102
net.state.set(State::Play).await;
98103

@@ -168,28 +173,32 @@ async fn login(net: Arc<PlayerNet>, cx: Arc<TaskContext>, ent_id: Entity) -> Res
168173
portal_cooldown: VarInt(20),
169174
};
170175

171-
net.send_packet(login_play)?;
176+
net.send_packet(login_play).await?;
172177

173178
let difficulty = cx
174179
.run_on_main_thread(move |w| *w.world.resource::<DifficultySetting>())
175180
.await;
176181

177182
net.send_packet(FeatureFlags {
178183
feature_flags: Array::new(&[FeatureFlags::FEATURE_VANILLA]),
179-
})?;
184+
})
185+
.await?;
180186

181-
net.plugin_message(Identifier::MINECRAFT_BRAND, "implodent")?;
187+
net.plugin_message(Identifier::MINECRAFT_BRAND, "implodent")
188+
.await?;
182189

183190
net.send_packet(ChangeDifficulty {
184191
difficulty: difficulty.difficulty,
185192
difficulty_locked: difficulty.is_locked,
186-
})?;
193+
})
194+
.await?;
187195

188196
net.send_packet(PlayerAbilities {
189197
flags: Abilities::FLYING,
190198
flying_speed: 0.05f32,
191199
fov_modifier: 0.1f32,
192-
})?;
200+
})
201+
.await?;
193202

194203
net.send_packet(SetDefaultSpawnPosition {
195204
location: Position {
@@ -198,7 +207,8 @@ async fn login(net: Arc<PlayerNet>, cx: Arc<TaskContext>, ent_id: Entity) -> Res
198207
y: 50i8.into(),
199208
},
200209
angle: 0f32,
201-
})?;
210+
})
211+
.await?;
202212

203213
Ok(())
204214
}
@@ -242,10 +252,11 @@ async fn status(net: Arc<PlayerNet>) -> Result<()> {
242252
},
243253
..Default::default()
244254
}),
245-
})?;
255+
})
256+
.await?;
246257

247258
let PingRequest { payload } = net.recv_packet().await?;
248-
net.send_packet(PongResponse { payload })?;
259+
net.send_packet(PongResponse { payload }).await?;
249260

250261
Ok(())
251262
}
@@ -324,30 +335,36 @@ fn on_login(rt: Res<TokioTasksRuntime>, mut ev: EventReader<PlayerLoginEvent>, q
324335
let player = q.get(event.entity).unwrap().0.clone();
325336
rt.spawn_background_task(move |task| async move {
326337
let cx = Arc::new(task);
327-
match when_the_miette(lifecycle(player.clone(), cx.clone(), event.entity).await) {
328-
Ok(()) => Ok::<(), Error>(()),
329-
Err(e) => {
330-
error!(error=?e, ?player, "Disconnecting");
331-
332-
// ignore the result because we term the connection afterwards
333-
let _ = match *(player.state.read().await) {
334-
State::Login => player.send_packet(DisconnectLogin {
335-
reason: Json(ChatComponent::String(ChatStringComponent {
336-
text: format!("{e}"),
337-
..Default::default()
338-
})),
339-
}),
340-
State::Play => player.send_packet(DisconnectPlay {
341-
reason: Json(ChatComponent::String(ChatStringComponent {
342-
text: format!("{e}"),
343-
..Default::default()
344-
})),
345-
}),
346-
_ => Ok(()),
347-
};
348-
349-
player.cancellator.cancel();
350-
338+
tokio::select! {
339+
lfc = lifecycle(player.clone(), cx.clone(), event.entity) => match when_the_miette(lfc) {
340+
Ok(()) => Ok::<(), Error>(()),
341+
Err(e) => {
342+
error!(error=?e, ?player, "Disconnecting");
343+
344+
// ignore the result because we term the connection afterwards
345+
let _ = match *(player.state.read().await) {
346+
State::Login => player.send_packet(DisconnectLogin {
347+
reason: Json(ChatComponent::String(ChatStringComponent {
348+
text: format!("{e}"),
349+
..Default::default()
350+
})),
351+
}).await,
352+
State::Play => player.send_packet(DisconnectPlay {
353+
reason: Json(ChatComponent::String(ChatStringComponent {
354+
text: format!("{e}"),
355+
..Default::default()
356+
})),
357+
}).await,
358+
_ => Ok(()),
359+
};
360+
361+
player.cancellator.cancel();
362+
363+
Ok(())
364+
}
365+
},
366+
_ = player.cancellator.cancelled() => {
367+
info!("connection ended");
351368
Ok(())
352369
}
353370
}

0 commit comments

Comments
 (0)