SeaBattle/rust/sea_battle_backend/src/server.rs

204 lines
5.8 KiB
Rust
Raw Normal View History

2022-09-24 09:46:12 +00:00
use actix::{Actor, Addr};
2022-09-14 14:50:29 +00:00
use actix_cors::Cors;
use actix_web::{web, App, HttpRequest, HttpResponse, HttpServer, Responder};
use actix_web_actors::ws;
2022-09-17 10:02:13 +00:00
use crate::args::Args;
2022-10-18 06:58:36 +00:00
use crate::data::{GameRules, PlayConfiguration, VersionInfo};
2022-09-24 09:46:12 +00:00
use crate::dispatcher_actor::DispatcherActor;
2022-09-17 10:02:13 +00:00
use crate::human_player_ws::{HumanPlayerWS, StartMode};
2022-09-14 14:50:29 +00:00
/// The default '/' route
async fn index() -> impl Responder {
HttpResponse::Ok().json("Sea battle backend")
}
/// The default 404 route
async fn not_found() -> impl Responder {
HttpResponse::NotFound().json("You missed your strike lol")
}
2022-10-18 06:58:36 +00:00
/// Get version information
async fn version_information() -> impl Responder {
HttpResponse::Ok().json(VersionInfo::load_static())
}
/// Get game configuration
2022-09-14 14:50:29 +00:00
async fn game_configuration() -> impl Responder {
HttpResponse::Ok().json(PlayConfiguration::default())
}
#[derive(serde::Serialize, serde::Deserialize, Eq, PartialEq, Debug)]
pub struct BotPlayQuery {
#[serde(flatten)]
pub rules: GameRules,
pub player_name: String,
}
2022-09-14 14:50:29 +00:00
/// Start bot game
async fn start_bot_play(
req: HttpRequest,
stream: web::Payload,
query: web::Query<BotPlayQuery>,
2022-09-24 09:46:12 +00:00
dispatcher: web::Data<Addr<DispatcherActor>>,
2022-09-14 14:50:29 +00:00
) -> Result<HttpResponse, actix_web::Error> {
let errors = query.rules.get_errors();
2022-09-14 14:50:29 +00:00
if !errors.is_empty() {
return Ok(HttpResponse::BadRequest().json(errors));
}
2022-09-24 09:46:12 +00:00
let player_ws = HumanPlayerWS::new(
StartMode::Bot(query.rules.clone()),
2022-09-24 09:46:12 +00:00
&dispatcher,
query.player_name.clone(),
2022-09-24 09:46:12 +00:00
);
2022-09-14 14:50:29 +00:00
let resp = ws::start(player_ws, &req, stream);
log::info!("New bot play with configuration: {:?}", &query.rules);
2022-09-14 14:50:29 +00:00
resp
}
#[derive(serde::Serialize, serde::Deserialize)]
pub struct CreateInviteQuery {
#[serde(flatten)]
pub rules: GameRules,
pub player_name: String,
}
2022-09-24 09:46:12 +00:00
/// Start game by creating invite
async fn start_create_invite(
req: HttpRequest,
stream: web::Payload,
query: web::Query<CreateInviteQuery>,
2022-09-24 09:46:12 +00:00
dispatcher: web::Data<Addr<DispatcherActor>>,
) -> Result<HttpResponse, actix_web::Error> {
let errors = query.rules.get_errors();
2022-09-24 09:46:12 +00:00
if !errors.is_empty() {
return Ok(HttpResponse::BadRequest().json(errors));
}
let player_ws = HumanPlayerWS::new(
StartMode::CreateInvite(query.rules.clone()),
2022-09-24 09:46:12 +00:00
&dispatcher,
query.0.player_name,
2022-09-24 09:46:12 +00:00
);
let resp = ws::start(player_ws, &req, stream);
log::info!(
"New create invite play with configuration: {:?}",
&query.0.rules
);
2022-09-24 09:46:12 +00:00
resp
}
#[derive(serde::Serialize, serde::Deserialize)]
pub struct AcceptInviteQuery {
pub code: String,
pub player_name: String,
2022-09-24 09:46:12 +00:00
}
/// Start game by creating invite
async fn start_accept_invite(
req: HttpRequest,
stream: web::Payload,
query: web::Query<AcceptInviteQuery>,
dispatcher: web::Data<Addr<DispatcherActor>>,
) -> Result<HttpResponse, actix_web::Error> {
let player_ws = HumanPlayerWS::new(
StartMode::AcceptInvite {
code: query.code.clone(),
},
&dispatcher,
query.0.player_name,
2022-09-24 09:46:12 +00:00
);
let resp = ws::start(player_ws, &req, stream);
log::info!("New accept invite: {:?}", &query.0.code);
resp
}
2022-10-01 08:16:00 +00:00
#[derive(serde::Serialize, serde::Deserialize)]
pub struct PlayRandomQuery {
pub player_name: String,
}
/// Start game, playing against a random person
async fn start_random(
req: HttpRequest,
stream: web::Payload,
query: web::Query<PlayRandomQuery>,
dispatcher: web::Data<Addr<DispatcherActor>>,
) -> Result<HttpResponse, actix_web::Error> {
let player_ws = HumanPlayerWS::new(StartMode::PlayRandom, &dispatcher, query.0.player_name);
let resp = ws::start(player_ws, &req, stream);
log::info!("New random play");
resp
}
2022-09-14 15:36:16 +00:00
pub async fn start_server(args: Args) -> std::io::Result<()> {
log::info!("Start to listen on {}", args.listen_address);
2022-09-14 14:50:29 +00:00
let args_clone = args.clone();
2022-09-24 09:46:12 +00:00
let dispatcher_actor = DispatcherActor::default().start();
2022-09-14 14:50:29 +00:00
HttpServer::new(move || {
let mut cors = Cors::default();
match args_clone.cors.as_deref() {
Some("*") => cors = cors.allow_any_origin(),
Some(orig) => cors = cors.allowed_origin(orig),
None => {}
}
App::new()
2022-09-24 09:46:12 +00:00
.app_data(web::Data::new(dispatcher_actor.clone()))
2022-09-14 14:50:29 +00:00
.wrap(cors)
2022-10-18 06:58:36 +00:00
.route("/version", web::get().to(version_information))
2022-09-14 14:50:29 +00:00
.route("/config", web::get().to(game_configuration))
.route("/play/bot", web::get().to(start_bot_play))
2022-09-24 09:46:12 +00:00
.route("/play/create_invite", web::get().to(start_create_invite))
.route("/play/accept_invite", web::get().to(start_accept_invite))
2022-10-01 08:16:00 +00:00
.route("/play/random", web::get().to(start_random))
2022-09-14 14:50:29 +00:00
.route("/", web::get().to(index))
.route("{tail:.*}", web::get().to(not_found))
})
.bind(&args.listen_address)?
.run()
.await
}
#[cfg(test)]
mod test {
2022-10-17 05:42:17 +00:00
use crate::data::GameRules;
use crate::server::BotPlayQuery;
#[test]
fn simple_bot_request_serialize_deserialize() {
let query = BotPlayQuery {
rules: Default::default(),
player_name: "Player".to_string(),
};
let string = serde_urlencoded::to_string(&query).unwrap();
let des = serde_urlencoded::from_str(&string).unwrap();
assert_eq!(query, des)
}
2022-10-17 05:42:17 +00:00
#[test]
fn simple_bot_request_serialize_deserialize_no_timeout() {
let query = BotPlayQuery {
rules: GameRules {
strike_timeout: None,
..Default::default()
},
player_name: "Player".to_string(),
};
let string = serde_urlencoded::to_string(&query).unwrap();
let des = serde_urlencoded::from_str(&string).unwrap();
assert_eq!(query, des)
}
}