retrieve opponent from bots database

This commit is contained in:
Ilion Beyst 2022-02-27 22:57:06 +01:00
parent da71643176
commit edb3ead976
2 changed files with 30 additions and 18 deletions

View file

@ -34,6 +34,10 @@ pub fn find_bots_by_owner(owner_id: i32, conn: &PgConnection) -> QueryResult<Vec
.get_results(conn) .get_results(conn)
} }
pub fn find_bot_by_name(name: &str, conn: &PgConnection) -> QueryResult<Bot> {
bots::table.filter(bots::name.eq(name)).first(conn)
}
pub fn find_all_bots(conn: &PgConnection) -> QueryResult<Vec<Bot>> { pub fn find_all_bots(conn: &PgConnection) -> QueryResult<Vec<Bot>> {
// TODO: filter out bots that cannot be run (have no valid code bundle associated with them) // TODO: filter out bots that cannot be run (have no valid code bundle associated with them)
bots::table.get_results(conn) bots::table.get_results(conn)

View file

@ -1,10 +1,12 @@
use crate::db::matches::{self, MatchState}; use crate::db;
use crate::db::matches::MatchState;
use crate::modules::bots::save_code_bundle; use crate::modules::bots::save_code_bundle;
use crate::util::gen_alphanumeric; use crate::util::gen_alphanumeric;
use crate::{ConnectionPool, BOTS_DIR, MAPS_DIR, MATCHES_DIR}; use crate::{ConnectionPool, BOTS_DIR, MAPS_DIR, MATCHES_DIR};
use axum::extract::Extension; use axum::extract::Extension;
use axum::Json; use axum::Json;
use hyper::StatusCode; use hyper::StatusCode;
use planetwars_matchrunner::BotSpec;
use planetwars_matchrunner::{docker_runner::DockerBotSpec, run_match, MatchConfig, MatchPlayer}; use planetwars_matchrunner::{docker_runner::DockerBotSpec, run_match, MatchConfig, MatchPlayer};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::path::PathBuf; use std::path::PathBuf;
@ -12,7 +14,7 @@ use std::path::PathBuf;
use super::matches::ApiMatch; use super::matches::ApiMatch;
const PYTHON_IMAGE: &'static str = "python:3.10-slim-buster"; const PYTHON_IMAGE: &'static str = "python:3.10-slim-buster";
const SIMPLEBOT_PATH: &'static str = "../simplebot"; const OPPONENT_NAME: &'static str = "simplebot";
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
pub struct SubmitBotParams { pub struct SubmitBotParams {
@ -26,6 +28,16 @@ pub struct SubmitBotResponse {
pub match_data: ApiMatch, pub match_data: ApiMatch,
} }
fn code_bundle_to_botspec(code_bundle: &db::bots::CodeBundle) -> Box<dyn BotSpec> {
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 /// submit python code for a bot, which will face off
/// with a demo bot. Return a played match. /// with a demo bot. Return a played match.
pub async fn submit_bot( pub async fn submit_bot(
@ -34,12 +46,16 @@ pub async fn submit_bot(
) -> Result<Json<SubmitBotResponse>, StatusCode> { ) -> Result<Json<SubmitBotResponse>, StatusCode> {
let conn = pool.get().await.expect("could not get database connection"); let conn = pool.get().await.expect("could not get database connection");
let code_bundle = save_code_bundle(&params.code, None, &conn) let opponent =
db::bots::find_bot_by_name(OPPONENT_NAME, &conn).expect("could not find opponent bot");
let opponent_code_bundle =
db::bots::active_code_bundle(opponent.id, &conn).expect("opponent bot has no code bundles");
let player_code_bundle = save_code_bundle(&params.code, None, &conn)
// TODO: can we recover from this? // TODO: can we recover from this?
.expect("could not save bot code"); .expect("could not save bot code");
let log_file_name = format!("{}.log", gen_alphanumeric(16)); let log_file_name = format!("{}.log", gen_alphanumeric(16));
let uploaded_bot_dir = PathBuf::from(BOTS_DIR).join(&code_bundle.path);
// play the match // play the match
let match_config = MatchConfig { let match_config = MatchConfig {
map_path: PathBuf::from(MAPS_DIR).join("hex.json"), map_path: PathBuf::from(MAPS_DIR).join("hex.json"),
@ -48,31 +64,23 @@ pub async fn submit_bot(
players: vec![ players: vec![
MatchPlayer { MatchPlayer {
name: "player".to_string(), name: "player".to_string(),
bot_spec: Box::new(DockerBotSpec { bot_spec: code_bundle_to_botspec(&player_code_bundle),
code_path: uploaded_bot_dir,
image: PYTHON_IMAGE.to_string(),
argv: vec!["python".to_string(), "bot.py".to_string()],
}),
}, },
MatchPlayer { MatchPlayer {
name: "simplebot".to_string(), name: OPPONENT_NAME.to_string(),
bot_spec: Box::new(DockerBotSpec { bot_spec: code_bundle_to_botspec(&opponent_code_bundle),
code_path: PathBuf::from(SIMPLEBOT_PATH),
image: PYTHON_IMAGE.to_string(),
argv: vec!["python".to_string(), "simplebot.py".to_string()],
}),
}, },
], ],
}; };
// store match in database // store match in database
let new_match_data = matches::NewMatch { let new_match_data = db::matches::NewMatch {
state: MatchState::Playing, state: MatchState::Playing,
log_path: &log_file_name, log_path: &log_file_name,
}; };
// TODO: set match players // TODO: set match players
let match_data = let match_data =
matches::create_match(&new_match_data, &[], &conn).expect("failed to create match"); db::matches::create_match(&new_match_data, &[], &conn).expect("failed to create match");
tokio::spawn(run_match_task( tokio::spawn(run_match_task(
match_data.base.id, match_data.base.id,
@ -92,6 +100,6 @@ async fn run_match_task(match_id: i32, match_config: MatchConfig, connection_poo
.get() .get()
.await .await
.expect("could not get database connection"); .expect("could not get database connection");
matches::set_match_state(match_id, MatchState::Finished, &conn) db::matches::set_match_state(match_id, MatchState::Finished, &conn)
.expect("failed to update match state"); .expect("failed to update match state");
} }