Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement /post/game route #10

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 6 additions & 1 deletion ns2-stat-api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@ edition = "2021"

[dependencies]
actix-web = "4.0"
clap = { version = "3.1", default_features = false, features = ["std", "derive"] }
clap = { version = "3.1", default_features = false, features = [
"std",
"derive",
] }
ns2-stat = { path = "../ns2-stat" }
serde = "1.0"
serde_json = "1.0"
log = "0.4"
fern = { version = "0.6", features = ["colored"] }
97 changes: 84 additions & 13 deletions ns2-stat-api/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
use std::{fs, io, path::PathBuf};
use std::net::{IpAddr, SocketAddr};
use std::sync::RwLock;
use std::{fs, io, path::PathBuf};

use actix_web::post;
use actix_web::web::Json;
use actix_web::{
body::EitherBody,
error::JsonPayloadError,
Expand All @@ -9,8 +12,9 @@ use actix_web::{
web::{Data, Query},
App, HttpResponse, HttpServer, Responder,
};

use clap::Parser;
use ns2_stat::{input_types::GameStats, Games, NS2Stats};
use ns2_stat::{input_types::GameStats, Games, Merge, NS2Stats};
use serde::{Deserialize, Serialize};

fn json_response<T: Serialize>(data: &T) -> HttpResponse<EitherBody<String>> {
Expand All @@ -22,10 +26,10 @@ fn json_response<T: Serialize>(data: &T) -> HttpResponse<EitherBody<String>> {
Err(err) => HttpResponse::from_error(JsonPayloadError::Serialize(err)).map_into_right_body(),
}
}

struct AppData {
games: Vec<GameStats>,
stats: NS2Stats,
cli_args: CliArgs,
}

#[derive(Debug, Serialize)]
Expand Down Expand Up @@ -77,12 +81,14 @@ impl DateQuery {
}

#[get("/stats")]
async fn get_stats(data: Data<AppData>) -> impl Responder {
async fn get_stats(data: Data<RwLock<AppData>>) -> impl Responder {
let data = data.read().unwrap();
json_response(&DatedData::from(&data.stats))
}

#[get("/stats/continuous")]
async fn get_continuous_stats(data: Data<AppData>, query: Query<DateQuery>) -> impl Responder {
async fn get_continuous_stats(data: Data<RwLock<AppData>>, query: Query<DateQuery>) -> impl Responder {
let data = data.read().unwrap();
let game_stats = Games(query.slice(&data.games).iter()).genuine().collect::<Vec<_>>();
let continuous_stats = (0..game_stats.len())
.map(|i| DatedData {
Expand All @@ -94,31 +100,64 @@ async fn get_continuous_stats(data: Data<AppData>, query: Query<DateQuery>) -> i
}

#[get("/games")]
async fn get_games(data: Data<AppData>, query: Query<DateQuery>) -> impl Responder {
async fn get_games(data: Data<RwLock<AppData>>, query: Query<DateQuery>) -> impl Responder {
let data = data.read().unwrap();
json_response(&query.slice(&data.games))
}

#[post("/post/game")]
async fn post_game(data: Data<RwLock<AppData>>, game: Json<GameStats>) -> impl Responder {
let res = {
let mut data = data.write().unwrap(); // Needs better error handling -- esp. with if the RwLock is poisoned
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
let mut data = data.write().unwrap(); // Needs better error handling -- esp. with if the RwLock is poisoned
let mut data = data.write().unwrap(); // Needs better error handling -- esp. with if the RwLock is poisoned

We could use parking_lot, which has an RwLock without poisoning.

let game = game.into_inner();
let stats = NS2Stats::from(&game);
let res = json_response(&stats);

data.stats.merge(stats);
data.games.push(game);
Comment on lines +116 to +117
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we want to check if the game is already present (by checking the round_date)?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should check if the game already exists (by comparing the round date) and return an appropriate response (an error or something like an empty JSON) in that case.

res
};

let data = data.read().unwrap();
if !data.cli_args.no_copy {
let game = data.games.last().unwrap(); // we just pushed a game
let path = data.cli_args.data_path.join(&format!("{}.json", game.date()));
if path.exists() {
log::warn!("Tried to write {path:?}, but file already exists -- skipping.");
return res;
}
fs::write(&path, serde_json::to_string_pretty(&game).unwrap()).unwrap();
log::trace!("Writing {path:?}");
}

res
}

#[actix_web::main]
async fn main() -> io::Result<()> {
let args = CliArgs::parse();
let mut games = fs::read_dir(args.data_path)?
let cli_args = CliArgs::parse();
init_logger(&cli_args);

let mut games = fs::read_dir(&cli_args.data_path)?
.map(|e| e.map(|e| e.path()))
.map(|p| p.and_then(fs::read_to_string))
.map(|s| s.and_then(|o| serde_json::from_str::<GameStats>(&o).map_err(|e| io::Error::new(io::ErrorKind::Other, e))))
.collect::<io::Result<Vec<_>>>()?;

games.sort_by_key(|game| game.round_info.round_date);

let data = Data::new(AppData {
stats: NS2Stats::compute(Games(games.iter()).genuine()),
let addr = SocketAddr::new(cli_args.address, cli_args.port);
let data = Data::new(RwLock::new(AppData {
cli_args,
stats: NS2Stats::compute(Games(games.iter()).genuine()).expect("No stats found"),
games,
});
}));

let addr = SocketAddr::new(args.address, args.port);
println!("starting server at {}...", addr);
log::info!("starting server at http://{}", addr);
HttpServer::new(move || {
App::new()
.app_data(data.clone())
.service(post_game)
.service(get_stats)
.service(get_continuous_stats)
.service(get_games)
Expand All @@ -132,8 +171,40 @@ async fn main() -> io::Result<()> {
struct CliArgs {
/// The path for the game data.
data_path: PathBuf,

#[clap(long, default_value = "127.0.0.1")]
address: IpAddr,

#[clap(long, short, default_value = "8080")]
port: u16,

/// Don't copy new games (e.g. via /post/game) to `data_path`.
#[clap(long, short)]
no_copy: bool,

#[clap(long)]
no_color: bool,
}

fn init_logger(args: &CliArgs) {
use fern::colors::{Color, ColoredLevelConfig};
let colors = match args.no_color {
false => ColoredLevelConfig::new().debug(Color::Magenta).info(Color::Green).error(Color::Red),
true => ColoredLevelConfig::default(),
};

fern::Dispatch::new()
.chain(std::io::stdout())
.level_for("ns2_stat_api", log::LevelFilter::Trace)
.level(log::LevelFilter::Warn)
.format(move |out, message, record| {
out.finish(format_args!(
"[{}] {}",
// This will color the log level only, not the whole line. Just a touch.
colors.color(record.level()),
message
))
})
.apply()
.unwrap();
}
2 changes: 1 addition & 1 deletion ns2-stat-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ fn main() {
if let Some(players) = args.teams {
teams::suggest_teams(games, &players, args.marine_com, args.alien_com);
} else {
print_stats(NS2Stats::compute(games));
print_stats(NS2Stats::compute(games).expect("No stats found"));
}
}

Expand Down
2 changes: 1 addition & 1 deletion ns2-stat/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ license = "MIT"
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
serde_repr = "0.1"
serde_repr = "0.1"
Copy link
Contributor

@konsumlamm konsumlamm Mar 9, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you readd the trailing newline?

Loading