diff --git a/Cargo.lock b/Cargo.lock index 34420ef0..a3425ffa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -354,7 +354,7 @@ dependencies = [ "getrandom", "once_cell", "version_check", - "zerocopy", + "zerocopy 0.7.35", ] [[package]] @@ -424,6 +424,7 @@ dependencies = [ "bimap", "cfg-if", "chrono", + "codee", "console_error_panic_hook", "cookie 0.18.1", "db", @@ -713,9 +714,9 @@ checksum = "e0ec6b951b160caa93cc0c7b209e5a3bff7aae9062213451ac99493cd844c239" [[package]] name = "cc" -version = "1.1.6" +version = "1.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2aba8f4e9906c7ce3c73463f62a7f0c65183ada1a2d47e397cc8810827f9694f" +checksum = "26a5c3fd7bfa1ce3897a3a3501d362b2d87b7f2583ebcb4a949ec25911025cbc" dependencies = [ "jobserver", "libc", @@ -779,6 +780,17 @@ dependencies = [ "inout", ] +[[package]] +name = "codee" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af40247be877a1e3353fb406aa27ab3ef4bd3ff18cef91e75e667bfa3fde701d" +dependencies = [ + "rmp-serde", + "serde", + "thiserror", +] + [[package]] name = "collection_literals" version = "1.0.1" @@ -1929,9 +1941,9 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] name = "leptix_primitives" -version = "0.2.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abb1c55c1e0403f008c8f82362e4e247034552d64cf641f51d12a2c46d391bf7" +checksum = "d3918fee422cf80296a97f3c10a628419835eaa149e5da96d8205e82dbe32240" dependencies = [ "derive_more", "itertools 0.12.1", @@ -1966,12 +1978,13 @@ dependencies = [ [[package]] name = "leptos-use" -version = "0.10.10" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3272d90b77cdbb99e9060f90eb6f5738e56128b2f912db57a50efb006a26e262" +checksum = "118fc5800f2ad58888ee849f0c133d9d62a63244c99f6e67170bf3558241b562" dependencies = [ "async-trait", "cfg-if", + "codee", "cookie 0.18.1", "default-struct-builder", "futures-util", @@ -2622,9 +2635,12 @@ checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" [[package]] name = "ppv-lite86" -version = "0.2.17" +version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" +checksum = "dee4364d9f3b902ef14fab8a1ddffb783a1cb6b4bba3bfc1fa3922732c7de97f" +dependencies = [ + "zerocopy 0.6.6", +] [[package]] name = "pq-sys" @@ -2816,6 +2832,28 @@ version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a66a03ae7c801facd77a29370b4faec201768915ac14a721ba36f20bc9c209b" +[[package]] +name = "rmp" +version = "0.8.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "228ed7c16fa39782c3b3468e974aec2795e9089153cd08ee2e9aefb3613334c4" +dependencies = [ + "byteorder", + "num-traits", + "paste", +] + +[[package]] +name = "rmp-serde" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52e599a477cf9840e92f2cde9a7189e67b42c57532749bf90aea6ec10facd4db" +dependencies = [ + "byteorder", + "rmp", + "serde", +] + [[package]] name = "rstml" version = "0.11.2" @@ -3931,13 +3969,34 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" +[[package]] +name = "zerocopy" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "854e949ac82d619ee9a14c66a1b674ac730422372ccb759ce0c39cabcf2bf8e6" +dependencies = [ + "byteorder", + "zerocopy-derive 0.6.6", +] + [[package]] name = "zerocopy" version = "0.7.35" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" dependencies = [ - "zerocopy-derive", + "zerocopy-derive 0.7.35", +] + +[[package]] +name = "zerocopy-derive" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "125139de3f6b9d625c39e2efdd73d41bdac468ccd556556440e322be0e1bbd91" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.72", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index b2f49ec0..5add15e1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,7 +10,7 @@ opt-level = 'z' [workspace.dependencies] leptos = { version = "0.6" , features = ["nightly"] } -leptos-use = { version = "0.10" } +leptos-use = { version = "0.11" } leptos_meta = { version = "0.6" , features = ["nightly"] } leptos_router = { version = "0.6" , features = ["nightly"] } leptos_actix = { version = "0.6" } @@ -32,6 +32,7 @@ serde_json = { version = "1" } cfg-if = "1.0.0" console_error_panic_hook = "0.1.7" console_log = "1.0.0" +codee = { version = "0.1.2", features = ["msgpack_serde"] } regex = "1.10" http = "1.1.0" log = "0.4.22" @@ -56,7 +57,7 @@ cookie = "0.18" skillratings = "0.27" chrono = { version = "0.4", features = ["serde"] } itertools = "0.13.0" -leptix_primitives = { version = "0.2.0" } +leptix_primitives = { version = "0.2" } tree-ds = {version = "0.1.5", features = ["serde", "compact_serde"] } bimap = {version = "0.6.3", features = ["serde"] } # Defines a size-optimized profile for the WASM bundle in release mode diff --git a/apis/Cargo.toml b/apis/Cargo.toml index 80e7c785..1ff2a837 100644 --- a/apis/Cargo.toml +++ b/apis/Cargo.toml @@ -17,6 +17,7 @@ actix = { workspace = true, optional = true } argon2 = { workspace = true, optional = true } cfg-if = { workspace = true } chrono = { workspace = true } +codee ={ workspace = true } console_error_panic_hook = { workspace = true } cookie = { workspace = true } db = { path = "../db", optional = true } diff --git a/apis/src/common/mod.rs b/apis/src/common/mod.rs index 5cbcdd57..6a624b21 100644 --- a/apis/src/common/mod.rs +++ b/apis/src/common/mod.rs @@ -24,8 +24,8 @@ pub use move_info::MoveInfo; pub use piece_type::PieceType; pub use rating_change_info::RatingChangeInfo; pub use server_result::{ - ChallengeUpdate, ExternalServerError, GameActionResponse, GameUpdate, ServerMessage, - ServerResult, TournamentUpdate, UserStatus, UserUpdate, + ChallengeUpdate, CommonMessage, ExternalServerError, GameActionResponse, GameUpdate, + ServerMessage, ServerResult, TournamentUpdate, UserStatus, UserUpdate, }; pub use svg_pos::SvgPos; pub use time_signals::TimeSignals; diff --git a/apis/src/common/server_result.rs b/apis/src/common/server_result.rs index 89fc7bb2..05ffa39a 100644 --- a/apis/src/common/server_result.rs +++ b/apis/src/common/server_result.rs @@ -1,4 +1,5 @@ use super::game_reaction::GameReaction; +use super::ClientRequest; use crate::responses::{ ChallengeResponse, GameResponse, HeartbeatResponse, TournamentResponse, UserResponse, }; @@ -15,6 +16,11 @@ pub enum ServerResult { Err(ExternalServerError), } +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum CommonMessage { + Server(ServerResult), + Client(ClientRequest), +} #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ExternalServerError { pub user_id: Uuid, diff --git a/apis/src/jobs/tournament_start.rs b/apis/src/jobs/tournament_start.rs index 7ee019c7..ffa3335b 100644 --- a/apis/src/jobs/tournament_start.rs +++ b/apis/src/jobs/tournament_start.rs @@ -1,5 +1,6 @@ use crate::common::{ - GameActionResponse, GameReaction, GameUpdate, ServerMessage, ServerResult, TournamentUpdate, + CommonMessage, GameActionResponse, GameReaction, GameUpdate, ServerMessage, ServerResult, + TournamentUpdate, }; use crate::responses::{GameResponse, TournamentResponse}; use crate::websockets::internal_server_message::{InternalServerMessage, MessageDestination}; @@ -7,6 +8,8 @@ use crate::websockets::messages::ClientActorMessage; use crate::websockets::ws_server::WsServer; use actix::Addr; use actix_web::web::Data; +use codee::binary::MsgpackSerdeCodec; +use codee::Encoder; use db_lib::{get_conn, models::Tournament, DbPool}; use diesel_async::scoped_futures::ScopedFutureExt; use diesel_async::AsyncConnection; @@ -81,16 +84,17 @@ pub fn run(pool: DbPool, ws_server: Data>) { } } for message in messages { - let serialized = serde_json::to_string(&ServerResult::Ok( + let serialized = CommonMessage::Server(ServerResult::Ok( Box::new(message.message), - )) - .expect("Failed to serialize a server message"); - let cam = ClientActorMessage { - destination: message.destination, - serialized, - from: None, + )); + if let Ok(serialized) = MsgpackSerdeCodec::encode(&serialized) { + let cam = ClientActorMessage { + destination: message.destination, + serialized, + from: None, + }; + ws_server.do_send(cam); }; - ws_server.do_send(cam); } } Ok(()) diff --git a/apis/src/providers/api_requests.rs b/apis/src/providers/api_requests.rs index fe0e76db..f625a8f8 100644 --- a/apis/src/providers/api_requests.rs +++ b/apis/src/providers/api_requests.rs @@ -30,8 +30,7 @@ impl ApiRequests { game_id: game_id.clone(), action: GameAction::Turn(turn), }; - self.websocket - .send(&serde_json::to_string(&msg).expect("Serde_json::to_string failed")); + self.websocket.send(&msg); let mut games = expect_context::(); // TODO: fix this so that it just removes from next_games games.remove_from_next_games(&game_id); games.own_games_remove(&game_id); @@ -39,8 +38,7 @@ impl ApiRequests { pub fn pong(&self, nonce: u64) { let msg = ClientRequest::Pong(nonce); - self.websocket - .send(&serde_json::to_string(&msg).expect("Serde_json::to_string failed")); + self.websocket.send(&msg); } pub fn game_control(&self, game_id: GameId, gc: GameControl) { @@ -48,8 +46,7 @@ impl ApiRequests { game_id, action: GameAction::Control(gc), }; - self.websocket - .send(&serde_json::to_string(&msg).expect("Serde_json::to_string failed")); + self.websocket.send(&msg); } pub fn tournament_game_start(&self, game_id: GameId) { @@ -57,14 +54,12 @@ impl ApiRequests { game_id, action: GameAction::Start, }; - self.websocket - .send(&serde_json::to_string(&msg).expect("Serde_json::to_string failed")); + self.websocket.send(&msg); } pub fn tournament_abandon(&self, tournament_id: TournamentId) { let msg = ClientRequest::Tournament(TournamentAction::Abandon(tournament_id)); - self.websocket - .send(&serde_json::to_string(&msg).expect("Serde_json::to_string failed")); + self.websocket.send(&msg); } pub fn tournament_adjudicate_game_result( @@ -74,20 +69,17 @@ impl ApiRequests { ) { let msg = ClientRequest::Tournament(TournamentAction::AdjudicateResult(game_id, new_result)); - self.websocket - .send(&serde_json::to_string(&msg).expect("Serde_json::to_string failed")); + self.websocket.send(&msg); } pub fn chat(&self, message: &ChatMessageContainer) { let msg = ClientRequest::Chat(message.to_owned()); - self.websocket - .send(&serde_json::to_string(&msg).expect("Serde_json::to_string failed")); + self.websocket.send(&msg); } pub fn tournament(&self, action: TournamentAction) { let msg = ClientRequest::Tournament(action.to_owned()); - self.websocket - .send(&serde_json::to_string(&msg).expect("Serde_json::to_string failed")); + self.websocket.send(&msg); } pub fn game_check_time(&self, game_id: &GameId) { @@ -95,8 +87,7 @@ impl ApiRequests { game_id: game_id.clone(), action: GameAction::CheckTime, }; - self.websocket - .send(&serde_json::to_string(&msg).expect("Serde_json::to_string failed")); + self.websocket.send(&msg); } pub fn join(&self, game_id: GameId) { @@ -104,8 +95,7 @@ impl ApiRequests { game_id, action: GameAction::Join, }; - self.websocket - .send(&serde_json::to_string(&msg).expect("Serde_json::to_string failed")); + self.websocket.send(&msg); } pub fn challenge(&self, challenge_action: ChallengeAction) { @@ -130,34 +120,29 @@ impl ApiRequests { }; if let Some(challenge_action) = challenge_action { let msg = ClientRequest::Challenge(challenge_action); - self.websocket - .send(&serde_json::to_string(&msg).expect("Serde_json::to_string failed")); + self.websocket.send(&msg); } } pub fn challenge_cancel(&self, challenger_id: ChallengeId) { let msg = ClientRequest::Challenge(ChallengeAction::Delete(challenger_id)); - self.websocket - .send(&serde_json::to_string(&msg).expect("Serde_json::to_string failed")); + self.websocket.send(&msg); } pub fn challenge_accept(&self, challenger_id: ChallengeId) { let msg = ClientRequest::Challenge(ChallengeAction::Accept(challenger_id)); - self.websocket - .send(&serde_json::to_string(&msg).expect("Serde_json::to_string failed")); + self.websocket.send(&msg); } pub fn challenge_get(&self, challenger_id: ChallengeId) { let msg = ClientRequest::Challenge(ChallengeAction::Get(challenger_id)); - self.websocket - .send(&serde_json::to_string(&msg).expect("Serde_json::to_string failed")); + self.websocket.send(&msg); } pub fn search_user(&self, pattern: String) { if !pattern.is_empty() { let msg = ClientRequest::UserSearch(pattern); - self.websocket - .send(&serde_json::to_string(&msg).expect("Serde_json::to_string failed")); + self.websocket.send(&msg); } } } diff --git a/apis/src/providers/websocket/context.rs b/apis/src/providers/websocket/context.rs index a9952350..61a5a0d9 100644 --- a/apis/src/providers/websocket/context.rs +++ b/apis/src/providers/websocket/context.rs @@ -1,16 +1,14 @@ +use super::response_handler::handle_response; +use crate::common::{ClientRequest, CommonMessage}; use crate::functions::hostname::hostname_and_port; - +use codee::binary::MsgpackSerdeCodec; use lazy_static::lazy_static; use leptos::*; - use leptos_use::core::ConnectionReadyState; use leptos_use::*; use regex::Regex; - use std::rc::Rc; -use super::response_handler::handle_response; - lazy_static! { static ref NANOID: Regex = Regex::new(r"/game/(?.*)").expect("This regex should compile"); @@ -18,8 +16,8 @@ lazy_static! { #[derive(Clone)] pub struct WebsocketContext { - pub message: Signal>, - send: Rc, + pub message: Signal>, + send: Rc, pub ready_state: Signal, open: Rc, close: Rc, @@ -27,8 +25,8 @@ pub struct WebsocketContext { impl WebsocketContext { pub fn new( - message: Signal>, - send: Rc, + message: Signal>, + send: Rc, ready_state: Signal, open: Rc, close: Rc, @@ -43,8 +41,9 @@ impl WebsocketContext { } #[inline(always)] - pub fn send(&self, message: &str) { - (self.send)(message) + pub fn send(&self, message: &ClientRequest) { + let message = CommonMessage::Client(message.clone()); + (self.send)(&message) } #[inline(always)] @@ -60,7 +59,7 @@ impl WebsocketContext { } } -fn on_message_callback(m: String) { +fn on_message_callback(m: &CommonMessage) { handle_response(m); } @@ -81,14 +80,14 @@ fn fix_wss(url: &str) -> String { pub fn provide_websocket(url: &str) { let url = fix_wss(url); //log!("Establishing new websocket connection"); - let UseWebsocketReturn { + let UseWebSocketReturn { message, send, ready_state, open, close, .. - } = use_websocket_with_options( + } = use_websocket_with_options::( &url, UseWebSocketOptions::default() .on_message(on_message_callback) diff --git a/apis/src/providers/websocket/response_handler.rs b/apis/src/providers/websocket/response_handler.rs index 8fbb1479..25c68487 100644 --- a/apis/src/providers/websocket/response_handler.rs +++ b/apis/src/providers/websocket/response_handler.rs @@ -1,4 +1,4 @@ -use crate::common::{ServerMessage::*, ServerResult}; +use crate::common::{CommonMessage, ServerMessage::*, ServerResult}; use leptos::logging::log; use leptos::*; @@ -9,10 +9,10 @@ use super::{ user_search::handle::handle_user_search, user_status::handle::handle_user_status, }; -pub fn handle_response(m: String) { - batch(move || match serde_json::from_str::(&m) { - Ok(result) => match result { - ServerResult::Ok(message) => match *message { +pub fn handle_response(m: &CommonMessage) { + batch(move || match m { + CommonMessage::Server(result) => match result { + ServerResult::Ok(message) => match *message.clone() { Ping { value, nonce } => handle_ping(nonce, value), UserStatus(user_update) => handle_user_status(user_update), Game(game_update) => handle_game(*game_update), @@ -26,6 +26,8 @@ pub fn handle_response(m: String) { }, ServerResult::Err(e) => log!("Got error from server: {e}"), }, - Err(e) => log!("Can't parse: {m}, error is: {e}"), + CommonMessage::Client(request) => { + log!("Got a client request: {request:?}") + } }); } diff --git a/apis/src/websockets/messages.rs b/apis/src/websockets/messages.rs index 4dc269cc..7fd7a56f 100644 --- a/apis/src/websockets/messages.rs +++ b/apis/src/websockets/messages.rs @@ -5,7 +5,7 @@ use super::internal_server_message::MessageDestination; #[derive(Message, Debug)] #[rtype(result = "()")] -pub struct WsMessage(pub String); +pub struct WsMessage(pub Vec); #[derive(Message, Debug)] #[rtype(result = "()")] @@ -38,11 +38,11 @@ pub struct Ping {} pub struct ClientActorMessage { pub destination: MessageDestination, pub from: Option, - pub serialized: String, // the serialized message + pub serialized: Vec, // the serialized message } impl ClientActorMessage { - pub fn new(from: Option, destination: MessageDestination, serialized: &str) -> Self { + pub fn new(from: Option, destination: MessageDestination, serialized: &Vec) -> Self { Self { from, destination, diff --git a/apis/src/websockets/ws_connection.rs b/apis/src/websockets/ws_connection.rs index da2896c1..21fc01e0 100644 --- a/apis/src/websockets/ws_connection.rs +++ b/apis/src/websockets/ws_connection.rs @@ -1,6 +1,6 @@ use super::tournament_game_start::TournamentGameStart; use super::{api::request_handler::RequestHandler, internal_server_message::MessageDestination}; -use crate::common::{ClientRequest, ExternalServerError, ServerResult}; +use crate::common::{CommonMessage, ExternalServerError, ServerResult}; use crate::lag_tracking::lags::Lags; use crate::ping::pings::Pings; use crate::websockets::{ @@ -12,8 +12,9 @@ use actix::{ fut, Actor, ActorContext, ActorFutureExt, Addr, AsyncContext, ContextFutureSpawner, Handler, Running, StreamHandler, WrapFuture, }; -use actix_web_actors::ws::{self, Message::Text}; +use actix_web_actors::ws::{self}; use anyhow::Result; +use codee::{binary::MsgpackSerdeCodec, Decoder, Encoder}; use db_lib::DbPool; use shared_types::SimpleUser; use std::time::{Duration, Instant}; @@ -123,9 +124,9 @@ impl StreamHandler> for WsConnection { Ok(ws::Message::Pong(_)) => { self.hb = Instant::now(); } - Ok(ws::Message::Binary(bin)) => { - println!("Got bin message, we don't do these here..."); - ctx.binary(bin) + Ok(ws::Message::Text(bin)) => { + println!("Got text message, we don't do these here..."); + ctx.text(bin) } Ok(ws::Message::Close(reason)) => { ctx.close(reason); @@ -135,8 +136,9 @@ impl StreamHandler> for WsConnection { ctx.stop(); } Ok(ws::Message::Nop) => (), - Ok(Text(s)) => { - if let Ok(request) = serde_json::from_str::(s.as_ref()) { + Ok(ws::Message::Binary(s)) => { + let request: Result = MsgpackSerdeCodec::decode(&s); + if let Ok(CommonMessage::Client(request)) = request { let pool = self.pool.clone(); let lobby = self.wss_addr.clone(); let user_id = self.user_uid; @@ -168,16 +170,17 @@ impl StreamHandler> for WsConnection { match handler_result { Ok(messages) => { for message in messages { - let serialized = serde_json::to_string(&ServerResult::Ok( + let serialized = CommonMessage::Server(ServerResult::Ok( Box::new(message.message), - )) - .expect("Failed to serialize a server message"); - let cam = ClientActorMessage { - destination: message.destination, - serialized, - from: Some(user_id), + )); + if let Ok(serialized) = MsgpackSerdeCodec::encode(&serialized) { + let cam = ClientActorMessage { + destination: message.destination, + serialized, + from: Some(user_id), + }; + lobby.do_send(cam); }; - lobby.do_send(cam); } } Err(err) => { @@ -196,14 +199,15 @@ impl StreamHandler> for WsConnection { reason: format!("{err}"), status_code: http::StatusCode::NOT_IMPLEMENTED, }); - let serialized = serde_json::to_string(&message) - .expect("Failed to serialize a server message"); - let cam = ClientActorMessage { - destination: MessageDestination::User(user_id), - serialized, - from: Some(user_id), + let serialized = CommonMessage::Server(message); + if let Ok(serialized) = MsgpackSerdeCodec::encode(&serialized) { + let cam = ClientActorMessage { + destination: MessageDestination::User(user_id), + serialized, + from: Some(user_id), + }; + lobby.do_send(cam); }; - lobby.do_send(cam); } } }; @@ -224,6 +228,6 @@ impl Handler for WsConnection { type Result = (); fn handle(&mut self, msg: WsMessage, ctx: &mut Self::Context) { - ctx.text(msg.0); + ctx.binary(msg.0); } } diff --git a/apis/src/websockets/ws_server.rs b/apis/src/websockets/ws_server.rs index 14965d5c..1971f7a1 100644 --- a/apis/src/websockets/ws_server.rs +++ b/apis/src/websockets/ws_server.rs @@ -3,8 +3,8 @@ use super::{internal_server_message::MessageDestination, messages::Ping}; use crate::ping::pings::Pings; use crate::{ common::{ - ChallengeUpdate, GameUpdate, ServerMessage, ServerResult, TournamentUpdate, UserStatus, - UserUpdate, + ChallengeUpdate, CommonMessage, GameUpdate, ServerMessage, ServerResult, TournamentUpdate, + UserStatus, UserUpdate, }, responses::{ ChallengeResponse, GameResponse, HeartbeatResponse, TournamentResponse, UserResponse, @@ -16,6 +16,8 @@ use actix::{ AsyncContext, WrapFuture, }; use actix_web::web::Data; +use codee::binary::MsgpackSerdeCodec; +use codee::Encoder; use db_lib::{ get_conn, models::{Challenge, Game, Tournament, TournamentInvitation, User}, @@ -53,7 +55,7 @@ impl WsServer { } impl WsServer { - fn send_message(&self, message: &str, id_to: &Uuid) { + fn send_message(&self, message: &Vec, id_to: &Uuid) { if let Some(sockets) = self.sessions.get(id_to) { for socket in sockets { socket.do_send(WsMessage(message.to_owned())); @@ -78,9 +80,10 @@ impl Handler for WsServer { nonce, value: self.pings.value(*user_id), })); - let serialized = - serde_json::to_string(&message).expect("Failed to serialize a server message"); - self.send_message(&serialized, user_id); + let serialized = CommonMessage::Server(message); + if let Ok(serialized) = MsgpackSerdeCodec::encode(&serialized) { + self.send_message(&serialized, user_id); + }; } } } @@ -110,15 +113,16 @@ impl Handler for WsServer { let message = ServerResult::Ok(Box::new(ServerMessage::Game( Box::new(GameUpdate::Heartbeat(hb)), ))); - let serialized = serde_json::to_string(&message) - .expect("Failed to serialize a server message"); - for user_id in user_ids { - if let Some(sockets) = sessions.get(&user_id) { - for socket in sockets { - socket.do_send(WsMessage(serialized.clone())); + let serialized = CommonMessage::Server(message); + if let Ok(serialized) = MsgpackSerdeCodec::encode(&serialized) { + for user_id in user_ids { + if let Some(sockets) = sessions.get(&user_id) { + for socket in sockets { + socket.do_send(WsMessage(serialized.clone())); + } } } - } + }; } } } @@ -161,17 +165,18 @@ impl Handler for WsServer { user: None, username: msg.username, }))); - let serialized = - serde_json::to_string(&message).expect("Failed to serialize a server message"); - let game_id = GameId(self.id.clone()); - if let Some(ws_server) = self.games_users.get_mut(&game_id) { - ws_server.remove(&msg.user_id); - } - if let Some(ws_server) = self.games_users.get(&game_id) { - ws_server - .iter() - .for_each(|user_id| self.send_message(&serialized, user_id)); - } + let serialized = CommonMessage::Server(message); + if let Ok(serialized) = MsgpackSerdeCodec::encode(&serialized) { + let game_id = GameId(self.id.clone()); + if let Some(ws_server) = self.games_users.get_mut(&game_id) { + ws_server.remove(&msg.user_id); + } + if let Some(ws_server) = self.games_users.get(&game_id) { + ws_server + .iter() + .for_each(|user_id| self.send_message(&serialized, user_id)); + } + }; } } } @@ -208,14 +213,15 @@ impl Handler for WsServer { user: Some(user_response.clone()), username: user_response.username, }))); - let serialized = serde_json::to_string(&message) - .expect("Failed to serialize a server message"); - let cam = ClientActorMessage { - destination: MessageDestination::User(user_id), - serialized, - from: Some(user_id), + let serialized = CommonMessage::Server(message); + if let Ok(serialized) = MsgpackSerdeCodec::encode(&serialized) { + let cam = ClientActorMessage { + destination: MessageDestination::User(user_id), + serialized, + from: Some(user_id), + }; + address.do_send(cam); }; - address.do_send(cam); } } @@ -227,19 +233,20 @@ impl Handler for WsServer { user: Some(user_response), username: msg.username, }))); - let serialized = serde_json::to_string(&message) - .expect("Failed to serialize a server message"); - // TODO: one needs to be a game::join to everyone in the game, the other one just to the - // ws_server that the user came online - if let Some(user_ids) = games_users.get(&GameId(msg.game_id)) { - for id in user_ids { - if let Some(sockets) = sessions.get(id) { - for socket in sockets { - socket.do_send(WsMessage(serialized.clone())); + let serialized = CommonMessage::Server(message); + if let Ok(serialized) = MsgpackSerdeCodec::encode(&serialized) { + // TODO: one needs to be a game::join to everyone in the game, the other one just to the + // ws_server that the user came online + if let Some(user_ids) = games_users.get(&GameId(msg.game_id)) { + for id in user_ids { + if let Some(sockets) = sessions.get(id) { + for socket in sockets { + socket.do_send(WsMessage(serialized.clone())); + } } } } - } + }; } // Send games which require input from the user @@ -270,14 +277,15 @@ impl Handler for WsServer { let message = ServerResult::Ok(Box::new(ServerMessage::Game( Box::new(GameUpdate::Urgent(games)), ))); - let serialized = serde_json::to_string(&message) - .expect("Failed to serialize a server message"); - let cam = ClientActorMessage { - destination: MessageDestination::User(user_id), - serialized, - from: Some(user_id), + let serialized = CommonMessage::Server(message); + if let Ok(serialized) = MsgpackSerdeCodec::encode(&serialized) { + let cam = ClientActorMessage { + destination: MessageDestination::User(user_id), + serialized, + from: Some(user_id), + }; + address.do_send(cam); }; - address.do_send(cam); } } // send tournament invitations @@ -292,14 +300,15 @@ impl Handler for WsServer { let message = ServerResult::Ok(Box::new( ServerMessage::Tournament(TournamentUpdate::Invited(response)), )); - let serialized = serde_json::to_string(&message) - .expect("Failed to serialize a server message"); - let cam = ClientActorMessage { - destination: MessageDestination::User(user_id), - serialized, - from: Some(user_id), + let serialized = CommonMessage::Server(message); + if let Ok(serialized) = MsgpackSerdeCodec::encode(&serialized) { + let cam = ClientActorMessage { + destination: MessageDestination::User(user_id), + serialized, + from: Some(user_id), + }; + address.do_send(cam); }; - address.do_send(cam); } } } @@ -338,7 +347,8 @@ impl Handler for WsServer { let message = ServerResult::Ok(Box::new(ServerMessage::Challenge( ChallengeUpdate::Challenges(responses), ))); - serde_json::to_string(&message).expect("Failed to serialize a server message") + let message = CommonMessage::Server(message); + MsgpackSerdeCodec::encode(&message) } else { let mut responses = Vec::new(); if let Ok(challenges) = Challenge::get_public(&mut conn).await { @@ -353,14 +363,17 @@ impl Handler for WsServer { let message = ServerResult::Ok(Box::new(ServerMessage::Challenge( ChallengeUpdate::Challenges(responses), ))); - serde_json::to_string(&message).expect("Failed to serialize a server message") + let message = CommonMessage::Server(message); + MsgpackSerdeCodec::encode(&message) }; - let cam = ClientActorMessage { - destination: MessageDestination::User(user_id), - serialized, - from: Some(user_id), + if let Ok(serialized) = serialized { + let cam = ClientActorMessage { + destination: MessageDestination::User(user_id), + serialized, + from: Some(user_id), + }; + address.do_send(cam); }; - address.do_send(cam); } }; let actor_future = future.into_actor(self);