From d82127c5fb4e5156ea486feb21e6e700cfae1eab Mon Sep 17 00:00:00 2001 From: ErrorNoInternet Date: Mon, 1 Jun 2026 21:49:28 -0400 Subject: [PATCH] treewide: add basic optimizations --- Cargo.lock | 39 --------- Cargo.toml | 1 - src/main.rs | 223 ++++++++++++++++++++++++++++------------------------ 3 files changed, 120 insertions(+), 143 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 9bad49d..92c06c7 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 &str } // Allow only letters, numbers, _ and - - let re = Regex::new(r"^[a-zA-Z0-9_-]+$").unwrap(); - - if re.is_match(input) { input } else { "anon" } + if input + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-') + { + input + } + else + { + "anon" + } }