Replace repeated Mutex lock functions with a macro

This commit is contained in:
Ethan O'Brien 2024-11-02 12:09:35 -05:00
parent d9ce65df42
commit 7aaf22c923
6 changed files with 110 additions and 167 deletions

View file

@ -142,6 +142,7 @@ pub fn get_data_path(file_name: &str) -> String {
format!("{}/{}", path, file_name) format!("{}/{}", path, file_name)
} }
// include_file macro: includes a file compressed at compile time, and decompresses it on reference. Decreases binary size
#[macro_export] #[macro_export]
macro_rules! include_file { macro_rules! include_file {
( $s:expr ) => { ( $s:expr ) => {
@ -152,6 +153,7 @@ macro_rules! include_file {
} }
}; };
} }
pub fn decode(bytes: &[u8]) -> Vec<u8> { pub fn decode(bytes: &[u8]) -> Vec<u8> {
use std::io::{Cursor, Read}; use std::io::{Cursor, Read};
@ -161,32 +163,32 @@ pub fn decode(bytes: &[u8]) -> Vec<u8> {
ret ret
} }
#[macro_export]
macro_rules! lock_onto_mutex {
($mutex:expr) => {{
loop {
match $mutex.lock() {
Ok(value) => {
break value;
}
Err(_) => {
actix_web::rt::time::sleep(std::time::Duration::from_millis(15)).await;
}
}
}
}};
}
lazy_static! { lazy_static! {
static ref RUNNING: Mutex<bool> = Mutex::new(false); static ref RUNNING: Mutex<bool> = Mutex::new(false);
} }
async fn set_running(running: bool) { async fn set_running(running: bool) {
loop { let mut result = lock_onto_mutex!(RUNNING);
match RUNNING.lock() { *result = running;
Ok(mut result) => {
*result = running;
return;
}
Err(_) => {
actix_web::rt::time::sleep(Duration::from_millis(15)).await;
}
}
}
} }
async fn get_running() -> bool { async fn get_running() -> bool {
loop { let result = lock_onto_mutex!(RUNNING);
match RUNNING.lock() { return *result;
Ok(result) => {
return *result;
}
Err(_) => {
actix_web::rt::time::sleep(Duration::from_millis(15)).await;
}
}
}
} }

View file

@ -93,7 +93,7 @@ async fn api_req(req: HttpRequest, body: String) -> HttpResponse {
"/api/event" => event::event(req, body), "/api/event" => event::event(req, body),
"/api/event/star_event" => event::star_event(req, body), "/api/event/star_event" => event::star_event(req, body),
"/api/event/set/member" => event::set_member(req, body), "/api/event/set/member" => event::set_member(req, body),
"/api/event/ranking" => event::ranking(req, body), "/api/event/ranking" => event::ranking(req, body).await,
"/api/event_star_live/change_target_music" => event::change_target_music(req, body), "/api/event_star_live/change_target_music" => event::change_target_music(req, body),
"/api/event_star_live/start" => live::event_start(req, body), "/api/event_star_live/start" => live::event_start(req, body),
"/api/event_star_live/end" => event::event_end(req, body), "/api/event_star_live/end" => event::event_end(req, body),
@ -135,7 +135,7 @@ async fn api_req(req: HttpRequest, body: String) -> HttpResponse {
"/api/gift" => home::gift_get(req), "/api/gift" => home::gift_get(req),
"/api/purchase" => purchase::purchase(req), "/api/purchase" => purchase::purchase(req),
"/api/friend/ids" => friend::ids(req), "/api/friend/ids" => friend::ids(req),
"/api/live/clearRate" => clear_rate::clearrate(req), "/api/live/clearRate" => clear_rate::clearrate(req).await,
"/api/mission" => mission::mission(req), "/api/mission" => mission::mission(req),
"/api/home" => home::home(req), "/api/home" => home::home(req),
"/api/home/preset" => home::preset_get(req), "/api/home/preset" => home::preset_get(req),

View file

@ -2,7 +2,6 @@ use json::{object, array, JsonValue};
use actix_web::{HttpRequest}; use actix_web::{HttpRequest};
use rusqlite::params; use rusqlite::params;
use std::sync::Mutex; use std::sync::Mutex;
use std::thread;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use crate::encryption; use crate::encryption;
@ -167,42 +166,23 @@ fn get_json() -> JsonValue {
} }
} }
fn get_clearrate_json() -> JsonValue { async fn get_clearrate_json() -> JsonValue {
loop { let mut result = crate::lock_onto_mutex!(CACHED_DATA);
match CACHED_DATA.lock() { if result.is_none() {
Ok(mut result) => { result.replace(get_json());
if result.is_none() {
result.replace(get_json());
}
let cache = result.as_ref().unwrap();
let rv = cache["cache"].clone();
if cache["last_updated"].as_u64().unwrap() + (60 * 60) < global::timestamp() {
thread::spawn(|| {
loop {
match CACHED_DATA.lock() {
Ok(mut result) => {
let new = get_json();
result.replace(new.clone());
break;
}
Err(_) => {
std::thread::sleep(std::time::Duration::from_millis(15));
}
}
}
});
}
return rv;
}
Err(_) => {
std::thread::sleep(std::time::Duration::from_millis(15));
}
}
} }
let cache = result.as_ref().unwrap();
let rv = cache["cache"].clone();
if cache["last_updated"].as_u64().unwrap() + (60 * 60) < global::timestamp() {
let mut result = crate::lock_onto_mutex!(CACHED_DATA);
let new = get_json();
result.replace(new.clone());
}
return rv;
} }
pub fn clearrate(_req: HttpRequest) -> Option<JsonValue> { pub async fn clearrate(_req: HttpRequest) -> Option<JsonValue> {
Some(get_clearrate_json()) Some(get_clearrate_json().await)
} }
pub fn ranking(_req: HttpRequest, body: String) -> Option<JsonValue> { pub fn ranking(_req: HttpRequest, body: String) -> Option<JsonValue> {

View file

@ -219,10 +219,10 @@ fn get_rank(event: u32, user_id: u64) -> u32 {
0 0
} }
pub fn ranking(_req: HttpRequest, body: String) -> Option<JsonValue> { pub async fn ranking(_req: HttpRequest, body: String) -> Option<JsonValue> {
let body = &encryption::decrypt_packet(&body).unwrap(); let body = &encryption::decrypt_packet(&body).unwrap();
let body: EventRankingGet = serde_json::from_str(body).unwrap(); let body: EventRankingGet = serde_json::from_str(body).unwrap();
let scores = crate::router::event_ranking::get_scores_json()[body.master_event_id.to_string()].clone(); let scores = crate::router::event_ranking::get_scores_json().await[body.master_event_id.to_string()].clone();
let mut rv = array![]; let mut rv = array![];
let mut i=1; let mut i=1;
let start = if body.user_id == 0 { body.start_rank } else { get_rank(body.master_event_id, body.user_id) }; let start = if body.user_id == 0 { body.start_rank } else { get_rank(body.master_event_id, body.user_id) };

View file

@ -1,7 +1,6 @@
use json::{object, array, JsonValue}; use json::{object, array, JsonValue};
use rusqlite::params; use rusqlite::params;
use std::sync::Mutex; use std::sync::Mutex;
use std::thread;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use crate::sql::SQLite; use crate::sql::SQLite;
@ -98,36 +97,17 @@ fn get_json() -> JsonValue {
} }
} }
pub fn get_scores_json() -> JsonValue { pub async fn get_scores_json() -> JsonValue {
loop { let mut result = crate::lock_onto_mutex!(CACHED_DATA);
match CACHED_DATA.lock() { if result.is_none() {
Ok(mut result) => { result.replace(get_json());
if result.is_none() {
result.replace(get_json());
}
let cache = result.as_ref().unwrap();
let rv = cache["cache"].clone();
if cache["last_updated"].as_u64().unwrap() + (60 * 60) < global::timestamp() {
thread::spawn(|| {
loop {
match CACHED_DATA.lock() {
Ok(mut result) => {
let new = get_json();
result.replace(new.clone());
break;
}
Err(_) => {
std::thread::sleep(std::time::Duration::from_millis(15));
}
}
}
});
}
return rv;
}
Err(_) => {
std::thread::sleep(std::time::Duration::from_millis(15));
}
}
} }
let cache = result.as_ref().unwrap();
let rv = cache["cache"].clone();
if cache["last_updated"].as_u64().unwrap() + (60 * 60) < global::timestamp() {
let mut result = crate::lock_onto_mutex!(CACHED_DATA);
let new = get_json();
result.replace(new.clone());
}
return rv;
} }

View file

@ -5,8 +5,23 @@ use json::{JsonValue, array};
use crate::router::clear_rate::Live; use crate::router::clear_rate::Live;
pub struct SQLite { pub struct SQLite {
engine: Mutex<Connection>, engine: Mutex<Connection>
sleep_duration: u64 }
// This is duplicated, for ease of people wanting to use this file in their project
macro_rules! lock_onto_mutex {
($mutex:expr) => {{
loop {
match $mutex.lock() {
Ok(value) => {
break value;
}
Err(_) => {
std::thread::sleep(std::time::Duration::from_millis(10));
}
}
}
}};
} }
impl SQLite { impl SQLite {
@ -14,94 +29,60 @@ impl SQLite {
let conn = Connection::open(crate::get_data_path(path)).unwrap(); let conn = Connection::open(crate::get_data_path(path)).unwrap();
conn.execute("PRAGMA foreign_keys = ON;", ()).unwrap(); conn.execute("PRAGMA foreign_keys = ON;", ()).unwrap();
let instance = SQLite { let instance = SQLite {
engine: Mutex::new(conn), engine: Mutex::new(conn)
sleep_duration: 10
}; };
setup(&instance); setup(&instance);
instance instance
} }
pub fn lock_and_exec(&self, command: &str, args: &[&dyn ToSql]) { pub fn lock_and_exec(&self, command: &str, args: &[&dyn ToSql]) {
loop { let conn = lock_onto_mutex!(self.engine);
match self.engine.lock() { conn.execute(command, args).unwrap();
Ok(conn) => {
conn.execute(command, args).unwrap();
return;
}
Err(_) => {
std::thread::sleep(std::time::Duration::from_millis(self.sleep_duration));
}
}
}
} }
pub fn lock_and_select(&self, command: &str, args: &[&dyn ToSql]) -> Result<String, rusqlite::Error> { pub fn lock_and_select(&self, command: &str, args: &[&dyn ToSql]) -> Result<String, rusqlite::Error> {
loop { let conn = lock_onto_mutex!(self.engine);
match self.engine.lock() { let mut stmt = conn.prepare(command)?;
Ok(conn) => { return stmt.query_row(args, |row| {
let mut stmt = conn.prepare(command)?; match row.get::<usize, i64>(0) {
return stmt.query_row(args, |row| { Ok(val) => Ok(val.to_string()),
match row.get::<usize, i64>(0) { Err(_) => row.get(0)
Ok(val) => Ok(val.to_string()),
Err(_) => row.get(0)
}
});
}
Err(_) => {
std::thread::sleep(std::time::Duration::from_millis(self.sleep_duration));
}
} }
} });
} }
pub fn lock_and_select_all(&self, command: &str, args: &[&dyn ToSql]) -> Result<JsonValue, rusqlite::Error> { pub fn lock_and_select_all(&self, command: &str, args: &[&dyn ToSql]) -> Result<JsonValue, rusqlite::Error> {
loop { let conn = lock_onto_mutex!(self.engine);
match self.engine.lock() { let mut stmt = conn.prepare(command)?;
Ok(conn) => { let map = stmt.query_map(args, |row| {
let mut stmt = conn.prepare(command)?; match row.get::<usize, i64>(0) {
let map = stmt.query_map(args, |row| { Ok(val) => Ok(val.to_string()),
match row.get::<usize, i64>(0) { Err(_) => row.get(0)
Ok(val) => Ok(val.to_string()),
Err(_) => row.get(0)
}
})?;
let mut rv = array![];
for val in map {
let res = val?;
match res.clone().parse::<i64>() {
Ok(v) => rv.push(v).unwrap(),
Err(_) => rv.push(res).unwrap()
};
}
return Ok(rv);
}
Err(_) => {
std::thread::sleep(std::time::Duration::from_millis(self.sleep_duration));
}
} }
})?;
let mut rv = array![];
for val in map {
let res = val?;
match res.clone().parse::<i64>() {
Ok(v) => rv.push(v).unwrap(),
Err(_) => rv.push(res).unwrap()
};
} }
return Ok(rv);
} }
pub fn get_live_data(&self, id: i64) -> Result<Live, rusqlite::Error> { pub fn get_live_data(&self, id: i64) -> Result<Live, rusqlite::Error> {
loop { let conn = lock_onto_mutex!(self.engine);
match self.engine.lock() { let mut stmt = conn.prepare("SELECT * FROM lives WHERE live_id=?1")?;
Ok(conn) => { return stmt.query_row(params!(id), |row| {
let mut stmt = conn.prepare("SELECT * FROM lives WHERE live_id=?1")?; Ok(Live {
return stmt.query_row(params!(id), |row| { live_id: row.get(0)?,
Ok(Live { normal_failed: row.get(1)?,
live_id: row.get(0)?, normal_pass: row.get(2)?,
normal_failed: row.get(1)?, hard_failed: row.get(3)?,
normal_pass: row.get(2)?, hard_pass: row.get(4)?,
hard_failed: row.get(3)?, expert_failed: row.get(5)?,
hard_pass: row.get(4)?, expert_pass: row.get(6)?,
expert_failed: row.get(5)?, master_failed: row.get(7)?,
expert_pass: row.get(6)?, master_pass: row.get(8)?,
master_failed: row.get(7)?, })
master_pass: row.get(8)?, });
})
});
}
Err(_) => {
std::thread::sleep(std::time::Duration::from_millis(self.sleep_duration));
}
}
}
} }
pub fn create_store_v2(&self, table: &str) { pub fn create_store_v2(&self, table: &str) {
self.lock_and_exec(table, params!()); self.lock_and_exec(table, params!());