Skip to content

Commit

Permalink
refactor: Entire codebase upgrade, extended tests
Browse files Browse the repository at this point in the history
  • Loading branch information
hampfh committed Jul 11, 2024
1 parent e06d78b commit 6ec0386
Show file tree
Hide file tree
Showing 37 changed files with 1,376 additions and 602 deletions.
272 changes: 238 additions & 34 deletions apps/server/Cargo.lock

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions apps/server/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "hampfh-github-profile"
version = "1.0.0"
version = "1.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
Expand Down Expand Up @@ -31,7 +31,8 @@ chrono = { version = "0.4.11", features = ["serde"] }
diesel = { version = "1.4.8", features = ["sqlite", "chrono", "r2d2"] }
diesel_migrations = "1.4.0"

reqwest = { version = "0.11.10", features = ["blocking"]}
reqwest = { version = "0.11.10", features = ["blocking"] }
# For compiling on linux
libsqlite3-sys = { version = "0.9.1", features = ["bundled"] }
gif = "0.12.0"
clap = { version = "4.5.8", features = ["derive", "cargo"] }
2 changes: 1 addition & 1 deletion apps/server/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,5 @@ run_migration:
info:
@echo "\033[32mSuccessfully set up local environment for bot creation!"
@echo "Execute your first match here:"
@echo "\033[36mcargo run --release match ../scripts/trivial_dodger.lua ../scripts/bfs.lua\033[0m"
@echo "\033[36mcargo run --release match --path-one ../scripts/trivial_dodger.lua --path-two ../scripts/bfs.lua\033[0m"
@echo "\033[32mYour output should now end up in the file match.temp.gif and match.temp.md\033[0m"
1 change: 1 addition & 0 deletions apps/server/src/backend/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ pub mod db;
pub mod models;
#[allow(non_snake_case)]
pub mod schema;
pub mod server;
pub mod services;
24 changes: 24 additions & 0 deletions apps/server/src/backend/server.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
use actix_web::{web::Data, App, HttpServer};

use crate::backend::{self, db::run_migrations, services::routes::routes};

pub(crate) async fn start_server(port: u16, host: String) -> Result<(), std::io::Error> {
migrations();

println!("Listening on port {} and host {}", port, host);
HttpServer::new(move || {
let db_connection = backend::db::establish_connection();
App::new()
.app_data(Data::new(db_connection))
.configure(routes)
})
.bind((host, port))?
.workers(2)
.run()
.await
}

fn migrations() {
let conn = backend::db::establish_connection().get().unwrap();
run_migrations(&conn);
}
133 changes: 0 additions & 133 deletions apps/server/src/cli.rs

This file was deleted.

22 changes: 22 additions & 0 deletions apps/server/src/cli/cli.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
use crate::backend::{self};
use clap::ArgMatches;

use super::{generate::generate, match_make::run_match_make, r#match::run_local_match};

pub async fn cli(matches: ArgMatches) -> Result<(), std::io::Error> {
match matches.subcommand() {
Some(("match", sub_m)) => run_local_match(sub_m),
Some(("db", sub_m)) => match sub_m.subcommand() {
Some(("generate", sub_m)) => generate(sub_m),
_ => return Ok(()),
},
Some(("server", sub_m)) => {
let port = sub_m.get_one::<u16>("port").unwrap();
let host = sub_m.get_one::<String>("host").unwrap();
backend::server::start_server(*port, host.clone()).await?;
}
Some(("matchmake", _)) => run_match_make(),
_ => {}
}
Ok(())
}
51 changes: 51 additions & 0 deletions apps/server/src/cli/generate.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
use clap::ArgMatches;

use crate::{
backend::{
self,
models::{
match_model::Match, submission_model::Submission, turn_model::Turn, user_model::User,
},
},
external_related::readme_factory::{
build_match_files_wrapper, build_match_log_wrapper, build_submission_log_wrapper,
clear_match_dir, generate_readme, write_file,
},
};

pub(crate) fn generate(matches: &ArgMatches) {
let primary_flag = *matches.get_one::<bool>("primary").unwrap();
let matches_flag = *matches.get_one::<bool>("matches").unwrap();
let logs_flag = *matches.get_one::<bool>("logs").unwrap();
let clear_flag = *matches.get_one::<bool>("clear").unwrap();

let no_flags = !primary_flag && !matches_flag && !logs_flag && !clear_flag;

if clear_flag || no_flags {
clear_match_dir();
}
if primary_flag || no_flags {
generate_main();
}
if matches_flag || no_flags {
build_match_files_wrapper();
}
if logs_flag || no_flags {
build_match_log_wrapper();
build_submission_log_wrapper();
}
}

fn generate_main() {
let conn = backend::db::establish_connection().get().unwrap();
write_file(
"../../README.md",
generate_readme(
User::list(&conn),
Submission::list(&conn),
Match::list(&conn),
Turn::list(&conn),
),
)
.unwrap();
}
104 changes: 104 additions & 0 deletions apps/server/src/cli/match.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
use std::{fs, time::Duration};

use clap::ArgMatches;

use crate::{
external_related::readme_factory::{
create_and_encode_file, generate_gif_from_turn, get_match_from_tiles_compact,
},
game::{
game_state::{ErrorType, GameConfig, GameResult},
initialize_game::initialize_game,
player::PlayerType,
},
};

pub(crate) fn run_local_match(matches: &ArgMatches) {
let script1 = std::fs::read_to_string(matches.get_one::<String>("path-one").unwrap())
.expect("Could not load script 1");
let script2 = std::fs::read_to_string(matches.get_one::<String>("path-two").unwrap())
.expect("Could not load script 2");
let outdir = matches.get_one::<String>("output").unwrap();

let mut config = GameConfig::new();
config.live_print_match = *matches.get_one::<bool>("print").unwrap();
config.bot_initialization_timeout =
Duration::from_millis(*matches.get_one::<u64>("init-timeout").unwrap());
config.bot_turn_timeout =
Duration::from_millis(*matches.get_one::<u64>("turn-timeout").unwrap());

let (results, turns, logger) = initialize_game(&script1, &script2, config);

// Create output folder
fs::create_dir_all(outdir).unwrap();

if *matches.get_one::<bool>("readme").unwrap() {
let mut file: String = "".to_string();
file.push_str(&format!(
"<div align=\"center\"><p>{}</p></div>\n\n",
match results {
GameResult::PlayerOneWon => "Script 1 (🟩) won",
GameResult::PlayerTwoWon => "Script 2 (🟥) won",
_ => "",
}
));

if let GameResult::Error(error) = results.clone() {
let string: String;
file.push_str(&format!(
"<div align=\"center\"><p>--- Match has errors ---</p>\n\n{}</div>",
match error {
ErrorType::GameDeadlock => "Reason for error: Game Deadlock",
ErrorType::GameError { reason, fault } => {
// TODO This feels very hacky, there should be another solution for this
string = print_error(Some(reason), fault);
&string
}
ErrorType::RuntimeError { reason, fault } => {
string = print_error(Some(reason), fault);
&string
}
ErrorType::TurnTimeout { fault } => {
string = print_error(None, fault);
&string
}
}
))
}
file.push_str(&get_match_from_tiles_compact(turns.clone()));

fs::write(format!("./{}/{}", outdir, "match.md"), file)
.expect("Could not write match file");
}

if *matches.get_one::<bool>("gif").unwrap() {
let (color_palette, images) = generate_gif_from_turn(turns, Some(results), 50);
create_and_encode_file(
format!("./{}/{}", outdir, "match.gif".to_string()),
images,
&color_palette,
50,
);
}

if *matches.get_one::<bool>("log").unwrap() {
let mut file: String = "".to_string();
for log in logger {
file.push_str(&format!("{}\n", log));
}
fs::write(format!("./{}/{}", outdir, "match.log.txt"), file)
.expect("Could not write log file");
}
}

fn print_error(reason: Option<String>, fault: Option<PlayerType>) -> String {
format!(
"Reason for error: {}\n\nFault: {}",
&reason.unwrap_or("Unknown".to_string()),
match fault {
Some(PlayerType::Flipped) => "Player 1 (🟩)",
Some(PlayerType::Regular) => "Player 2 (🟥)",
_ => "Unknown",
}
)
}
17 changes: 17 additions & 0 deletions apps/server/src/cli/match_make.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
use std::process;

use crate::{backend, match_maker::scheduler::run_scheduled_matchmaking};

pub(crate) fn run_match_make() {
let db_connection = backend::db::establish_connection();
let conn = match db_connection.get() {
Ok(conn) => conn,
Err(error) => {
println!("Could not establish connection to database: {}", error);
process::exit(1);
}
};

run_scheduled_matchmaking(&conn);
process::exit(0);
}
4 changes: 4 additions & 0 deletions apps/server/src/cli/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
pub mod cli;
pub mod generate;
pub mod r#match;
pub mod match_make;
Loading

0 comments on commit 6ec0386

Please sign in to comment.