From f7921cbefb997f044dbf2c1de5873ac3ade28899 Mon Sep 17 00:00:00 2001 From: ErrorNoInternet Date: Mon, 1 Jun 2026 20:53:20 -0400 Subject: [PATCH 1/2] treewide: set up formatting --- rustfmt.toml | 2 + src/main.rs | 220 +++++++++++++++++++++------------------------------ 2 files changed, 94 insertions(+), 128 deletions(-) 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..8da2841 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,5 @@ // TODO rename pingscores userscores -use std:: -{ +use std::{ collections::HashMap, fs, io::Write, @@ -8,28 +7,25 @@ use std:: sync::Arc, }; -use axum:: -{ +use axum::{ Router, - extract:: - { + extract::{ State, ws::{Message, WebSocket, WebSocketUpgrade}, }, response::IntoResponse, routing::get, }; -use tokio:: -{ +use futures::StreamExt as _; +use rand::random_bool; +use regex::Regex; +use serde::{Deserialize, Serialize, de}; +use serde_json::json; +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; #[derive(Deserialize, Serialize, Debug, Ord, Eq, PartialEq, PartialOrd, Clone)] struct Entry @@ -55,8 +51,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; @@ -70,11 +72,8 @@ const MAX_LEADERBOARD: usize = 20; #[tokio::main] async fn main() -> anyhow::Result<()> { - fn read_file de::Deserialize<'de>> - ( - file_path: &str, - ) - -> anyhow::Result>> + fn read_file de::Deserialize<'de>>(file_path: &str) + -> anyhow::Result>> { let file_contents: String = fs::read_to_string(file_path)?; Ok(Arc::new(Mutex::new(serde_json::from_str(&file_contents)?))) @@ -101,16 +100,14 @@ async fn main() -> anyhow::Result<()> { 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 { @@ -136,8 +133,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,34 +149,29 @@ async fn main() -> anyhow::Result<()> Ok(()) } // receiver: 0 for hiscore, 1 for loscore, 2 for pingscore -async fn handle_hiscores -( +async fn handle_hiscores( mut rx: mpsc::Receiver, hiscores: &Mutex>, loscores: &Mutex>, pingscores: &Mutex>, ) { - fn update_scoretable> + DerefMut> - ( + 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 - ( + let push_out = std::mem::replace( &mut scoretable[index_to_insert_at], - Entry - { + Entry { score, person: name.to_string(), }, @@ -202,8 +193,7 @@ async fn handle_hiscores else if scoretable.len() < MAX_LEADERBOARD { println!("New {score_name} {score} by {name}"); - scoretable.push - (Entry { + scoretable.push(Entry { score, person: name.to_string(), }); @@ -237,8 +227,7 @@ async fn handle_hiscores LeaderboardUpdateType::Reset { hiscore_pingscore } => { // Hiscore - update_scoretable - ( + update_scoretable( "hiscore", hiscores.lock().await, &name, @@ -261,8 +250,7 @@ async fn handle_hiscores LeaderboardUpdateType::Increment { loscore } => { - update_scoretable - ( + update_scoretable( "loscore", loscores.lock().await, &name, @@ -275,27 +263,16 @@ async fn handle_hiscores } } -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>, @@ -306,82 +283,57 @@ async fn handle_leaderboard { Some(Ok(Message::Text(selection))) => { - let msg; - match selection.as_str() + let msg = match selection.as_str() { - "0" => // all the leaderboards - { - 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() }, - } + // all the leaderboards + "0" => json! + ({ + "hiscores": &*hiscores.lock().await, + "loscores": &*loscores.lock().await, + "pingscores": &*pingscores.lock().await + }) + .to_string(), + // just the hiscores table + "1" => json! ({ "hiscores": &*hiscores.lock().await }).to_string(), + // just the loscores table + "2" => json! ({ "loscores": &*hiscores.lock().await }).to_string(), + // just the pingscores table + "3" => json! ({ "pingscores": &*hiscores.lock().await }).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::Sender) { 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"), }; @@ -401,11 +353,9 @@ async fn handle_socket { // reset let _ = tx - .send(LeaderboardUpdate - { + .send(LeaderboardUpdate { name: name.clone(), - update: LeaderboardUpdateType::Reset - { + update: LeaderboardUpdateType::Reset { hiscore_pingscore: value, }, }) @@ -419,8 +369,7 @@ async fn handle_socket if prev == 0 { let _ = tx - .send - (LeaderboardUpdate { + .send(LeaderboardUpdate { name: name.clone(), update: LeaderboardUpdateType::Increment { loscore: resets }, }) @@ -437,19 +386,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" + } } -- 2.54.0 From 4614125fffa9fba6890bf6f92d2494547f67df20 Mon Sep 17 00:00:00 2001 From: ErrorNoInternet Date: Mon, 1 Jun 2026 21:49:28 -0400 Subject: [PATCH 2/2] treewide: add basic optimizations --- Cargo.lock | 39 ---------- Cargo.toml | 1 - src/main.rs | 210 +++++++++++++++++++++++++++------------------------- 3 files changed, 110 insertions(+), 140 deletions(-) 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/src/main.rs b/src/main.rs index 8da2841..3620022 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,7 +2,6 @@ use std::{ collections::HashMap, fs, - io::Write, ops::{Deref, DerefMut}, sync::Arc, }; @@ -18,11 +17,11 @@ use axum::{ }; use futures::StreamExt as _; use rand::random_bool; -use regex::Regex; use serde::{Deserialize, Serialize, de}; use serde_json::json; use tokio::{ - sync::{Mutex, mpsc}, + io::AsyncWriteExt as _, + sync::{RwLock, mpsc}, time::{Duration, sleep}, }; use tower_http::services::ServeDir; @@ -37,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 @@ -69,14 +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>>(file_path: &str) - -> anyhow::Result>> + fn read_file de::Deserialize<'de>>( + file_path: &str, + ) -> 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 @@ -90,13 +102,13 @@ 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()); @@ -112,18 +124,12 @@ async fn main() -> anyhow::Result<()> 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); } }); } @@ -150,13 +156,13 @@ async fn main() -> anyhow::Result<()> } // receiver: 0 for hiscore, 1 for loscore, 2 for pingscore async fn handle_hiscores( - mut rx: mpsc::Receiver, - hiscores: &Mutex>, - loscores: &Mutex>, - pingscores: &Mutex>, + 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, @@ -164,59 +170,59 @@ async fn handle_hiscores( file_path: &str, ) -> 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 { @@ -229,15 +235,16 @@ async fn handle_hiscores( // Hiscore 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 { @@ -252,11 +259,12 @@ async fn handle_hiscores( { update_scoretable( "loscore", - loscores.lock().await, + loscores.write().await, &name, loscore, PATH_LOSCORES, ) + .await .expect("failed to update loscores"); } } @@ -274,9 +282,9 @@ async fn leaderboard_handler( } async fn handle_leaderboard( mut socket: WebSocket, - hiscores: &Mutex>, - loscores: &Mutex>, - pingscores: &Mutex>, + hiscores: &RwLock>, + loscores: &RwLock>, + pingscores: &RwLock>, ) { match socket.next().await @@ -286,19 +294,25 @@ async fn handle_leaderboard( let msg = match selection.as_str() { // all the leaderboards - "0" => json! - ({ - "hiscores": &*hiscores.lock().await, - "loscores": &*loscores.lock().await, - "pingscores": &*pingscores.lock().await - }) - .to_string(), + "0" => + { + 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.lock().await }).to_string(), + "1" => json! ({ "hiscores": hiscores.read().await.clone() }).to_string(), // just the loscores table - "2" => json! ({ "loscores": &*hiscores.lock().await }).to_string(), + "2" => json! ({ "loscores": hiscores.read().await.clone() }).to_string(), // just the pingscores table - "3" => json! ({ "pingscores": &*hiscores.lock().await }).to_string(), + "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; @@ -321,7 +335,7 @@ async fn ws_handler(ws: WebSocketUpgrade, State(state): State) -> impl }) } -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; @@ -352,14 +366,12 @@ async fn handle_socket(mut socket: WebSocket, tx: &mpsc::Sender