treewide: set up formatting

This commit is contained in:
2026-06-01 20:53:20 -04:00
parent 0e4d5d7686
commit 36b0c0343d
2 changed files with 79 additions and 129 deletions
+2
View File
@@ -1 +1,3 @@
brace_style = "AlwaysNextLine"
control_brace_style = "AlwaysNextLine"
hard_tabs = true hard_tabs = true
+77 -129
View File
@@ -1,6 +1,5 @@
// TODO rename pingscores userscores // TODO rename pingscores userscores
use std:: use std::{
{
collections::HashMap, collections::HashMap,
fs, fs,
io::Write, io::Write,
@@ -8,28 +7,25 @@ use std::
sync::Arc, sync::Arc,
}; };
use axum:: use axum::{
{
Router, Router,
extract:: extract::{
{
State, State,
ws::{Message, WebSocket, WebSocketUpgrade}, ws::{Message, WebSocket, WebSocketUpgrade},
}, },
response::IntoResponse, response::IntoResponse,
routing::get, 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}, sync::{Mutex, mpsc},
time::{Duration, sleep}, time::{Duration, sleep},
}; };
use tower_http::services::ServeDir; 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)] #[derive(Deserialize, Serialize, Debug, Ord, Eq, PartialEq, PartialOrd, Clone)]
struct Entry struct Entry
@@ -55,8 +51,14 @@ struct LeaderboardUpdate
enum LeaderboardUpdateType enum LeaderboardUpdateType
{ {
Reset { hiscore_pingscore: u32 }, Reset
Increment { loscore: u32 }, {
hiscore_pingscore: u32
},
Increment
{
loscore: u32
},
} }
const CHANCE: f64 = 1.0 / 3.0; const CHANCE: f64 = 1.0 / 3.0;
@@ -70,11 +72,8 @@ const MAX_LEADERBOARD: usize = 20;
#[tokio::main] #[tokio::main]
async fn main() -> anyhow::Result<()> async fn main() -> anyhow::Result<()>
{ {
fn read_file<T: for<'de> de::Deserialize<'de>> fn read_file<T: for<'de> de::Deserialize<'de>>(file_path: &str)
( -> anyhow::Result<Arc<Mutex<T>>>
file_path: &str,
)
-> anyhow::Result<Arc<Mutex<T>>>
{ {
let file_contents: String = fs::read_to_string(file_path)?; let file_contents: String = fs::read_to_string(file_path)?;
Ok(Arc::new(Mutex::new(serde_json::from_str(&file_contents)?))) Ok(Arc::new(Mutex::new(serde_json::from_str(&file_contents)?)))
@@ -101,16 +100,14 @@ async fn main() -> anyhow::Result<()>
{ {
let (hiscores, loscores, pingscores) = let (hiscores, loscores, pingscores) =
(hiscores.clone(), loscores.clone(), pingscores.clone()); (hiscores.clone(), loscores.clone(), pingscores.clone());
tokio::spawn tokio::spawn(async move {
(async move {
handle_hiscores(rx, &hiscores, &loscores, &pingscores).await; handle_hiscores(rx, &hiscores, &loscores, &pingscores).await;
}); });
} }
{ {
let pingscores = pingscores.clone(); let pingscores = pingscores.clone();
tokio::spawn tokio::spawn(async move {
(async move {
// write pingscores every 30s // write pingscores every 30s
loop loop
{ {
@@ -136,8 +133,7 @@ async fn main() -> anyhow::Result<()>
.fallback_service(static_files) .fallback_service(static_files)
.route("/ws", get(ws_handler)) .route("/ws", get(ws_handler))
.route("/ws-leaderboard", get(leaderboard_handler)) .route("/ws-leaderboard", get(leaderboard_handler))
.with_state .with_state(AppState {
(AppState {
tx, tx,
hiscores: Arc::clone(&hiscores), hiscores: Arc::clone(&hiscores),
loscores: Arc::clone(&loscores), loscores: Arc::clone(&loscores),
@@ -153,34 +149,29 @@ async fn main() -> anyhow::Result<()>
Ok(()) Ok(())
} }
// receiver: 0 for hiscore, 1 for loscore, 2 for pingscore // receiver: 0 for hiscore, 1 for loscore, 2 for pingscore
async fn handle_hiscores async fn handle_hiscores(
(
mut rx: mpsc::Receiver<LeaderboardUpdate>, mut rx: mpsc::Receiver<LeaderboardUpdate>,
hiscores: &Mutex<Vec<Entry>>, hiscores: &Mutex<Vec<Entry>>,
loscores: &Mutex<Vec<Entry>>, loscores: &Mutex<Vec<Entry>>,
pingscores: &Mutex<HashMap<String, (u64, u32)>>, pingscores: &Mutex<HashMap<String, (u64, u32)>>,
) )
{ {
fn update_scoretable<G: Deref<Target = Vec<Entry>> + DerefMut> fn update_scoretable<G: Deref<Target = Vec<Entry>> + DerefMut>(
(
score_name: &str, score_name: &str,
mut scoretable_lock: G, mut scoretable_lock: G,
name: &str, name: &str,
score: u32, score: u32,
file_path: &str, file_path: &str,
) ) -> anyhow::Result<()>
-> anyhow::Result<()>
{ {
let scoretable = &mut *scoretable_lock; let scoretable = &mut *scoretable_lock;
if let Some(index_to_insert_at) = scoretable.iter().position(|e| score > e.score) if let Some(index_to_insert_at) = scoretable.iter().position(|e| score > e.score)
{ {
println!("New {score_name} {score} by {name}"); println!("New {score_name} {score} by {name}");
scoretable[index_to_insert_at..].rotate_right(1); 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], &mut scoretable[index_to_insert_at],
Entry Entry {
{
score, score,
person: name.to_string(), person: name.to_string(),
}, },
@@ -202,8 +193,7 @@ async fn handle_hiscores
else if scoretable.len() < MAX_LEADERBOARD else if scoretable.len() < MAX_LEADERBOARD
{ {
println!("New {score_name} {score} by {name}"); println!("New {score_name} {score} by {name}");
scoretable.push scoretable.push(Entry {
(Entry {
score, score,
person: name.to_string(), person: name.to_string(),
}); });
@@ -237,8 +227,7 @@ async fn handle_hiscores
LeaderboardUpdateType::Reset { hiscore_pingscore } => LeaderboardUpdateType::Reset { hiscore_pingscore } =>
{ {
// Hiscore // Hiscore
update_scoretable update_scoretable(
(
"hiscore", "hiscore",
hiscores.lock().await, hiscores.lock().await,
&name, &name,
@@ -261,8 +250,7 @@ async fn handle_hiscores
LeaderboardUpdateType::Increment { loscore } => LeaderboardUpdateType::Increment { loscore } =>
{ {
update_scoretable update_scoretable(
(
"loscore", "loscore",
loscores.lock().await, loscores.lock().await,
&name, &name,
@@ -275,27 +263,16 @@ async fn handle_hiscores
} }
} }
async fn leaderboard_handler async fn leaderboard_handler(
(
ws: WebSocketUpgrade, ws: WebSocketUpgrade,
State(state): State<AppState> State(state): State<AppState>,
) ) -> impl IntoResponse
-> impl IntoResponse
{ {
ws.on_upgrade ws.on_upgrade(|socket| async move {
(|socket| async move { handle_leaderboard(socket, &state.hiscores, &state.loscores, &state.pingscores).await;
handle_leaderboard
(
socket,
&state.hiscores,
&state.loscores,
&state.pingscores,
)
.await;
}) })
} }
async fn handle_leaderboard async fn handle_leaderboard(
(
mut socket: WebSocket, mut socket: WebSocket,
hiscores: &Mutex<Vec<Entry>>, hiscores: &Mutex<Vec<Entry>>,
loscores: &Mutex<Vec<Entry>>, loscores: &Mutex<Vec<Entry>>,
@@ -306,82 +283,57 @@ async fn handle_leaderboard
{ {
Some(Ok(Message::Text(selection))) => Some(Ok(Message::Text(selection))) =>
{ {
let msg; let msg = match selection.as_str()
match selection.as_str()
{ {
"0" => // all the leaderboards // all the leaderboards
{ "0" => json!
msg = ({
{ "hiscores": &*hiscores.lock().await,
json! "loscores": &*loscores.lock().await,
({ "pingscores": &*pingscores.lock().await
"hiscores": &*hiscores.lock().await, })
"loscores": &*loscores.lock().await, .to_string(),
"pingscores": &*pingscores.lock().await // just the hiscores table
}) "1" => json! ({ "hiscores": &*hiscores.lock().await }).to_string(),
.to_string() // just the loscores table
}; "2" => json! ({ "loscores": &*hiscores.lock().await }).to_string(),
}, // just the pingscores table
"1" => // just the hiscores table "3" => json! ({ "pingscores": &*hiscores.lock().await }).to_string(),
{ _ => "Invalid leaderboard selection, please use 0,1,2 or 3".to_string(),
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 _ = socket.send(Message::Text(msg.into())).await; 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 async fn ws_handler(ws: WebSocketUpgrade, State(state): State<AppState>) -> impl IntoResponse
(
ws: WebSocketUpgrade,
State(state): State<AppState>
)
-> impl IntoResponse
{ {
ws.on_upgrade ws.on_upgrade(|socket| async move {
(|socket| async move { handle_socket(socket, &state.tx).await;
handle_socket
(
socket,
&state.tx,
)
.await;
}) })
} }
async fn handle_socket async fn handle_socket(mut socket: WebSocket, tx: &mpsc::Sender<LeaderboardUpdate>)
(
mut socket: WebSocket,
tx: &mpsc::Sender<LeaderboardUpdate>,
)
{ {
let mut value: u32 = 0; let mut value: u32 = 0;
let Some(name) = socket.next().await else let Some(name) = socket.next().await
else
{ {
eprintln!("No username"); eprintln!("No username");
return; return;
}; };
let name: Arc<str> = match name.expect("failed to recv socket msg") let name: Arc<str> = match name.expect("failed to recv socket msg")
{ {
Message::Text(text) => Message::Text(text) => Arc::from(validate_name(&text)),
{
Arc::from(validate_name(&text))
}
_ => Arc::from("anon"), _ => Arc::from("anon"),
}; };
@@ -401,11 +353,9 @@ async fn handle_socket
{ {
// reset // reset
let _ = tx let _ = tx
.send(LeaderboardUpdate .send(LeaderboardUpdate {
{
name: name.clone(), name: name.clone(),
update: LeaderboardUpdateType::Reset update: LeaderboardUpdateType::Reset {
{
hiscore_pingscore: value, hiscore_pingscore: value,
}, },
}) })
@@ -419,8 +369,7 @@ async fn handle_socket
if prev == 0 if prev == 0
{ {
let _ = tx let _ = tx
.send .send(LeaderboardUpdate {
(LeaderboardUpdate {
name: name.clone(), name: name.clone(),
update: LeaderboardUpdateType::Increment { loscore: resets }, update: LeaderboardUpdateType::Increment { loscore: resets },
}) })
@@ -437,28 +386,27 @@ async fn handle_socket
break; break;
} }
_ => {} _ =>
{}
} }
} }
} }
fn validate_name(input: &str) -> &str { fn validate_name(input: &str) -> &str
{
let input = input.trim(); let input = input.trim();
if input == "null" if input == "null"
{ {
return "anon"; return "anon";
} }
// Length check // Length check
if input.is_empty() || input.len() > 32 { if input.is_empty() || input.len() > 32
{
return "anon"; return "anon";
} }
// Allow only letters, numbers, _ and - // Allow only letters, numbers, _ and -
let re = Regex::new(r"^[a-zA-Z0-9_-]+$").unwrap(); let re = Regex::new(r"^[a-zA-Z0-9_-]+$").unwrap();
if re.is_match(input) { if re.is_match(input) { input } else { "anon" }
input
} else {
"anon"
}
} }