refactored println statements into formatted logs with log crate
This commit is contained in:
1263
server/Cargo.lock
generated
Normal file
1263
server/Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
@@ -15,6 +15,8 @@ uuid = {version = "1.18.1", features = ["v4", "serde"] }
|
||||
anyhow = "1.0.100"
|
||||
rand = "0.9.2"
|
||||
engine = {path = "../engine/"}
|
||||
log = {version = "0.4.28"}
|
||||
env_logger = "0.11.8"
|
||||
|
||||
|
||||
[[bin]]
|
||||
|
||||
@@ -3,6 +3,7 @@ use engine::chessmove::ChessMove;
|
||||
use engine::gameend::GameEnd::{self, *};
|
||||
use engine::{get_available_moves, is_game_over};
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use log::{error, info, warn};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::sync::Arc;
|
||||
@@ -19,14 +20,17 @@ pub type WaitingQueue = Arc<Mutex<VecDeque<Uuid>>>;
|
||||
|
||||
// Helper functions to create new instances
|
||||
pub fn new_connection_map() -> ConnectionMap {
|
||||
warn!("Created new connection map");
|
||||
Arc::new(Mutex::new(HashMap::new()))
|
||||
}
|
||||
|
||||
pub fn new_match_map() -> MatchMap {
|
||||
warn!("Created new match map");
|
||||
Arc::new(Mutex::new(HashMap::new()))
|
||||
}
|
||||
|
||||
pub fn new_waiting_queue() -> WaitingQueue {
|
||||
warn!("Created new waiting queue");
|
||||
Arc::new(Mutex::new(VecDeque::new()))
|
||||
}
|
||||
|
||||
@@ -103,11 +107,11 @@ pub async fn send_message_to_player_connection(
|
||||
) -> Result<(), tokio_tungstenite::tungstenite::Error> {
|
||||
match connection {
|
||||
Some(connection) => {
|
||||
println!("sending message to: {}", connection.id);
|
||||
info!("sending message to: {}", connection.id);
|
||||
connection.tx.send(Message::Text(message.to_string())).await
|
||||
}
|
||||
None => {
|
||||
eprintln!("No connection provided");
|
||||
error!("No connection provided");
|
||||
Err(tokio_tungstenite::tungstenite::Error::ConnectionClosed)
|
||||
}
|
||||
}
|
||||
@@ -119,7 +123,7 @@ pub async fn broadcast_to_all(connections: &ConnectionMap, message: &str) {
|
||||
|
||||
for (id, connection) in connections_lock.iter_mut() {
|
||||
if let Err(e) = connection.tx.send(Message::Text(message.to_string())).await {
|
||||
eprintln!("Failed to send to {}: {}", id, e);
|
||||
error!("Failed to send to {}: {}", id, e);
|
||||
dead_connections.push(*id);
|
||||
}
|
||||
}
|
||||
@@ -136,6 +140,7 @@ pub async fn broadcast_to_match(
|
||||
match_id: Uuid,
|
||||
message: &str,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
info!("Broadcasting data to match: {}", &match_id);
|
||||
let matches_lock = matches.lock().await;
|
||||
if let Some(game_match) = matches_lock.get(&match_id) {
|
||||
send_message_to_player_connection(
|
||||
@@ -163,6 +168,7 @@ pub async fn handle_connection(
|
||||
|
||||
let ws_stream = accept_async(stream).await?;
|
||||
let (write, mut read) = ws_stream.split();
|
||||
warn!("Accepted new connection");
|
||||
|
||||
let player_id = Uuid::new_v4();
|
||||
|
||||
@@ -180,33 +186,33 @@ pub async fn handle_connection(
|
||||
);
|
||||
}
|
||||
|
||||
println!("New connection: {}", player_id);
|
||||
info!("id: {}", &player_id);
|
||||
|
||||
// Message processing loop
|
||||
while let Some(Ok(message)) = read.next().await {
|
||||
if message.is_text() {
|
||||
let text = message.to_text()?;
|
||||
println!("Received from {}: {}", player_id, text);
|
||||
info!("Received from {}: {}", player_id, text);
|
||||
|
||||
let client_data: ClientEvent = serde_json::from_str(text)
|
||||
.expect("Failed to convert data into json at handle_connection");
|
||||
|
||||
//println!("client: {:?}", client_data);
|
||||
|
||||
match client_data {
|
||||
Join { username } => {
|
||||
{
|
||||
let mut conn_map = connections.lock().await;
|
||||
let player = conn_map.get_mut(&player_id).unwrap();
|
||||
player.username = Some(username);
|
||||
player.username = Some(username.clone());
|
||||
info!("player: {}, set username: {}", &player_id, username);
|
||||
}
|
||||
|
||||
//respone to client
|
||||
// TODO: switch over to server message 2?
|
||||
let response: EventResponse = EventResponse {
|
||||
response: core::result::Result::Ok(()),
|
||||
};
|
||||
|
||||
println!("response: {:?}", response);
|
||||
info!("response: {:?}", response);
|
||||
|
||||
let mut conn_map = connections.lock().await;
|
||||
let _ = send_message_to_player_connection(
|
||||
@@ -218,8 +224,8 @@ pub async fn handle_connection(
|
||||
FindMatch => {
|
||||
let mut wait_queue = waiting_queue.lock().await;
|
||||
wait_queue.push_back(player_id.clone());
|
||||
println!("Appended {} to the waiting queue", player_id);
|
||||
println!("queue {:?}", wait_queue);
|
||||
info!("Appended {} to the waiting queue", player_id);
|
||||
info!("queue {:?}", wait_queue);
|
||||
}
|
||||
Move { step } => {
|
||||
let match_id = connections
|
||||
@@ -231,6 +237,7 @@ pub async fn handle_connection(
|
||||
.unwrap();
|
||||
|
||||
{
|
||||
info!("updating board state in match: {}", &match_id);
|
||||
let mut matches = matches.lock().await;
|
||||
matches.get_mut(&match_id).unwrap().board_state =
|
||||
engine::get_board_after_move(
|
||||
@@ -261,6 +268,7 @@ pub async fn handle_connection(
|
||||
&matches.lock().await.get(&match_id).unwrap().board_state,
|
||||
) {
|
||||
Some(res) => {
|
||||
warn!("A player won the match: {}", &match_id);
|
||||
let message = ServerMessage2::GameEnd { winner: res };
|
||||
let _ = broadcast_to_match(
|
||||
&connections,
|
||||
@@ -271,26 +279,27 @@ pub async fn handle_connection(
|
||||
.await;
|
||||
}
|
||||
None => {
|
||||
println!("No winner match continues.")
|
||||
info!("No winner match continues. Id: {}", &match_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
RequestLegalMoves { fen } => {
|
||||
info!("Requesting legal moves player: {}", &player_id);
|
||||
let moves = get_available_moves(&fen);
|
||||
let _ = send_message_to_player_connection(
|
||||
connections.lock().await.get_mut(&player_id),
|
||||
&serde_json::to_string(&moves).unwrap(),
|
||||
)
|
||||
.await;
|
||||
println!("Sent moves to player: {}", player_id);
|
||||
info!("Sent moves to player: {}", player_id);
|
||||
}
|
||||
Resign => {
|
||||
// TODO: set game over and turn on game end ui, then delete the match
|
||||
println!("Resigned!");
|
||||
warn!("Resigned!");
|
||||
}
|
||||
_ => {
|
||||
println!("Not known client event");
|
||||
warn!("Not known client event");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -298,7 +307,7 @@ pub async fn handle_connection(
|
||||
|
||||
// Cleanup on disconnect
|
||||
cleanup_player(player_id, &connections, &matches, &waiting_queue).await;
|
||||
println!("Connection {} closed", player_id);
|
||||
warn!("Connection {} closed", player_id);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -315,7 +324,7 @@ async fn cleanup_player(
|
||||
// Remove from connections
|
||||
connections.lock().await.remove(&player_id);
|
||||
|
||||
println!("Cleaned up player {}", player_id);
|
||||
warn!("Cleaned up player {}", player_id);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1,12 +1,19 @@
|
||||
mod connection;
|
||||
mod matchmaking;
|
||||
use dotenvy::dotenv;
|
||||
use env_logger::{Env, Logger};
|
||||
use log::{error, info, warn};
|
||||
use std::env;
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let env = Env::default().filter_or("MY_LOG_LEVEL", "INFO");
|
||||
env_logger::init_from_env(env);
|
||||
|
||||
let address = "0.0.0.0:9001";
|
||||
let listener = TcpListener::bind(address).await?;
|
||||
println!("Server running on ws://{}", address);
|
||||
info!("Server running on ws://{}", address);
|
||||
|
||||
// Shared state initialization using the new helper functions
|
||||
let connections = connection::new_connection_map();
|
||||
@@ -33,7 +40,7 @@ async fn main() -> anyhow::Result<()> {
|
||||
if let Err(e) =
|
||||
connection::handle_connection(stream, connections, matches, waiting_queue).await
|
||||
{
|
||||
eprintln!("Connection error: {}", e);
|
||||
error!("Connection error: {}", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::connection::ServerMessage2;
|
||||
use crate::connection::{ConnectionMap, GameMatch, MatchMap, WaitingQueue, broadcast_to_match};
|
||||
use log::{error, info, warn};
|
||||
use rand::random;
|
||||
use uuid::Uuid;
|
||||
|
||||
@@ -26,16 +27,21 @@ impl MatchmakingSystem {
|
||||
}
|
||||
|
||||
async fn try_create_match(&self) {
|
||||
info!("Checking for new matches!");
|
||||
let mut queue = self.waiting_queue.lock().await;
|
||||
|
||||
while queue.len() >= 2 {
|
||||
let player1 = queue.pop_front().unwrap();
|
||||
let player2 = queue.pop_front().unwrap();
|
||||
|
||||
info!("Creating new match. Players: {}, {}", &player1, &player2);
|
||||
|
||||
let match_id = Uuid::new_v4();
|
||||
let (white_player, black_player) = if random::<bool>() {
|
||||
info!("player1 is white, player2 is black");
|
||||
(player1, player2)
|
||||
} else {
|
||||
info!("player2 is white, player1 is black");
|
||||
(player2, player1)
|
||||
};
|
||||
|
||||
@@ -47,6 +53,8 @@ impl MatchmakingSystem {
|
||||
move_history: Vec::new(),
|
||||
};
|
||||
|
||||
info!("Match id: {}", &game_match.id);
|
||||
|
||||
// Store the match
|
||||
self.matches.lock().await.insert(match_id, game_match);
|
||||
|
||||
@@ -55,14 +63,18 @@ impl MatchmakingSystem {
|
||||
let mut conn_map = self.connections.lock().await;
|
||||
if let Some(player) = conn_map.get_mut(&white_player) {
|
||||
player.current_match = Some(match_id);
|
||||
} else {
|
||||
error!("Could not store match id for white player");
|
||||
}
|
||||
if let Some(player) = conn_map.get_mut(&black_player) {
|
||||
player.current_match = Some(match_id);
|
||||
} else {
|
||||
error!("Could not store match id for black player");
|
||||
}
|
||||
}
|
||||
|
||||
// Notify players
|
||||
println!(
|
||||
info!(
|
||||
"Notifying player for a match: {:?} | {:?}",
|
||||
white_player, black_player
|
||||
);
|
||||
@@ -112,7 +124,7 @@ impl MatchmakingSystem {
|
||||
.await;
|
||||
}
|
||||
|
||||
println!("Match created: {} (white) vs {} (black)", white, black);
|
||||
info!("Match created: {} (white) vs {} (black)", white, black);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user