From 22a8f3d619e8ef89eeb9a60ab0a27aed01aa93f7 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Sun, 27 Feb 2022 20:35:22 +0100 Subject: save all uploaded code bundles in database --- planetwars-server/src/routes/bots.rs | 2 +- planetwars-server/src/routes/demo.rs | 24 ++++++++---------------- 2 files changed, 9 insertions(+), 17 deletions(-) (limited to 'planetwars-server/src/routes') diff --git a/planetwars-server/src/routes/bots.rs b/planetwars-server/src/routes/bots.rs index 0edfaa9..66b4d82 100644 --- a/planetwars-server/src/routes/bots.rs +++ b/planetwars-server/src/routes/bots.rs @@ -97,7 +97,7 @@ pub async fn upload_code_multipart( .map_err(|_| StatusCode::BAD_REQUEST)?; let bundle = bots::NewCodeBundle { - bot_id: bot.id, + bot_id: Some(bot.id), path: &folder_name, }; let code_bundle = diff --git a/planetwars-server/src/routes/demo.rs b/planetwars-server/src/routes/demo.rs index dbcdb64..28eab97 100644 --- a/planetwars-server/src/routes/demo.rs +++ b/planetwars-server/src/routes/demo.rs @@ -1,10 +1,11 @@ use crate::db::matches::{self, MatchState}; +use crate::modules::bots::save_code_bundle; +use crate::util::gen_alphanumeric; 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}; use std::path::PathBuf; @@ -15,6 +16,7 @@ const SIMPLEBOT_PATH: &'static str = "../simplebot"; #[derive(Serialize, Deserialize, Debug)] pub struct SubmitBotParams { + pub bot_name: Option, pub code: String, } @@ -32,14 +34,12 @@ pub async fn submit_bot( ) -> Result, StatusCode> { 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)); - - // 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(); + let code_bundle = save_code_bundle(¶ms.code, None, &conn) + // TODO: can we recover from this? + .expect("could not save bot code"); + let log_file_name = format!("{}.log", gen_alphanumeric(16)); + let uploaded_bot_dir = PathBuf::from(BOTS_DIR).join(&code_bundle.path); // play the match let match_config = MatchConfig { map_path: PathBuf::from(MAPS_DIR).join("hex.json"), @@ -95,11 +95,3 @@ async fn run_match_task(match_id: i32, match_config: MatchConfig, connection_poo 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) - .take(length) - .map(char::from) - .collect() -} -- cgit v1.2.3