From 0a9ff1761526255df86578f72de17b92396ad4ca Mon Sep 17 00:00:00 2001 From: Pierre HUBERT Date: Fri, 11 Mar 2022 22:46:13 +0100 Subject: [PATCH] Add asynchronous operation in user websocket --- src/controllers/user_ws_controller.rs | 34 +++++++++++++++------------ 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/src/controllers/user_ws_controller.rs b/src/controllers/user_ws_controller.rs index 8357049..8fa32b7 100644 --- a/src/controllers/user_ws_controller.rs +++ b/src/controllers/user_ws_controller.rs @@ -244,7 +244,7 @@ impl WsSession { } /// Handle incoming message - fn handle_message(&self, ctx: &mut ws::WebsocketContext, msg: &str) -> Res { + async fn handle_message(addr: Addr, msg: &str) -> Res { let incoming_msg: UserWsMessage = serde_json::from_str(&msg)?; let data = incoming_msg.data.as_object() @@ -262,7 +262,7 @@ impl WsSession { } let mut handler = UserWsRequestHandler::new( - &find_connection(ctx.address()).ok_or(ExecError::boxed_new("Connection not found!"))?, + &find_connection(addr).ok_or(ExecError::boxed_new("Connection not found!"))?, args, ); @@ -357,23 +357,27 @@ impl StreamHandler> for WsSession { } ws::Message::Text(msg) => { - match self.handle_message(ctx, &msg) { - Ok(msg) => { - let response = serde_json::to_string(&msg) - .unwrap_or("Failed to serialize".to_string()); + let addr = ctx.address(); + let future = async move { + match Self::handle_message(addr.clone(), &msg).await { + Ok(msg) => { + let response = serde_json::to_string(&msg) + .unwrap_or("Failed to serialize".to_string()); - if conf().verbose_mode { - println!("USER WEBSOCKET RESPONSE {}", response); + if conf().verbose_mode { + println!("USER WEBSOCKET RESPONSE {}", response); + } + + addr.do_send(WsQueuedMessage(response)) } - ctx.text(response) + Err(e) => { + println!("WS processing error: {}", e); + addr.do_send(WsQueuedMessage("Failed to parse message".to_string())); + } } - - Err(e) => { - println!("WS processing error: {}", e); - ctx.text("Failed to parse message"); - } - } + }; + future.into_actor(self).spawn(ctx); } ws::Message::Binary(_) => {