Skip to content

Commit

Permalink
chore: entity and shared
Browse files Browse the repository at this point in the history
  • Loading branch information
ElaBosak233 committed Nov 20, 2024
1 parent a7f389c commit f6667c4
Show file tree
Hide file tree
Showing 51 changed files with 1,890 additions and 1,347 deletions.
8 changes: 4 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ serde_json = { version = "1.0" }
serde_repr = { version = "0.1" }

# Error Handling
thiserror = { version = "1.0" }
thiserror = { version = "2.0" }
anyhow = { version = "1.0" }

# Tracing
Expand All @@ -78,10 +78,10 @@ sea-orm = { version = "1.1", features = [
sea-orm-migration = { version = "1.1" }

# Message Queue
async-nats = { version = "0.37" }
async-nats = { version = "0.38" }

# Cache
fred = { version = "9.3", features = [
fred = { version = "9.4", features = [
"enable-rustls",
"dns",
"mocks",
Expand All @@ -98,7 +98,7 @@ k8s-openapi = { version = "0.23", features = ["latest"] }
# Miscellaneous
once_cell = { version = "1.20" }
prometheus = { version = "0.13" }
validator = { version = "0.18", features = ["derive"] }
validator = { version = "0.19", features = ["derive"] }
reqwest = { version = "0.12", features = [
"json",
"rustls-tls",
Expand Down
19 changes: 10 additions & 9 deletions src/cluster/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::{collections::BTreeMap, process, sync::OnceLock, time::Duration};

use axum::extract::ws::WebSocket;
use k8s_openapi::api::core::v1::{
Container as K8sContainer, ContainerPort, EnvVar, Pod, PodSpec, Service, ServicePort,
Expand All @@ -10,7 +12,6 @@ use kube::{
Client as K8sClient, Config,
};
use once_cell::sync::OnceCell;
use std::{collections::BTreeMap, process, sync::OnceLock, time::Duration};
use tokio_util::codec::Framed;
use tracing::{error, info};

Expand All @@ -24,9 +25,9 @@ pub async fn init() {
let result = Config::from_kubeconfig(&Default::default()).await;
if let Err(e) = result {
error!(
"Failed to create Kubernetes client from custom config: {:?}",
e
);
"Failed to create Kubernetes client from custom config: {:?}",
e
);
process::exit(1);
}
let config = result.unwrap();
Expand All @@ -40,9 +41,9 @@ pub async fn init() {
}

pub async fn create(
name: String, challenge: crate::model::challenge::Model,
injected_flag: crate::model::challenge::Flag,
) -> Result<Vec<crate::model::pod::Nat>, anyhow::Error> {
name: String, challenge: crate::shared::Challenge,
injected_flag: crate::db::entity::challenge::Flag,
) -> Result<Vec<crate::db::entity::pod::Nat>, anyhow::Error> {
let client = get_k8s_client().clone();

let metadata = k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta {
Expand Down Expand Up @@ -142,12 +143,12 @@ pub async fn create(

let service = service_api.get(&name).await?;

let mut nats: Vec<crate::model::pod::Nat> = Vec::new();
let mut nats: Vec<crate::db::entity::pod::Nat> = Vec::new();
if let Some(spec) = service.spec {
if let Some(ports) = spec.ports {
for port in ports {
if let Some(node_port) = port.node_port {
nats.push(crate::model::pod::Nat {
nats.push(crate::db::entity::pod::Nat {
src: format!("{}", port.port),
dst: Some(format!("{}", node_port)),
proxy: crate::env::get_env().cluster.proxy.enabled,
Expand Down
6 changes: 3 additions & 3 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ pub struct Config {
pub cluster: cluster::Config,
}

impl From<crate::model::config::Model> for Config {
fn from(config: crate::model::config::Model) -> Self {
impl From<crate::db::entity::config::Model> for Config {
fn from(config: crate::db::entity::config::Model) -> Self {
Config {
auth: config.auth,
cluster: config.cluster,
Expand All @@ -49,7 +49,7 @@ pub async fn init() {
}

pub async fn sync() {
let config = crate::model::config::Entity::find()
let config = crate::db::entity::config::Entity::find()
.one(get_db())
.await
.unwrap();
Expand Down
106 changes: 40 additions & 66 deletions src/model/challenge/mod.rs → src/db/entity/challenge.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
pub mod category;
pub mod env;
pub mod flag;

use axum::async_trait;
pub use category::Category;
pub use env::Env;
pub use flag::Flag;
use sea_orm::{entity::prelude::*, FromJsonQueryResult, QuerySelect, Set};
use async_trait::async_trait;
use sea_orm::{
ActiveModelBehavior, ActiveModelTrait, ColumnTrait, ConnectionTrait, DbErr, DeriveActiveEnum,
DeriveEntityModel, DerivePrimaryKey, EntityTrait, EnumIter, FromJsonQueryResult,
PaginatorTrait, PrimaryKeyTrait, QueryFilter, QuerySelect, Related, RelationDef, RelationTrait,
Set,
};
use serde::{Deserialize, Serialize};
use serde_repr::{Deserialize_repr, Serialize_repr};

use super::{game, game_challenge, pod, submission};
use crate::db::get_db;
Expand All @@ -19,7 +18,7 @@ pub struct Model {
pub id: i64,
pub title: String,
pub description: Option<String>,
pub category: Category,
pub category: i32,
pub tags: Vec<String>,
#[sea_orm(default_value = false)]
pub is_dynamic: bool,
Expand All @@ -44,14 +43,38 @@ pub struct Model {
}

#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, FromJsonQueryResult)]
pub struct Ports(pub Vec<i64>);
pub struct Env {
pub key: String,
pub value: String,
}

impl Model {
pub fn desensitize(&mut self) {
self.envs.clear();
self.ports.clear();
self.flags.clear();
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, FromJsonQueryResult)]
pub struct Flag {
#[serde(rename = "type")]
pub type_: FlagType,
pub banned: bool,
pub env: Option<String>,
pub value: String,
}

#[derive(
Clone,
Debug,
Default,
PartialEq,
Eq,
Serialize_repr,
Deserialize_repr,
EnumIter,
DeriveActiveEnum,
)]
#[sea_orm(rs_type = "i32", db_type = "Integer")]
#[repr(i32)]
pub enum FlagType {
#[default]
Static = 0,
Pattern = 1,
Dynamic = 2,
}

#[derive(Copy, Clone, Debug, EnumIter)]
Expand Down Expand Up @@ -102,52 +125,3 @@ impl ActiveModelBehavior for ActiveModel {
Ok(self)
}
}

pub async fn find(
id: Option<i64>, title: Option<String>, category: Option<Category>,
is_practicable: Option<bool>, is_dynamic: Option<bool>, page: Option<u64>, size: Option<u64>,
) -> Result<(Vec<Model>, u64), DbErr> {
let mut sql = Entity::find();

if let Some(id) = id {
sql = sql.filter(Column::Id.eq(id));
}

if let Some(title) = title {
sql = sql.filter(Column::Title.contains(title));
}

if let Some(category) = category {
sql = sql.filter(Column::Category.eq(category));
}

if let Some(is_practicable) = is_practicable {
sql = sql.filter(Column::IsPracticable.eq(is_practicable));
}

if let Some(is_dynamic) = is_dynamic {
sql = sql.filter(Column::IsDynamic.eq(is_dynamic));
}

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 challenges = sql.all(get_db()).await?;

Ok((challenges, total))
}

pub async fn find_by_ids(ids: Vec<i64>) -> Result<Vec<Model>, DbErr> {
let challenges = Entity::find()
.filter(Column::Id.is_in(ids))
.all(get_db())
.await?;

Ok(challenges)
}
File renamed without changes.
36 changes: 2 additions & 34 deletions src/model/game/mod.rs → src/db/entity/game.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use axum::async_trait;
use async_trait::async_trait;
use sea_orm::{entity::prelude::*, QuerySelect, Set};
use serde::{Deserialize, Serialize};

Expand All @@ -24,7 +24,7 @@ pub struct Model {
#[sea_orm(default_value = false)]
pub is_need_write_up: bool,
pub started_at: i64,
pub frozed_at: i64,
pub frozen_at: i64,
pub ended_at: i64,
pub created_at: i64,
pub updated_at: i64,
Expand Down Expand Up @@ -82,35 +82,3 @@ impl ActiveModelBehavior for ActiveModel {
Ok(self)
}
}

pub async fn find(
id: Option<i64>, title: Option<String>, is_enabled: Option<bool>, page: Option<u64>,
size: Option<u64>,
) -> Result<(Vec<Model>, u64), DbErr> {
let mut sql = Entity::find();

if let Some(id) = id {
sql = sql.filter(Column::Id.eq(id));
}

if let Some(title) = title {
sql = sql.filter(Column::Title.contains(title));
}

if let Some(is_enabled) = is_enabled {
sql = sql.filter(Column::IsEnabled.eq(is_enabled));
}

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 games = sql.all(get_db()).await?;

Ok((games, total))
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,6 @@ pub struct Model {

#[sea_orm(default_value = 0)]
pub pts: i64,

#[sea_orm(ignore)]
pub challenge: Option<challenge::Model>,
}

#[derive(Copy, Clone, Debug, EnumIter)]
Expand Down Expand Up @@ -83,41 +80,3 @@ impl Related<user::Entity> for Entity {

#[async_trait]
impl ActiveModelBehavior for ActiveModel {}

async fn preload(mut game_challenges: Vec<Model>) -> Result<Vec<Model>, DbErr> {
let challenges = game_challenges
.load_one(challenge::Entity, get_db())
.await?;

for (i, game_challenge) in game_challenges.iter_mut().enumerate() {
game_challenge.challenge = challenges[i].clone();
}

Ok(game_challenges)
}

pub async fn find(
game_id: Option<i64>, challenge_id: Option<i64>, is_enabled: Option<bool>,
) -> Result<(Vec<Model>, u64), DbErr> {
let mut sql = Entity::find();

if let Some(game_id) = game_id {
sql = sql.filter(Column::GameId.eq(game_id));
}

if let Some(challenge_id) = challenge_id {
sql = sql.filter(Column::ChallengeId.eq(challenge_id));
}

if let Some(is_enabled) = is_enabled {
sql = sql.filter(Column::IsEnabled.eq(is_enabled));
}

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

let mut game_challenges = sql.all(get_db()).await?;

game_challenges = preload(game_challenges).await?;

Ok((game_challenges, total))
}
47 changes: 47 additions & 0 deletions src/db/entity/game_team.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
use async_trait::async_trait;
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};

use super::{game, team};

#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "game_teams")]
pub struct Model {
#[sea_orm(primary_key)]
pub game_id: i64,
#[sea_orm(primary_key)]
pub team_id: i64,
#[sea_orm(default_value = false)]
pub is_allowed: bool,

#[sea_orm(default_value = 0)]
pub pts: i64,
#[sea_orm(default_value = 0)]
pub rank: i64,
}

#[derive(Copy, Clone, Debug, EnumIter)]
pub enum Relation {
Game,
Team,
}

impl RelationTrait for Relation {
fn def(&self) -> RelationDef {
match self {
Self::Game => Entity::belongs_to(game::Entity)
.from(Column::GameId)
.to(game::Column::Id)
.on_delete(ForeignKeyAction::Cascade)
.into(),
Self::Team => Entity::belongs_to(team::Entity)
.from(Column::TeamId)
.to(team::Column::Id)
.on_delete(ForeignKeyAction::Cascade)
.into(),
}
}
}

#[async_trait]
impl ActiveModelBehavior for ActiveModel {}
File renamed without changes.
Loading

0 comments on commit f6667c4

Please sign in to comment.