diff options
-rw-r--r-- | planetwars-server/src/db/matches.rs | 9 | ||||
-rw-r--r-- | planetwars-server/src/routes/demo.rs | 23 |
2 files changed, 27 insertions, 5 deletions
diff --git a/planetwars-server/src/db/matches.rs b/planetwars-server/src/db/matches.rs index efaa1eb..6444bf6 100644 --- a/planetwars-server/src/db/matches.rs +++ b/planetwars-server/src/db/matches.rs @@ -1,6 +1,6 @@ pub use crate::db_types::MatchState; use chrono::NaiveDateTime; -use diesel::{BelongingToDsl, QueryDsl, RunQueryDsl}; +use diesel::{BelongingToDsl, ExpressionMethods, QueryDsl, RunQueryDsl}; use diesel::{Connection, GroupedBy, PgConnection, QueryResult}; use crate::schema::{match_players, matches}; @@ -120,3 +120,10 @@ pub fn find_match(id: i32, conn: &PgConnection) -> QueryResult<MatchData> { pub fn find_mach_base(id: i32, conn: &PgConnection) -> QueryResult<MatchBase> { matches::table.find(id).get_result::<MatchBase>(conn) } + +pub fn set_match_state(id: i32, match_state: MatchState, conn: &PgConnection) -> QueryResult<()> { + diesel::update(matches::table.find(id)) + .set(matches::state.eq(match_state)) + .execute(conn)?; + Ok(()) +} diff --git a/planetwars-server/src/routes/demo.rs b/planetwars-server/src/routes/demo.rs index 11d8d72..dbcdb64 100644 --- a/planetwars-server/src/routes/demo.rs +++ b/planetwars-server/src/routes/demo.rs @@ -41,7 +41,7 @@ pub async fn submit_bot( std::fs::write(uploaded_bot_dir.join("bot.py"), params.code.as_bytes()).unwrap(); // play the match - run_match(MatchConfig { + 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), @@ -63,24 +63,39 @@ pub async fn submit_bot( }), }, ], - }) - .await; + }; // store match in database let new_match_data = matches::NewMatch { - state: MatchState::Finished, + state: MatchState::Playing, log_path: &log_file_name, }; // TODO: set match players let match_data = matches::create_match(&new_match_data, &[], &conn).expect("failed to create match"); + tokio::spawn(run_match_task( + match_data.base.id, + match_config, + pool.clone(), + )); + let api_match = super::matches::match_data_to_api(match_data); Ok(Json(SubmitBotResponse { 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"); + matches::set_match_state(match_id, MatchState::Finished, &conn) + .expect("failed to update match state"); +} + pub fn gen_alphanumeric(length: usize) -> String { rand::thread_rng() .sample_iter(&Alphanumeric) |