Skip to content

Commit

Permalink
wip: scoreboard
Browse files Browse the repository at this point in the history
  • Loading branch information
ElaBosak233 committed Dec 16, 2024
1 parent d8f0f12 commit bb74a5b
Show file tree
Hide file tree
Showing 30 changed files with 432 additions and 437 deletions.
3 changes: 1 addition & 2 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ fn main() {

println!(
"cargo:rustc-env=BUILD_AT={}",
chrono::Utc::now()
.format("%Y-%m-%d %H:%M:%S UTC")
chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")
);
}
39 changes: 10 additions & 29 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,11 @@ pub mod site;
pub mod traits;

use futures_util::StreamExt;
use once_cell::sync::Lazy;
use sea_orm::EntityTrait;
use serde::{Deserialize, Serialize};
use tokio::sync::RwLock;
use tracing::info;

use crate::db::get_db;

pub static APP_CONFIG: Lazy<RwLock<Config>> = Lazy::new(|| RwLock::new(Config::default()));

#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct Config {
pub site: site::Config,
Expand All @@ -32,33 +27,19 @@ impl From<crate::db::entity::config::Model> for Config {
}

pub async fn init() {
tokio::spawn(async move {
let mut messages = crate::queue::subscribe("config").await.unwrap();
while let Some(result) = messages.next().await {
if result.is_err() {
continue;
}
let message = result.unwrap();
let _ = String::from_utf8(message.payload.to_vec()).unwrap();
sync().await;
message.ack().await.unwrap();
let config = crate::cache::get::<Config>("config").await.unwrap();
if config.is_none() {
let model = crate::db::entity::config::Entity::find()
.one(get_db())
.await
.unwrap();
if let Some(model) = model {
let _ = crate::cache::set("config", Config::from(model.clone())).await;
}
});
sync().await;
info!("Configuration synchronizer initialized successfully.");
}

pub async fn sync() {
let config = crate::db::entity::config::Entity::find()
.one(get_db())
.await
.unwrap();
if let Some(config) = config {
*APP_CONFIG.write().await = config.into();
}
}

pub async fn get_config() -> Config {
let config = APP_CONFIG.read().await;
config.clone()
let config = crate::cache::get::<Config>("config").await.unwrap();
config.clone().unwrap()
}
1 change: 0 additions & 1 deletion src/config/site/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use sea_orm::FromJsonQueryResult;
use serde::{Deserialize, Serialize};


#[derive(Clone, Debug, Serialize, Deserialize, FromJsonQueryResult, PartialEq, Eq, Default)]
pub struct Config {
pub title: String,
Expand Down
4 changes: 2 additions & 2 deletions src/db/entity/challenge.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use async_trait::async_trait;
use sea_orm::{
ActiveModelBehavior, ActiveModelTrait, ColumnTrait, ConnectionTrait, DbErr, DeriveActiveEnum,
DeriveEntityModel, DerivePrimaryKey, EntityTrait, EnumIter, FromJsonQueryResult, PrimaryKeyTrait, Related, RelationDef, RelationTrait,
Set,
DeriveEntityModel, DerivePrimaryKey, EntityTrait, EnumIter, FromJsonQueryResult,
PrimaryKeyTrait, Related, RelationDef, RelationTrait, Set,
};
use serde::{Deserialize, Serialize};
use serde_repr::{Deserialize_repr, Serialize_repr};
Expand Down
2 changes: 1 addition & 1 deletion src/db/entity/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ impl ActiveModelBehavior for ActiveModel {
async fn after_save<C>(model: Model, _db: &C, _insert: bool) -> Result<Model, DbErr>
where
C: ConnectionTrait, {
let _ = crate::queue::publish("config", "").await.unwrap();
let _ = crate::cache::set("config", crate::config::Config::from(model.clone())).await;
Ok(model)
}
}
4 changes: 3 additions & 1 deletion src/db/migration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ where
let schema = Schema::new(builder);
let stmt = builder.build(schema.create_table_from_entity(entity).if_not_exists());

if let Err(e) = db.execute(stmt).await { error!("Error: {}", e) }
if let Err(e) = db.execute(stmt).await {
error!("Error: {}", e)
}
}

pub async fn migrate(db: &DbConn) {
Expand Down
2 changes: 1 addition & 1 deletion src/db/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ pub async fn init_config() {
let config = entity::config::ActiveModel {
auth: Set(crate::config::auth::Config {
jwt: crate::config::auth::jwt::Config {
secret_key: String::from("123456"),
secret_key: String::from(uuid::Uuid::new_v4()),
expiration: 1800,
},
registration: crate::config::auth::registration::Config {
Expand Down
4 changes: 1 addition & 3 deletions src/db/transfer/game_challenge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,7 @@ impl From<entity::game_challenge::Model> for GameChallenge {
}
}

async fn preload(
models: Vec<entity::game_challenge::Model>,
) -> Result<Vec<GameChallenge>, DbErr> {
async fn preload(models: Vec<entity::game_challenge::Model>) -> Result<Vec<GameChallenge>, DbErr> {
let challenges = models
.load_one(entity::challenge::Entity, get_db())
.await?
Expand Down
37 changes: 34 additions & 3 deletions src/db/transfer/game_team.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use sea_orm::entity::prelude::*;
use std::str::FromStr;

use sea_orm::{entity::prelude::*, Order, QueryOrder, QuerySelect};
use serde::{Deserialize, Serialize};

use super::{team, Game, Team};
use super::{team, Game, Submission, Team};
use crate::db::{entity, get_db};

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
Expand Down Expand Up @@ -50,7 +52,8 @@ async fn preload(mut game_teams: Vec<GameTeam>) -> Result<Vec<GameTeam>, DbErr>
}

pub async fn find(
game_id: Option<i64>, team_id: Option<i64>,
game_id: Option<i64>, team_id: Option<i64>, is_allowed: Option<bool>, sorts: Option<String>,
page: Option<u64>, size: Option<u64>,
) -> Result<(Vec<GameTeam>, u64), DbErr> {
let mut sql = entity::game_team::Entity::find();

Expand All @@ -62,8 +65,36 @@ pub async fn find(
sql = sql.filter(entity::game_team::Column::TeamId.eq(team_id));
}

if let Some(is_allowed) = is_allowed {
sql = sql.filter(entity::game_team::Column::IsAllowed.eq(is_allowed));
}

if let Some(sorts) = sorts {
let sorts = sorts.split(",").collect::<Vec<&str>>();
for sort in sorts {
let col = match crate::db::entity::game_team::Column::from_str(
sort.replace("-", "").as_str(),
) {
Ok(col) => col,
Err(_) => return Err(DbErr::Custom("invalid sort column".to_string())),
};
if sort.starts_with("-") {
sql = sql.order_by(col, Order::Desc);
} else {
sql = sql.order_by(col, Order::Asc);
}
}
}

let total = sql.clone().count(get_db()).await?;

if let Some(page) = page {
if let Some(size) = size {
let offset = (page - 1) * size;
sql = sql.offset(offset).limit(size);
}
}

let game_teams = sql.all(get_db()).await?;
let mut game_teams = game_teams
.into_iter()
Expand Down
5 changes: 1 addition & 4 deletions src/db/transfer/pod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,10 +148,7 @@ pub async fn find(
let total = sql.clone().count(get_db()).await?;

let pods = sql.all(get_db()).await?;
let mut pods = pods
.into_iter()
.map(Pod::from)
.collect::<Vec<Pod>>();
let mut pods = pods.into_iter().map(Pod::from).collect::<Vec<Pod>>();

pods = preload(pods).await?;

Expand Down
27 changes: 26 additions & 1 deletion src/db/transfer/submission.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use sea_orm::{entity::prelude::*, QueryOrder, QuerySelect};
use sea_orm::{entity::prelude::*, Condition, QueryOrder, QuerySelect};
use serde::{Deserialize, Serialize};

use super::{Challenge, Game, Team, User};
Expand Down Expand Up @@ -185,3 +185,28 @@ pub async fn get_by_challenge_ids(challenge_ids: Vec<i64>) -> Result<Vec<Submiss
submissions = preload(submissions).await?;
Ok(submissions)
}

pub async fn get_by_game_id_and_team_ids(
game_id: i64, team_ids: Vec<i64>, status: Option<Status>,
) -> Result<Vec<Submission>, DbErr> {
let mut sql = entity::submission::Entity::find().filter(
Condition::all()
.add(entity::submission::Column::GameId.eq(game_id))
.add(entity::submission::Column::TeamId.is_in(team_ids)),
);

if let Some(status) = status {
sql = sql.filter(entity::submission::Column::Status.eq(status));
}

let submissions = sql.all(get_db()).await?;

let mut submissions = submissions
.into_iter()
.map(Submission::from)
.collect::<Vec<Submission>>();

submissions = preload(submissions).await?;

Ok(submissions)
}
7 changes: 1 addition & 6 deletions src/db/transfer/team.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,7 @@ async fn preload(mut teams: Vec<Team>) -> Result<Vec<Team>, DbErr> {
.load_many_to_many(entity::user::Entity, entity::user_team::Entity, get_db())
.await?
.into_iter()
.map(|users| {
users
.into_iter()
.map(User::from)
.collect::<Vec<User>>()
})
.map(|users| users.into_iter().map(User::from).collect::<Vec<User>>())
.collect::<Vec<Vec<User>>>();

for (i, team) in teams.iter_mut().enumerate() {
Expand Down
7 changes: 1 addition & 6 deletions src/db/transfer/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,7 @@ async fn preload(mut users: Vec<User>) -> Result<Vec<User>, DbErr> {
.load_many_to_many(entity::team::Entity, entity::user_team::Entity, get_db())
.await?
.into_iter()
.map(|teams| {
teams
.into_iter()
.map(Team::from)
.collect::<Vec<Team>>()
})
.map(|teams| teams.into_iter().map(Team::from).collect::<Vec<Team>>())
.collect::<Vec<Vec<Team>>>();

for (i, user) in users.iter_mut().enumerate() {
Expand Down
4 changes: 2 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,10 @@ async fn bootstrap() {
logger::init().await;
env::init().await;
queue::init().await;
db::init().await;
cache::init().await;
cluster::init().await;
db::init().await;
config::init().await;
cluster::init().await;
web::init().await;

let addr = format!("{}:{}", env::get_env().axum.host, env::get_env().axum.port);
Expand Down
2 changes: 1 addition & 1 deletion src/media/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ pub async fn delete(path: String, filename: String) -> Result<(), MediaError> {
Ok(())
}

pub async fn delete_dir(path: String) -> Result<(), Box<dyn Error>> {
pub async fn delete_dir(path: String) -> Result<(), MediaError> {
let filepath = PathBuf::from(crate::env::consts::path::MEDIA).join(path);
if metadata(&filepath).await.is_ok() {
remove_dir_all(&filepath).await?;
Expand Down
1 change: 1 addition & 0 deletions src/web/middleware/error.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use axum::response::IntoResponse;
use serde_json::json;

use crate::web::traits::WebError;

pub async fn validation_error(err: validator::ValidationError) -> impl IntoResponse {}
Expand Down
39 changes: 27 additions & 12 deletions src/web/middleware/mod.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,30 @@
pub mod error;

use std::net::SocketAddr;
use axum::body::Body;
use axum::extract::{ConnectInfo, Request};
use axum::http::header::COOKIE;
use axum::middleware::Next;
use axum::response::Response;

use axum::{
body::Body,
extract::{ConnectInfo, Request},
http::header::COOKIE,
middleware::Next,
response::Response,
};
use jsonwebtoken::{decode, DecodingKey, Validation};
use sea_orm::EntityTrait;
use serde_json::json;
use crate::db::entity::user::Group;
use crate::db::get_db;
use crate::web;
use crate::web::traits::{Ext, WebError};

use crate::{
db::{entity::user::Group, get_db},
web,
web::traits::{Ext, WebError},
};

pub async fn auth(mut req: Request<Body>, next: Next) -> Result<Response, WebError> {
let mut ext = req.extensions().get::<Ext>().unwrap_or(&Ext::default()).to_owned();
let mut ext = req
.extensions()
.get::<Ext>()
.unwrap_or(&Ext::default())
.to_owned();

let cookies = req
.headers()
Expand Down Expand Up @@ -61,11 +70,17 @@ pub async fn auth(mut req: Request<Body>, next: Next) -> Result<Response, WebErr

ext.operator = user;

req.extensions_mut().insert(ext);

Ok(next.run(req).await)
}

pub async fn network(mut req: Request<Body>, next: Next) -> Result<Response, WebError> {
let mut ext = req.extensions().get::<Ext>().unwrap_or(&Ext::default()).to_owned();
let mut ext = req
.extensions()
.get::<Ext>()
.unwrap_or(&Ext::default())
.to_owned();

let ConnectInfo(addr) = req.extensions().get::<ConnectInfo<SocketAddr>>().unwrap();

Expand All @@ -80,4 +95,4 @@ pub async fn network(mut req: Request<Body>, next: Next) -> Result<Response, Web
req.extensions_mut().insert(ext);

Ok(next.run(req).await)
}
}
Loading

0 comments on commit bb74a5b

Please sign in to comment.