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 3 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
66 changes: 54 additions & 12 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,61 @@ 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();
Comeza marked this conversation as resolved.
Show resolved Hide resolved
let path = data.cli_args.data_path.join(&format!("{}.json", game.date()));
if path.exists() {
println!("Tried to write {path:?}, but file already exists -- skipping.");
konsumlamm marked this conversation as resolved.
Show resolved Hide resolved
return res;
}
fs::write(path, serde_json::to_string_pretty(&game).unwrap()).unwrap();
}

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();
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);
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 +168,14 @@ 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,

/// Wether the Webserver should copy new games (e.g. via /post/game) to `data_path`
Comeza marked this conversation as resolved.
Show resolved Hide resolved
#[clap(long, short)]
no_copy: bool,
}
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
165 changes: 117 additions & 48 deletions ns2-stat/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ use input_types::{GameStats, WinningTeam};

pub mod input_types;

pub trait Merge {
fn merge(&mut self, other: Self);
}

/// A wrapper around an `Iterator<Item = &GameStats>`.
pub struct Games<'a, I: Iterator<Item = &'a GameStats>>(pub I);

Expand Down Expand Up @@ -64,7 +68,7 @@ pub struct Map {
pub alien_wins: u32,
}

#[derive(Serialize)]
#[derive(Serialize, Default)]
pub struct NS2Stats {
pub latest_game: u32,
pub users: HashMap<String, User>,
Expand All @@ -74,65 +78,130 @@ pub struct NS2Stats {
pub alien_wins: u32,
}

impl NS2Stats {
pub fn compute<'a, I: Iterator<Item = &'a GameStats>>(games: Games<'a, I>) -> Self {
let mut users = HashMap::new();
let mut maps = HashMap::new();
let mut marine_wins = 0;
let mut alien_wins = 0;
let mut total_games = 0;
let mut latest_game = 0;

for game in games {
for player_stat in game.player_stats.values() {
let user = match users.get_mut(&player_stat.player_name) {
Some(user) => user,
None => users.entry(player_stat.player_name.clone()).or_insert_with(User::default),
};
user.total_games += 1;

for stats in [&player_stat.marines, &player_stat.aliens] {
user.kills += stats.kills;
user.assists += stats.assists;
user.deaths += stats.deaths;
}
}
impl Merge for User {
fn merge(&mut self, other: Self) {
self.total_games += other.total_games;
self.kills += other.kills;
self.assists += other.assists;
self.deaths += other.deaths;
self.kd = self.kills as f32 / self.deaths as f32;
self.kda = (self.kills + self.assists) as f32 / self.deaths as f32;
}
}

let map_entry = match maps.get_mut(&game.round_info.map_name) {
Some(map) => map,
None => maps.entry(game.round_info.map_name.clone()).or_insert_with(Map::default),
};
map_entry.total_games += 1;
match game.round_info.winning_team {
WinningTeam::Marines => {
map_entry.marine_wins += 1;
marine_wins += 1;
impl Merge for Map {
fn merge(&mut self, other: Self) {
self.total_games += other.total_games;
self.marine_wins += other.marine_wins;
self.alien_wins += other.alien_wins;
}
}

impl Merge for NS2Stats {
fn merge(&mut self, other: Self) {
self.total_games += other.total_games;
self.marine_wins += other.marine_wins;
self.alien_wins += other.marine_wins;
konsumlamm marked this conversation as resolved.
Show resolved Hide resolved

if self.latest_game < other.latest_game {
self.latest_game = other.latest_game
}

// There should be a better way for this
for (key, value) in other.users {
match self.users.get_mut(&key) {
Some(t) => {
t.merge(value);
}
konsumlamm marked this conversation as resolved.
Show resolved Hide resolved
WinningTeam::Aliens => {
map_entry.alien_wins += 1;
alien_wins += 1;
None => {
self.users.insert(key, value);
}
WinningTeam::None => {}
}
}

if game.round_info.round_date > latest_game {
latest_game = game.round_info.round_date;
for (key, value) in other.maps {
match self.maps.get_mut(&key) {
Some(t) => {
t.merge(value);
}
None => {
self.maps.insert(key, value);
}
}
konsumlamm marked this conversation as resolved.
Show resolved Hide resolved
total_games += 1;
}
}
}

for user in users.values_mut() {
user.kd = user.kills as f32 / user.deaths as f32;
user.kda = (user.kills + user.assists) as f32 / user.deaths as f32;
}
impl FromIterator<NS2Stats> for Option<NS2Stats> {
Comeza marked this conversation as resolved.
Show resolved Hide resolved
fn from_iter<T: IntoIterator<Item = NS2Stats>>(iter: T) -> Self {
iter.into_iter().reduce(|mut acc, item| {
acc.merge(item);
acc
})
}
}

Self {
latest_game,
impl From<GameStats> for NS2Stats {
fn from(gs: GameStats) -> Self {
(&gs).into()
konsumlamm marked this conversation as resolved.
Show resolved Hide resolved
}
}

impl From<&GameStats> for NS2Stats {
fn from(game: &GameStats) -> Self {
use std::collections::hash_map::Entry;
konsumlamm marked this conversation as resolved.
Show resolved Hide resolved
let mut stats = Self::default();

let Self {
users,
maps,
total_games,
marine_wins,
alien_wins,
latest_game,
marine_wins,
total_games,
} = &mut stats;

for player_stat in game.player_stats.values() {
let user = match users.entry(player_stat.player_name.clone()) {
Comeza marked this conversation as resolved.
Show resolved Hide resolved
Entry::Occupied(o) => o.into_mut(),
Entry::Vacant(v) => v.insert(User::default()),
};

user.total_games += 1;

for stats in [&player_stat.marines, &player_stat.aliens] {
user.kills += stats.kills;
user.assists += stats.assists;
user.deaths += stats.deaths;
}
}

let map_entry = match maps.entry(game.round_info.map_name.clone()) {
Entry::Occupied(o) => o.into_mut(),
Entry::Vacant(v) => v.insert(Map::default()),
};

map_entry.total_games += 1;
match game.round_info.winning_team {
WinningTeam::Marines => {
map_entry.marine_wins += 1;
*marine_wins += 1;
}
WinningTeam::Aliens => {
map_entry.alien_wins += 1;
*alien_wins += 1;
}
WinningTeam::None => {}
}

*latest_game = game.round_info.round_date;
*total_games += 1;
stats
Comeza marked this conversation as resolved.
Show resolved Hide resolved
}
}

impl NS2Stats {
pub fn compute<'a, I: Iterator<Item = &'a GameStats>>(games: Games<'a, I>) -> Option<Self> {
games.map(NS2Stats::from).collect()
}
}