planetwars.dev/planetwars-server/src/routes/demo.rs

106 lines
3.4 KiB
Rust
Raw Normal View History

2022-02-08 20:13:24 +01:00
use crate::db::matches::{self, MatchState};
use crate::{ConnectionPool, BOTS_DIR, MAPS_DIR, MATCHES_DIR};
use axum::extract::Extension;
use axum::Json;
use hyper::StatusCode;
use planetwars_matchrunner::{docker_runner::DockerBotSpec, run_match, MatchConfig, MatchPlayer};
use rand::{distributions::Alphanumeric, Rng};
use serde::{Deserialize, Serialize};
2022-02-08 20:13:24 +01:00
use std::path::PathBuf;
2022-02-08 20:13:24 +01:00
use super::matches::ApiMatch;
const PYTHON_IMAGE: &'static str = "python:3.10-slim-buster";
const SIMPLEBOT_PATH: &'static str = "../simplebot";
#[derive(Serialize, Deserialize, Debug)]
pub struct SubmitBotParams {
pub code: String,
}
2022-02-08 20:13:24 +01:00
#[derive(Serialize, Deserialize)]
pub struct SubmitBotResponse {
2022-02-08 20:13:24 +01:00
#[serde(rename = "match")]
pub match_data: ApiMatch,
}
/// submit python code for a bot, which will face off
/// with a demo bot. Return a played match.
pub async fn submit_bot(
Json(params): Json<SubmitBotParams>,
2022-02-08 20:13:24 +01:00
Extension(pool): Extension<ConnectionPool>,
) -> Result<Json<SubmitBotResponse>, StatusCode> {
2022-02-08 20:13:24 +01:00
let conn = pool.get().await.expect("could not get database connection");
let uploaded_bot_uuid: String = gen_alphanumeric(16);
let log_file_name = format!("{}.log", gen_alphanumeric(16));
2022-02-08 20:13:24 +01:00
// store uploaded bot
let uploaded_bot_dir = PathBuf::from(BOTS_DIR).join(&uploaded_bot_uuid);
std::fs::create_dir(&uploaded_bot_dir).unwrap();
std::fs::write(uploaded_bot_dir.join("bot.py"), params.code.as_bytes()).unwrap();
2022-02-08 20:13:24 +01:00
// play the match
2022-02-15 19:54:29 +01:00
let match_config = MatchConfig {
map_path: PathBuf::from(MAPS_DIR).join("hex.json"),
map_name: "hex".to_string(),
2022-02-08 20:13:24 +01:00
log_path: PathBuf::from(MATCHES_DIR).join(&log_file_name),
players: vec![
MatchPlayer {
2022-02-08 20:13:24 +01:00
name: "player".to_string(),
bot_spec: Box::new(DockerBotSpec {
2022-01-27 19:12:18 +01:00
code_path: uploaded_bot_dir,
image: PYTHON_IMAGE.to_string(),
argv: vec!["python".to_string(), "bot.py".to_string()],
}),
},
MatchPlayer {
name: "simplebot".to_string(),
bot_spec: Box::new(DockerBotSpec {
code_path: PathBuf::from(SIMPLEBOT_PATH),
image: PYTHON_IMAGE.to_string(),
argv: vec!["python".to_string(), "simplebot.py".to_string()],
}),
},
],
2022-02-15 19:54:29 +01:00
};
2022-02-08 20:13:24 +01:00
// store match in database
let new_match_data = matches::NewMatch {
2022-02-15 19:54:29 +01:00
state: MatchState::Playing,
2022-02-08 20:13:24 +01:00
log_path: &log_file_name,
};
// TODO: set match players
let match_data =
matches::create_match(&new_match_data, &[], &conn).expect("failed to create match");
2022-02-15 19:54:29 +01:00
tokio::spawn(run_match_task(
match_data.base.id,
match_config,
pool.clone(),
));
2022-02-08 20:13:24 +01:00
let api_match = super::matches::match_data_to_api(match_data);
Ok(Json(SubmitBotResponse {
match_data: api_match,
}))
}
2022-02-15 19:54:29 +01:00
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");
}
2022-02-08 20:13:24 +01:00
pub fn gen_alphanumeric(length: usize) -> String {
rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(length)
.map(char::from)
.collect()
}