forked from deadvey/button
treewide: add basic optimizations
This commit is contained in:
Generated
-39
@@ -2,15 +2,6 @@
|
|||||||
# It is not intended for manual editing.
|
# It is not intended for manual editing.
|
||||||
version = 4
|
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]]
|
[[package]]
|
||||||
name = "anyhow"
|
name = "anyhow"
|
||||||
version = "1.0.102"
|
version = "1.0.102"
|
||||||
@@ -107,7 +98,6 @@ dependencies = [
|
|||||||
"axum",
|
"axum",
|
||||||
"futures",
|
"futures",
|
||||||
"rand 0.10.1",
|
"rand 0.10.1",
|
||||||
"regex",
|
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"tokio",
|
"tokio",
|
||||||
@@ -678,35 +668,6 @@ dependencies = [
|
|||||||
"bitflags",
|
"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]]
|
[[package]]
|
||||||
name = "ryu"
|
name = "ryu"
|
||||||
version = "1.0.23"
|
version = "1.0.23"
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ anyhow = "1.0.102"
|
|||||||
axum = { version = "0.8.9", features = ["ws"] }
|
axum = { version = "0.8.9", features = ["ws"] }
|
||||||
futures = "0.3.32"
|
futures = "0.3.32"
|
||||||
rand = "0.10.1"
|
rand = "0.10.1"
|
||||||
regex = "1.12.3"
|
|
||||||
serde = { version = "1.0.228", features = ["derive"] }
|
serde = { version = "1.0.228", features = ["derive"] }
|
||||||
serde_json = "1.0.149"
|
serde_json = "1.0.149"
|
||||||
tokio = { version = "1.52.3", features = ["full"] }
|
tokio = { version = "1.52.3", features = ["full"] }
|
||||||
|
|||||||
+120
-103
@@ -2,7 +2,6 @@
|
|||||||
use std::{
|
use std::{
|
||||||
collections::HashMap,
|
collections::HashMap,
|
||||||
fs,
|
fs,
|
||||||
io::Write,
|
|
||||||
ops::{Deref, DerefMut},
|
ops::{Deref, DerefMut},
|
||||||
sync::Arc,
|
sync::Arc,
|
||||||
};
|
};
|
||||||
@@ -18,11 +17,11 @@ use axum::{
|
|||||||
};
|
};
|
||||||
use futures::StreamExt as _;
|
use futures::StreamExt as _;
|
||||||
use rand::random_bool;
|
use rand::random_bool;
|
||||||
use regex::Regex;
|
|
||||||
use serde::{Deserialize, Serialize, de};
|
use serde::{Deserialize, Serialize, de};
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
use tokio::{
|
use tokio::{
|
||||||
sync::{Mutex, mpsc},
|
io::AsyncWriteExt as _,
|
||||||
|
sync::{RwLock, mpsc},
|
||||||
time::{Duration, sleep},
|
time::{Duration, sleep},
|
||||||
};
|
};
|
||||||
use tower_http::services::ServeDir;
|
use tower_http::services::ServeDir;
|
||||||
@@ -37,10 +36,10 @@ struct Entry
|
|||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
struct AppState
|
struct AppState
|
||||||
{
|
{
|
||||||
tx: mpsc::Sender<LeaderboardUpdate>,
|
tx: mpsc::UnboundedSender<LeaderboardUpdate>,
|
||||||
hiscores: Arc<Mutex<Vec<Entry>>>,
|
hiscores: Arc<RwLock<Vec<Entry>>>,
|
||||||
loscores: Arc<Mutex<Vec<Entry>>>,
|
loscores: Arc<RwLock<Vec<Entry>>>,
|
||||||
pingscores: Arc<Mutex<HashMap<String, (u64, u32)>>>, // u64 is reset count and u32 is PB
|
pingscores: Arc<RwLock<HashMap<String, (u64, u32)>>>, // u64 is reset count and u32 is PB
|
||||||
}
|
}
|
||||||
|
|
||||||
struct LeaderboardUpdate
|
struct LeaderboardUpdate
|
||||||
@@ -69,14 +68,27 @@ const PATH_PINGSCORES: &str = "pingscores.json";
|
|||||||
|
|
||||||
const MAX_LEADERBOARD: usize = 20;
|
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]
|
#[tokio::main]
|
||||||
async fn main() -> anyhow::Result<()>
|
async fn main() -> anyhow::Result<()>
|
||||||
{
|
{
|
||||||
fn read_file<T: for<'de> de::Deserialize<'de>>(file_path: &str)
|
fn read_file<T: for<'de> de::Deserialize<'de>>(
|
||||||
-> anyhow::Result<Arc<Mutex<T>>>
|
file_path: &str,
|
||||||
|
) -> anyhow::Result<Arc<RwLock<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(RwLock::new(serde_json::from_str(&file_contents)?)))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Makes the vector at `vec` one with a capacity of exactly [`MAX_LEADERBOARD`] if `vec` is
|
/// 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<Mutex<Vec<Entry>>> = read_file(PATH_HISCORES)?;
|
let hiscores: Arc<RwLock<Vec<Entry>>> = read_file(PATH_HISCORES)?;
|
||||||
exact_leaderboard(hiscores.lock().await);
|
exact_leaderboard(hiscores.write().await);
|
||||||
let loscores: Arc<Mutex<Vec<Entry>>> = read_file(PATH_LOSCORES)?;
|
let loscores: Arc<RwLock<Vec<Entry>>> = read_file(PATH_LOSCORES)?;
|
||||||
exact_leaderboard(loscores.lock().await);
|
exact_leaderboard(loscores.write().await);
|
||||||
let pingscores: Arc<Mutex<HashMap<String, (u64, u32)>>> = read_file(PATH_PINGSCORES)?;
|
let pingscores: Arc<RwLock<HashMap<String, (u64, u32)>>> = read_file(PATH_PINGSCORES)?;
|
||||||
|
|
||||||
let (tx, rx) = mpsc::channel::<LeaderboardUpdate>(1024);
|
let (tx, rx) = mpsc::unbounded_channel::<LeaderboardUpdate>();
|
||||||
{
|
{
|
||||||
let (hiscores, loscores, pingscores) =
|
let (hiscores, loscores, pingscores) =
|
||||||
(hiscores.clone(), loscores.clone(), pingscores.clone());
|
(hiscores.clone(), loscores.clone(), pingscores.clone());
|
||||||
@@ -112,18 +124,12 @@ async fn main() -> anyhow::Result<()>
|
|||||||
loop
|
loop
|
||||||
{
|
{
|
||||||
sleep(Duration::from_secs(30)).await;
|
sleep(Duration::from_secs(30)).await;
|
||||||
let pingscores = pingscores.lock().await;
|
let pingscores = pingscores.read().await.clone();
|
||||||
let file_contents: String = serde_json::to_string(&pingscores.clone())
|
let file_contents: String =
|
||||||
.expect("failed to serialize pingscores");
|
serde_json::to_string(&pingscores).expect("failed to serialize pingscores");
|
||||||
drop(pingscores);
|
write_file(PATH_PINGSCORES, &file_contents)
|
||||||
let mut file = fs::OpenOptions::new()
|
.await
|
||||||
.write(true)
|
|
||||||
.truncate(true)
|
|
||||||
.open(PATH_PINGSCORES)
|
|
||||||
.expect("failed to open pingscores file");
|
|
||||||
file.write_all(file_contents.as_bytes())
|
|
||||||
.expect("failed to write pingscores");
|
.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
|
// 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::UnboundedReceiver<LeaderboardUpdate>,
|
||||||
hiscores: &Mutex<Vec<Entry>>,
|
hiscores: &RwLock<Vec<Entry>>,
|
||||||
loscores: &Mutex<Vec<Entry>>,
|
loscores: &RwLock<Vec<Entry>>,
|
||||||
pingscores: &Mutex<HashMap<String, (u64, u32)>>,
|
pingscores: &RwLock<HashMap<String, (u64, u32)>>,
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
fn update_scoretable<G: Deref<Target = Vec<Entry>> + DerefMut>(
|
async 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,
|
||||||
@@ -164,59 +170,59 @@ async fn handle_hiscores(
|
|||||||
file_path: &str,
|
file_path: &str,
|
||||||
) -> anyhow::Result<()>
|
) -> anyhow::Result<()>
|
||||||
{
|
{
|
||||||
let scoretable = &mut *scoretable_lock;
|
let file_contents = {
|
||||||
if let Some(index_to_insert_at) = scoretable.iter().position(|e| score > e.score)
|
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);
|
println!("New {score_name} {score} by {name}");
|
||||||
let push_out = std::mem::replace(
|
scoretable[index_to_insert_at..].rotate_right(1);
|
||||||
&mut scoretable[index_to_insert_at],
|
let push_out = std::mem::replace(
|
||||||
Entry {
|
&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,
|
score,
|
||||||
person: name.to_string(),
|
person: name.to_string(),
|
||||||
},
|
});
|
||||||
);
|
None
|
||||||
if scoretable.len() < MAX_LEADERBOARD
|
|
||||||
{
|
|
||||||
scoretable.push(push_out);
|
|
||||||
}
|
}
|
||||||
|
else
|
||||||
let file_contents: String = serde_json::to_string(&*scoretable_lock)?;
|
{
|
||||||
drop(scoretable_lock);
|
None
|
||||||
let mut file = fs::OpenOptions::new()
|
}
|
||||||
.write(true)
|
};
|
||||||
.truncate(true)
|
drop(scoretable_lock);
|
||||||
.open(file_path)?;
|
if let Some(file_contents) = file_contents
|
||||||
file.write_all(file_contents.as_bytes())?;
|
|
||||||
file.flush()?;
|
|
||||||
}
|
|
||||||
else if scoretable.len() < MAX_LEADERBOARD
|
|
||||||
{
|
{
|
||||||
println!("New {score_name} {score} by {name}");
|
write_file(file_path, &file_contents).await?;
|
||||||
scoretable.push(Entry {
|
|
||||||
score,
|
|
||||||
person: name.to_string(),
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
// Panic galore
|
// Panic galore
|
||||||
let mut hiscores_lock = hiscores.lock().await;
|
let mut hiscores_lock = hiscores.write().await;
|
||||||
hiscores_lock.sort();
|
hiscores_lock.sort();
|
||||||
hiscores_lock.reverse();
|
hiscores_lock.reverse();
|
||||||
let file_contents: String =
|
let file_contents: String =
|
||||||
serde_json::to_string(&hiscores_lock.clone()).expect("failed to serialize hiscores");
|
serde_json::to_string(&hiscores_lock.clone()).expect("failed to serialize hiscores");
|
||||||
drop(hiscores_lock);
|
drop(hiscores_lock);
|
||||||
let mut file = fs::OpenOptions::new()
|
write_file(PATH_HISCORES, &file_contents)
|
||||||
.write(true)
|
.await
|
||||||
.truncate(true)
|
|
||||||
.open(PATH_HISCORES)
|
|
||||||
.expect("failed to open hiscores");
|
|
||||||
file.write_all(file_contents.as_bytes())
|
|
||||||
.expect("failed to write hiscores");
|
.expect("failed to write hiscores");
|
||||||
drop(file);
|
|
||||||
|
|
||||||
loop
|
loop
|
||||||
{
|
{
|
||||||
@@ -229,15 +235,16 @@ async fn handle_hiscores(
|
|||||||
// Hiscore
|
// Hiscore
|
||||||
update_scoretable(
|
update_scoretable(
|
||||||
"hiscore",
|
"hiscore",
|
||||||
hiscores.lock().await,
|
hiscores.write().await,
|
||||||
&name,
|
&name,
|
||||||
hiscore_pingscore,
|
hiscore_pingscore,
|
||||||
PATH_HISCORES,
|
PATH_HISCORES,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.expect("failed to update hiscores");
|
.expect("failed to update hiscores");
|
||||||
|
|
||||||
// Pingscore
|
// Pingscore
|
||||||
let mut pingscores = pingscores.lock().await;
|
let mut pingscores = pingscores.write().await;
|
||||||
// pb
|
// pb
|
||||||
if hiscore_pingscore > pingscores.get(&*name).unwrap_or(&(0, 0)).1
|
if hiscore_pingscore > pingscores.get(&*name).unwrap_or(&(0, 0)).1
|
||||||
{
|
{
|
||||||
@@ -252,11 +259,12 @@ async fn handle_hiscores(
|
|||||||
{
|
{
|
||||||
update_scoretable(
|
update_scoretable(
|
||||||
"loscore",
|
"loscore",
|
||||||
loscores.lock().await,
|
loscores.write().await,
|
||||||
&name,
|
&name,
|
||||||
loscore,
|
loscore,
|
||||||
PATH_LOSCORES,
|
PATH_LOSCORES,
|
||||||
)
|
)
|
||||||
|
.await
|
||||||
.expect("failed to update loscores");
|
.expect("failed to update loscores");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -274,9 +282,9 @@ async fn leaderboard_handler(
|
|||||||
}
|
}
|
||||||
async fn handle_leaderboard(
|
async fn handle_leaderboard(
|
||||||
mut socket: WebSocket,
|
mut socket: WebSocket,
|
||||||
hiscores: &Mutex<Vec<Entry>>,
|
hiscores: &RwLock<Vec<Entry>>,
|
||||||
loscores: &Mutex<Vec<Entry>>,
|
loscores: &RwLock<Vec<Entry>>,
|
||||||
pingscores: &Mutex<HashMap<String, (u64, u32)>>,
|
pingscores: &RwLock<HashMap<String, (u64, u32)>>,
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
match socket.next().await
|
match socket.next().await
|
||||||
@@ -286,19 +294,25 @@ async fn handle_leaderboard(
|
|||||||
let msg = match selection.as_str()
|
let msg = match selection.as_str()
|
||||||
{
|
{
|
||||||
// all the leaderboards
|
// all the leaderboards
|
||||||
"0" => json!
|
"0" =>
|
||||||
({
|
{
|
||||||
"hiscores": &*hiscores.lock().await,
|
let hiscores = hiscores.read().await.clone();
|
||||||
"loscores": &*loscores.lock().await,
|
let loscores = loscores.read().await.clone();
|
||||||
"pingscores": &*pingscores.lock().await
|
let pingscores = pingscores.read().await.clone();
|
||||||
})
|
json!
|
||||||
.to_string(),
|
({
|
||||||
|
"hiscores": hiscores,
|
||||||
|
"loscores": loscores,
|
||||||
|
"pingscores": pingscores
|
||||||
|
})
|
||||||
|
.to_string()
|
||||||
|
}
|
||||||
// just the hiscores table
|
// 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
|
// 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
|
// 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(),
|
_ => "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;
|
||||||
@@ -321,7 +335,7 @@ async fn ws_handler(ws: WebSocketUpgrade, State(state): State<AppState>) -> impl
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handle_socket(mut socket: WebSocket, tx: &mpsc::Sender<LeaderboardUpdate>)
|
async fn handle_socket(mut socket: WebSocket, tx: &mpsc::UnboundedSender<LeaderboardUpdate>)
|
||||||
{
|
{
|
||||||
let mut value: u32 = 0;
|
let mut value: u32 = 0;
|
||||||
|
|
||||||
@@ -352,14 +366,12 @@ async fn handle_socket(mut socket: WebSocket, tx: &mpsc::Sender<LeaderboardUpdat
|
|||||||
if random_bool(CHANCE)
|
if random_bool(CHANCE)
|
||||||
{
|
{
|
||||||
// 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,
|
},
|
||||||
},
|
});
|
||||||
})
|
|
||||||
.await;
|
|
||||||
resets += 1;
|
resets += 1;
|
||||||
value = 0;
|
value = 0;
|
||||||
}
|
}
|
||||||
@@ -368,12 +380,10 @@ async fn handle_socket(mut socket: WebSocket, tx: &mpsc::Sender<LeaderboardUpdat
|
|||||||
value += 1;
|
value += 1;
|
||||||
if prev == 0
|
if prev == 0
|
||||||
{
|
{
|
||||||
let _ = tx
|
let _ = tx.send(LeaderboardUpdate {
|
||||||
.send(LeaderboardUpdate {
|
name: name.clone(),
|
||||||
name: name.clone(),
|
update: LeaderboardUpdateType::Increment { loscore: resets },
|
||||||
update: LeaderboardUpdateType::Increment { loscore: resets },
|
});
|
||||||
})
|
|
||||||
.await;
|
|
||||||
resets = 0;
|
resets = 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -406,7 +416,14 @@ fn validate_name(input: &str) -> &str
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Allow only letters, numbers, _ and -
|
// Allow only letters, numbers, _ and -
|
||||||
let re = Regex::new(r"^[a-zA-Z0-9_-]+$").unwrap();
|
if input
|
||||||
|
.bytes()
|
||||||
if re.is_match(input) { input } else { "anon" }
|
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')
|
||||||
|
{
|
||||||
|
input
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
"anon"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user