From 7b142554d808a494df4ba9e616c58861370ccd93 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Thu, 28 Apr 2022 21:31:49 +0200 Subject: [PATCH] move match running logic to separate module --- planetwars-matchrunner/src/lib.rs | 1 - planetwars-server/src/db/bots.rs | 2 +- planetwars-server/src/modules/matches.rs | 102 +++++++++++++++++++++++ planetwars-server/src/modules/mod.rs | 1 + planetwars-server/src/modules/ranking.rs | 33 +++++++- planetwars-server/src/routes/demo.rs | 79 +++--------------- planetwars-server/src/routes/matches.rs | 1 - 7 files changed, 144 insertions(+), 75 deletions(-) create mode 100644 planetwars-server/src/modules/matches.rs diff --git a/planetwars-matchrunner/src/lib.rs b/planetwars-matchrunner/src/lib.rs index 1f1a4c7..5aff793 100644 --- a/planetwars-matchrunner/src/lib.rs +++ b/planetwars-matchrunner/src/lib.rs @@ -38,7 +38,6 @@ pub struct PlayerInfo { } pub struct MatchPlayer { - pub name: String, pub bot_spec: Box, } diff --git a/planetwars-server/src/db/bots.rs b/planetwars-server/src/db/bots.rs index d99a459..108c692 100644 --- a/planetwars-server/src/db/bots.rs +++ b/planetwars-server/src/db/bots.rs @@ -11,7 +11,7 @@ pub struct NewBot<'a> { pub name: &'a str, } -#[derive(Queryable, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Queryable, Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Bot { pub id: i32, pub owner_id: Option, diff --git a/planetwars-server/src/modules/matches.rs b/planetwars-server/src/modules/matches.rs new file mode 100644 index 0000000..201c6d4 --- /dev/null +++ b/planetwars-server/src/modules/matches.rs @@ -0,0 +1,102 @@ +use std::path::PathBuf; + +use diesel::{PgConnection, QueryResult}; +use planetwars_matchrunner::{self as runner, docker_runner::DockerBotSpec, BotSpec, MatchConfig}; +use runner::MatchOutcome; +use tokio::task::JoinHandle; + +use crate::{ + db::{self, matches::MatchData}, + util::gen_alphanumeric, + ConnectionPool, BOTS_DIR, MAPS_DIR, MATCHES_DIR, +}; + +const PYTHON_IMAGE: &str = "python:3.10-slim-buster"; + +pub struct RunMatch<'a> { + log_file_name: String, + player_code_bundles: Vec<&'a db::bots::CodeBundle>, + match_id: Option, +} + +impl<'a> RunMatch<'a> { + pub fn from_players(player_code_bundles: Vec<&'a db::bots::CodeBundle>) -> Self { + let log_file_name = format!("{}.log", gen_alphanumeric(16)); + RunMatch { + log_file_name, + player_code_bundles, + match_id: None, + } + } + + pub fn runner_config(&self) -> runner::MatchConfig { + runner::MatchConfig { + map_path: PathBuf::from(MAPS_DIR).join("hex.json"), + map_name: "hex".to_string(), + log_path: PathBuf::from(MATCHES_DIR).join(&self.log_file_name), + players: self + .player_code_bundles + .iter() + .map(|b| runner::MatchPlayer { + bot_spec: code_bundle_to_botspec(b), + }) + .collect(), + } + } + + pub fn store_in_database(&mut self, db_conn: &PgConnection) -> QueryResult { + // don't store the same match twice + assert!(self.match_id.is_none()); + + let new_match_data = db::matches::NewMatch { + state: db::matches::MatchState::Playing, + log_path: &self.log_file_name, + }; + let new_match_players = self + .player_code_bundles + .iter() + .map(|b| db::matches::MatchPlayerData { + code_bundle_id: b.id, + }) + .collect::>(); + + let match_data = db::matches::create_match(&new_match_data, &new_match_players, &db_conn)?; + self.match_id = Some(match_data.base.id); + Ok(match_data) + } + + pub fn spawn(self, pool: ConnectionPool) -> JoinHandle { + let match_id = self.match_id.expect("match must be saved before running"); + let runner_config = self.runner_config(); + tokio::spawn(run_match_task(pool, runner_config, match_id)) + } +} + +pub fn code_bundle_to_botspec(code_bundle: &db::bots::CodeBundle) -> Box { + let bundle_path = PathBuf::from(BOTS_DIR).join(&code_bundle.path); + + Box::new(DockerBotSpec { + code_path: bundle_path, + image: PYTHON_IMAGE.to_string(), + argv: vec!["python".to_string(), "bot.py".to_string()], + }) +} + +async fn run_match_task( + connection_pool: ConnectionPool, + match_config: MatchConfig, + match_id: i32, +) -> MatchOutcome { + let outcome = runner::run_match(match_config).await; + + // update match state in database + let conn = connection_pool + .get() + .await + .expect("could not get database connection"); + + db::matches::set_match_state(match_id, db::matches::MatchState::Finished, &conn) + .expect("could not update match state"); + + return outcome; +} diff --git a/planetwars-server/src/modules/mod.rs b/planetwars-server/src/modules/mod.rs index 2efce4e..bea28e0 100644 --- a/planetwars-server/src/modules/mod.rs +++ b/planetwars-server/src/modules/mod.rs @@ -1,4 +1,5 @@ // This module implements general domain logic, not directly // tied to the database or API layers. pub mod bots; +pub mod matches; pub mod ranking; diff --git a/planetwars-server/src/modules/ranking.rs b/planetwars-server/src/modules/ranking.rs index 739e6a6..53e1e4e 100644 --- a/planetwars-server/src/modules/ranking.rs +++ b/planetwars-server/src/modules/ranking.rs @@ -1,5 +1,32 @@ -use crate::DbPool; +use crate::{db::bots::Bot, DbPool}; -pub async fn run_ranker(_db_pool: DbPool) { - // do nothing, for now +use crate::db; +use diesel::PgConnection; +use rand::seq::SliceRandom; +use std::time::Duration; +use tokio; + +pub async fn run_ranker(db_pool: DbPool) { + // TODO: make this configurable + // play at most one match every n seconds + let mut interval = tokio::time::interval(Duration::from_secs(10)); + let db_conn = db_pool + .get() + .await + .expect("could not get database connection"); + loop { + interval.tick().await; + let bots = db::bots::find_all_bots(&db_conn).unwrap(); + if bots.len() < 2 { + // not enough bots to play a match + continue; + } + let selected_bots: Vec = { + let mut rng = &mut rand::thread_rng(); + bots.choose_multiple(&mut rng, 2).cloned().collect() + }; + play_match(selected_bots, db_pool.clone()).await; + } } + +async fn play_match(selected_bots: Vec, db_pool: DbPool) {} diff --git a/planetwars-server/src/routes/demo.rs b/planetwars-server/src/routes/demo.rs index eb7f61f..7f7ba71 100644 --- a/planetwars-server/src/routes/demo.rs +++ b/planetwars-server/src/routes/demo.rs @@ -1,20 +1,16 @@ use crate::db; -use crate::db::matches::{FullMatchData, FullMatchPlayerData, MatchPlayerData, MatchState}; +use crate::db::matches::{FullMatchData, FullMatchPlayerData}; use crate::modules::bots::save_code_bundle; -use crate::util::gen_alphanumeric; -use crate::{ConnectionPool, BOTS_DIR, MAPS_DIR, MATCHES_DIR}; +use crate::modules::matches::RunMatch; +use crate::ConnectionPool; use axum::extract::Extension; use axum::Json; use hyper::StatusCode; -use planetwars_matchrunner::BotSpec; -use planetwars_matchrunner::{docker_runner::DockerBotSpec, run_match, MatchConfig, MatchPlayer}; use serde::{Deserialize, Serialize}; -use std::path::PathBuf; use super::matches::ApiMatch; -const PYTHON_IMAGE: &str = "python:3.10-slim-buster"; -const OPPONENT_NAME: &str = "simplebot"; +const DEFAULT_OPPONENT_NAME: &str = "simplebot"; #[derive(Serialize, Deserialize, Debug)] pub struct SubmitBotParams { @@ -29,16 +25,6 @@ pub struct SubmitBotResponse { pub match_data: ApiMatch, } -fn code_bundle_to_botspec(code_bundle: &db::bots::CodeBundle) -> Box { - let bundle_path = PathBuf::from(BOTS_DIR).join(&code_bundle.path); - - Box::new(DockerBotSpec { - code_path: bundle_path, - image: PYTHON_IMAGE.to_string(), - argv: vec!["python".to_string(), "bot.py".to_string()], - }) -} - /// submit python code for a bot, which will face off /// with a demo bot. Return a played match. pub async fn submit_bot( @@ -49,7 +35,7 @@ pub async fn submit_bot( let opponent_name = params .opponent_name - .unwrap_or_else(|| OPPONENT_NAME.to_string()); + .unwrap_or_else(|| DEFAULT_OPPONENT_NAME.to_string()); let opponent = db::bots::find_bot_by_name(&opponent_name, &conn).map_err(|_| StatusCode::BAD_REQUEST)?; @@ -60,46 +46,11 @@ pub async fn submit_bot( // TODO: can we recover from this? .expect("could not save bot code"); - let log_file_name = format!("{}.log", gen_alphanumeric(16)); - // play the match - let match_config = MatchConfig { - map_path: PathBuf::from(MAPS_DIR).join("hex.json"), - map_name: "hex".to_string(), - log_path: PathBuf::from(MATCHES_DIR).join(&log_file_name), - players: vec![ - MatchPlayer { - name: "player".to_string(), - bot_spec: code_bundle_to_botspec(&player_code_bundle), - }, - MatchPlayer { - name: OPPONENT_NAME.to_string(), - bot_spec: code_bundle_to_botspec(&opponent_code_bundle), - }, - ], - }; - - // store match in database - let new_match_data = db::matches::NewMatch { - state: MatchState::Playing, - log_path: &log_file_name, - }; - - let new_match_players = [ - MatchPlayerData { - code_bundle_id: player_code_bundle.id, - }, - MatchPlayerData { - code_bundle_id: opponent_code_bundle.id, - }, - ]; - let match_data = db::matches::create_match(&new_match_data, &new_match_players, &conn) - .expect("failed to create match"); - - tokio::spawn(run_match_task( - match_data.base.id, - match_config, - pool.clone(), - )); + let mut run_match = RunMatch::from_players(vec![&player_code_bundle, &opponent_code_bundle]); + let match_data = run_match + .store_in_database(&conn) + .expect("failed to save match"); + run_match.spawn(pool.clone()); // TODO: avoid clones let full_match_data = FullMatchData { @@ -123,13 +74,3 @@ pub async fn submit_bot( match_data: api_match, })) } - -async fn run_match_task(match_id: i32, match_config: MatchConfig, connection_pool: ConnectionPool) { - run_match(match_config).await; - let conn = connection_pool - .get() - .await - .expect("could not get database connection"); - db::matches::set_match_state(match_id, MatchState::Finished, &conn) - .expect("failed to update match state"); -} diff --git a/planetwars-server/src/routes/matches.rs b/planetwars-server/src/routes/matches.rs index 991a4b5..b61008d 100644 --- a/planetwars-server/src/routes/matches.rs +++ b/planetwars-server/src/routes/matches.rs @@ -52,7 +52,6 @@ pub async fn play_match( .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; players.push(MatchPlayer { - name: bot.name.clone(), bot_spec: Box::new(DockerBotSpec { code_path: PathBuf::from(BOTS_DIR).join(code_bundle.path), image: "python:3.10-slim-buster".to_string(),