diff --git a/Cargo.lock b/Cargo.lock index f91925c..914c91b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,15 +2,6 @@ # It is not intended for manual editing. version = 4 -[[package]] -name = "aho-corasick" -version = "1.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" -dependencies = [ - "memchr", -] - [[package]] name = "anyhow" version = "1.0.102" @@ -107,7 +98,6 @@ dependencies = [ "axum", "futures", "rand 0.10.1", - "regex", "serde", "serde_json", "tokio", @@ -678,35 +668,6 @@ dependencies = [ "bitflags", ] -[[package]] -name = "regex" -version = "1.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276" -dependencies = [ - "aho-corasick", - "memchr", - "regex-automata", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-syntax" -version = "0.8.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" - [[package]] name = "ryu" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index f64fae2..5c8450b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,7 +8,6 @@ anyhow = "1.0.102" axum = { version = "0.8.9", features = ["ws"] } futures = "0.3.32" rand = "0.10.1" -regex = "1.12.3" serde = { version = "1.0.228", features = ["derive"] } serde_json = "1.0.149" tokio = { version = "1.52.3", features = ["full"] } diff --git a/rustfmt.toml b/rustfmt.toml index 218e203..157ed0b 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1 +1,3 @@ +brace_style = "AlwaysNextLine" +control_brace_style = "AlwaysNextLine" hard_tabs = true diff --git a/src/main.rs b/src/main.rs index 1485a6a..3620022 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,35 +1,30 @@ // TODO rename pingscores userscores -use std:: -{ +use std::{ collections::HashMap, fs, - io::Write, ops::{Deref, DerefMut}, sync::Arc, }; -use axum:: -{ +use axum::{ Router, - extract:: - { + extract::{ State, ws::{Message, WebSocket, WebSocketUpgrade}, }, response::IntoResponse, routing::get, }; -use tokio:: -{ - sync::{Mutex, mpsc}, - time::{Duration, sleep}, -}; -use tower_http::services::ServeDir; use futures::StreamExt as _; use rand::random_bool; use serde::{Deserialize, Serialize, de}; use serde_json::json; -use regex::Regex; +use tokio::{ + io::AsyncWriteExt as _, + sync::{RwLock, mpsc}, + time::{Duration, sleep}, +}; +use tower_http::services::ServeDir; #[derive(Deserialize, Serialize, Debug, Ord, Eq, PartialEq, PartialOrd, Clone)] struct Entry @@ -41,10 +36,10 @@ struct Entry #[derive(Clone)] struct AppState { - tx: mpsc::Sender, - hiscores: Arc>>, - loscores: Arc>>, - pingscores: Arc>>, // u64 is reset count and u32 is PB + tx: mpsc::UnboundedSender, + hiscores: Arc>>, + loscores: Arc>>, + pingscores: Arc>>, // u64 is reset count and u32 is PB } struct LeaderboardUpdate @@ -55,8 +50,14 @@ struct LeaderboardUpdate enum LeaderboardUpdateType { - Reset { hiscore_pingscore: u32 }, - Increment { loscore: u32 }, + Reset + { + hiscore_pingscore: u32 + }, + Increment + { + loscore: u32 + }, } const CHANCE: f64 = 1.0 / 3.0; @@ -67,17 +68,27 @@ const PATH_PINGSCORES: &str = "pingscores.json"; const MAX_LEADERBOARD: usize = 20; +async fn write_file(file_path: &str, file_contents: &str) -> anyhow::Result<()> +{ + let mut file = tokio::fs::OpenOptions::new() + .write(true) + .truncate(true) + .open(file_path) + .await?; + file.write_all(file_contents.as_bytes()).await?; + file.flush().await?; + Ok(()) +} + #[tokio::main] async fn main() -> anyhow::Result<()> { - fn read_file de::Deserialize<'de>> - ( + fn read_file de::Deserialize<'de>>( file_path: &str, - ) - -> anyhow::Result>> + ) -> anyhow::Result>> { let file_contents: String = fs::read_to_string(file_path)?; - Ok(Arc::new(Mutex::new(serde_json::from_str(&file_contents)?))) + Ok(Arc::new(RwLock::new(serde_json::from_str(&file_contents)?))) } /// Makes the vector at `vec` one with a capacity of exactly [`MAX_LEADERBOARD`] if `vec` is @@ -91,42 +102,34 @@ async fn main() -> anyhow::Result<()> } } - let hiscores: Arc>> = read_file(PATH_HISCORES)?; - exact_leaderboard(hiscores.lock().await); - let loscores: Arc>> = read_file(PATH_LOSCORES)?; - exact_leaderboard(loscores.lock().await); - let pingscores: Arc>> = read_file(PATH_PINGSCORES)?; + let hiscores: Arc>> = read_file(PATH_HISCORES)?; + exact_leaderboard(hiscores.write().await); + let loscores: Arc>> = read_file(PATH_LOSCORES)?; + exact_leaderboard(loscores.write().await); + let pingscores: Arc>> = read_file(PATH_PINGSCORES)?; - let (tx, rx) = mpsc::channel::(1024); + let (tx, rx) = mpsc::unbounded_channel::(); { let (hiscores, loscores, pingscores) = (hiscores.clone(), loscores.clone(), pingscores.clone()); - tokio::spawn - (async move { + tokio::spawn(async move { handle_hiscores(rx, &hiscores, &loscores, &pingscores).await; }); } { let pingscores = pingscores.clone(); - tokio::spawn - (async move { + tokio::spawn(async move { // write pingscores every 30s loop { sleep(Duration::from_secs(30)).await; - let pingscores = pingscores.lock().await; - let file_contents: String = serde_json::to_string(&pingscores.clone()) - .expect("failed to serialize pingscores"); - drop(pingscores); - let mut file = fs::OpenOptions::new() - .write(true) - .truncate(true) - .open(PATH_PINGSCORES) - .expect("failed to open pingscores file"); - file.write_all(file_contents.as_bytes()) + let pingscores = pingscores.read().await.clone(); + let file_contents: String = + serde_json::to_string(&pingscores).expect("failed to serialize pingscores"); + write_file(PATH_PINGSCORES, &file_contents) + .await .expect("failed to write pingscores"); - drop(file); } }); } @@ -136,8 +139,7 @@ async fn main() -> anyhow::Result<()> .fallback_service(static_files) .route("/ws", get(ws_handler)) .route("/ws-leaderboard", get(leaderboard_handler)) - .with_state - (AppState { + .with_state(AppState { tx, hiscores: Arc::clone(&hiscores), loscores: Arc::clone(&loscores), @@ -153,80 +155,74 @@ async fn main() -> anyhow::Result<()> Ok(()) } // receiver: 0 for hiscore, 1 for loscore, 2 for pingscore -async fn handle_hiscores -( - mut rx: mpsc::Receiver, - hiscores: &Mutex>, - loscores: &Mutex>, - pingscores: &Mutex>, +async fn handle_hiscores( + mut rx: mpsc::UnboundedReceiver, + hiscores: &RwLock>, + loscores: &RwLock>, + pingscores: &RwLock>, ) { - fn update_scoretable> + DerefMut> - ( + async fn update_scoretable> + DerefMut>( score_name: &str, mut scoretable_lock: G, name: &str, score: u32, file_path: &str, - ) - -> anyhow::Result<()> + ) -> anyhow::Result<()> { - let scoretable = &mut *scoretable_lock; - if let Some(index_to_insert_at) = scoretable.iter().position(|e| score > e.score) - { - println!("New {score_name} {score} by {name}"); - scoretable[index_to_insert_at..].rotate_right(1); - let push_out = std::mem::replace - ( - &mut scoretable[index_to_insert_at], - Entry + let file_contents = { + let scoretable = &mut *scoretable_lock; + if let Some(index_to_insert_at) = scoretable.iter().position(|e| score > e.score) + { + println!("New {score_name} {score} by {name}"); + scoretable[index_to_insert_at..].rotate_right(1); + let push_out = std::mem::replace( + &mut scoretable[index_to_insert_at], + Entry { + score, + person: name.to_string(), + }, + ); + if scoretable.len() < MAX_LEADERBOARD { + scoretable.push(push_out); + } + + Some(serde_json::to_string(&*scoretable_lock)?) + } + else if scoretable.len() < MAX_LEADERBOARD + { + println!("New {score_name} {score} by {name}"); + scoretable.push(Entry { score, person: name.to_string(), - }, - ); - if scoretable.len() < MAX_LEADERBOARD - { - scoretable.push(push_out); + }); + None } - - let file_contents: String = serde_json::to_string(&*scoretable_lock)?; - drop(scoretable_lock); - let mut file = fs::OpenOptions::new() - .write(true) - .truncate(true) - .open(file_path)?; - file.write_all(file_contents.as_bytes())?; - file.flush()?; - } - else if scoretable.len() < MAX_LEADERBOARD + else + { + None + } + }; + drop(scoretable_lock); + if let Some(file_contents) = file_contents { - println!("New {score_name} {score} by {name}"); - scoretable.push - (Entry { - score, - person: name.to_string(), - }); + write_file(file_path, &file_contents).await?; } Ok(()) } // Panic galore - let mut hiscores_lock = hiscores.lock().await; + let mut hiscores_lock = hiscores.write().await; hiscores_lock.sort(); hiscores_lock.reverse(); let file_contents: String = serde_json::to_string(&hiscores_lock.clone()).expect("failed to serialize hiscores"); drop(hiscores_lock); - let mut file = fs::OpenOptions::new() - .write(true) - .truncate(true) - .open(PATH_HISCORES) - .expect("failed to open hiscores"); - file.write_all(file_contents.as_bytes()) + write_file(PATH_HISCORES, &file_contents) + .await .expect("failed to write hiscores"); - drop(file); loop { @@ -237,18 +233,18 @@ async fn handle_hiscores LeaderboardUpdateType::Reset { hiscore_pingscore } => { // Hiscore - update_scoretable - ( + update_scoretable( "hiscore", - hiscores.lock().await, + hiscores.write().await, &name, hiscore_pingscore, PATH_HISCORES, ) + .await .expect("failed to update hiscores"); // Pingscore - let mut pingscores = pingscores.lock().await; + let mut pingscores = pingscores.write().await; // pb if hiscore_pingscore > pingscores.get(&*name).unwrap_or(&(0, 0)).1 { @@ -261,127 +257,97 @@ async fn handle_hiscores LeaderboardUpdateType::Increment { loscore } => { - update_scoretable - ( + update_scoretable( "loscore", - loscores.lock().await, + loscores.write().await, &name, loscore, PATH_LOSCORES, ) + .await .expect("failed to update loscores"); } } } } -async fn leaderboard_handler -( +async fn leaderboard_handler( ws: WebSocketUpgrade, - State(state): State -) --> impl IntoResponse + State(state): State, +) -> impl IntoResponse { - ws.on_upgrade - (|socket| async move { - handle_leaderboard - ( - socket, - &state.hiscores, - &state.loscores, - &state.pingscores, - ) - .await; + ws.on_upgrade(|socket| async move { + handle_leaderboard(socket, &state.hiscores, &state.loscores, &state.pingscores).await; }) } -async fn handle_leaderboard -( +async fn handle_leaderboard( mut socket: WebSocket, - hiscores: &Mutex>, - loscores: &Mutex>, - pingscores: &Mutex>, + hiscores: &RwLock>, + loscores: &RwLock>, + pingscores: &RwLock>, ) { match socket.next().await { Some(Ok(Message::Text(selection))) => { - let msg; - match selection.as_str() + let msg = match selection.as_str() { - "0" => // all the leaderboards + // all the leaderboards + "0" => { - msg = - { - json! - ({ - "hiscores": &*hiscores.lock().await, - "loscores": &*loscores.lock().await, - "pingscores": &*pingscores.lock().await - }) - .to_string() - }; - }, - "1" => // just the hiscores table - { - msg = json! ({ "hiscores": &*hiscores.lock().await }).to_string() - }, - "2" => // just the loscores table - { - msg = json! ({ "loscores": &*hiscores.lock().await }).to_string() - }, - "3" => // just the pingscores table - { - msg = json! ({ "pingscores": &*hiscores.lock().await }).to_string() - }, - _ => { msg = "Invalid leaderboard selection, please use 0,1,2 or 3".to_string() }, - } + let hiscores = hiscores.read().await.clone(); + let loscores = loscores.read().await.clone(); + let pingscores = pingscores.read().await.clone(); + json! + ({ + "hiscores": hiscores, + "loscores": loscores, + "pingscores": pingscores + }) + .to_string() + } + // just the hiscores table + "1" => json! ({ "hiscores": hiscores.read().await.clone() }).to_string(), + // just the loscores table + "2" => json! ({ "loscores": hiscores.read().await.clone() }).to_string(), + // just the pingscores table + "3" => json! ({ "pingscores": hiscores.read().await.clone() }).to_string(), + _ => "Invalid leaderboard selection, please use 0,1,2 or 3".to_string(), + }; let _ = socket.send(Message::Text(msg.into())).await; - }, + } _ => { - let _ = socket.send(Message::Text("Invalid leaderboard selection, please use 0,1,2 or 3".into())).await; - }, + let _ = socket + .send(Message::Text( + "Invalid leaderboard selection, please use 0,1,2 or 3".into(), + )) + .await; + } } } -async fn ws_handler -( - ws: WebSocketUpgrade, - State(state): State -) - -> impl IntoResponse +async fn ws_handler(ws: WebSocketUpgrade, State(state): State) -> impl IntoResponse { - ws.on_upgrade - (|socket| async move { - handle_socket - ( - socket, - &state.tx, - ) - .await; + ws.on_upgrade(|socket| async move { + handle_socket(socket, &state.tx).await; }) } -async fn handle_socket -( - mut socket: WebSocket, - tx: &mpsc::Sender, -) +async fn handle_socket(mut socket: WebSocket, tx: &mpsc::UnboundedSender) { let mut value: u32 = 0; - let Some(name) = socket.next().await else + let Some(name) = socket.next().await + else { eprintln!("No username"); return; }; let name: Arc = match name.expect("failed to recv socket msg") { - Message::Text(text) => - { - Arc::from(validate_name(&text)) - } + Message::Text(text) => Arc::from(validate_name(&text)), _ => Arc::from("anon"), }; @@ -400,16 +366,12 @@ async fn handle_socket if random_bool(CHANCE) { // reset - let _ = tx - .send(LeaderboardUpdate - { - name: name.clone(), - update: LeaderboardUpdateType::Reset - { - hiscore_pingscore: value, - }, - }) - .await; + let _ = tx.send(LeaderboardUpdate { + name: name.clone(), + update: LeaderboardUpdateType::Reset { + hiscore_pingscore: value, + }, + }); resets += 1; value = 0; } @@ -418,13 +380,10 @@ async fn handle_socket value += 1; if prev == 0 { - let _ = tx - .send - (LeaderboardUpdate { - name: name.clone(), - update: LeaderboardUpdateType::Increment { loscore: resets }, - }) - .await; + let _ = tx.send(LeaderboardUpdate { + name: name.clone(), + update: LeaderboardUpdateType::Increment { loscore: resets }, + }); resets = 0; } } @@ -437,19 +396,34 @@ async fn handle_socket break; } - _ => {} + _ => + {} } } } -fn validate_name(input: &str) -> &str { +fn validate_name(input: &str) -> &str +{ let input = input.trim(); - // Allow only letters, numbers, _ and - - let re = Regex::new(r"^[a-zA-Z0-9_-]+$").unwrap(); - // Length check - if input.is_empty() || input.len() > 32 || !re.is_match(input) + if input == "null" { return "anon"; } - input + + // Length check + if input.is_empty() || input.len() > 32 + { + return "anon"; + } + + if input + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-') + { + input + } + else + { + "anon" + } }