From a7f389c3c13046c272f0b3aa702ec7d5bdaad078 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=9F=83=E6=8B=89?= Date: Sun, 17 Nov 2024 12:17:53 +0800 Subject: [PATCH] chore: once_lock to once_cell --- src/cluster/mod.rs | 28 +++++++------ src/config/mod.rs | 2 +- src/db/mod.rs | 14 +++---- src/env/mod.rs | 4 +- src/model/challenge/mod.rs | 6 +-- src/model/game/mod.rs | 4 +- src/model/game_challenge/mod.rs | 6 +-- src/model/game_team/mod.rs | 4 +- src/model/pod/mod.rs | 10 ++--- src/model/submission/mod.rs | 14 +++---- src/model/team/mod.rs | 10 ++--- src/model/user/mod.rs | 6 +-- src/model/user_team/mod.rs | 4 +- src/queue/mod.rs | 6 +-- src/web/middleware/auth.rs | 2 +- src/web/router/api/challenge/mod.rs | 6 +-- src/web/router/api/config/mod.rs | 2 +- src/web/router/api/game/calculator.rs | 16 ++++---- src/web/router/api/game/mod.rs | 20 ++++----- src/web/router/api/pod/daemon.rs | 4 +- src/web/router/api/pod/mod.rs | 14 +++---- src/web/router/api/submission/checker.rs | 18 ++++---- src/web/router/api/submission/mod.rs | 12 +++--- src/web/router/api/team/mod.rs | 52 +++++++++++++----------- src/web/router/api/user/mod.rs | 36 ++++++++-------- 25 files changed, 155 insertions(+), 145 deletions(-) diff --git a/src/cluster/mod.rs b/src/cluster/mod.rs index 38398d5e..b44115d2 100644 --- a/src/cluster/mod.rs +++ b/src/cluster/mod.rs @@ -1,5 +1,3 @@ -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, @@ -11,30 +9,34 @@ use kube::{ runtime::wait::conditions, 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}; -static K8S_CLIENT: OnceLock = OnceLock::new(); +static K8S_CLIENT: OnceCell = OnceCell::new(); pub fn get_k8s_client() -> &'static K8sClient { K8S_CLIENT.get().unwrap() } pub async fn init() { - match Config::from_kubeconfig(&Default::default()).await { - Ok(config) => { - let client = K8sClient::try_from(config).unwrap(); - let _ = K8S_CLIENT.set(client); - info!("Kubernetes client initialized successfully."); - } - Err(e) => { - error!( + let result = Config::from_kubeconfig(&Default::default()).await; + if let Err(e) = result { + error!( "Failed to create Kubernetes client from custom config: {:?}", e ); - process::exit(1); - } + process::exit(1); + } + let config = result.unwrap(); + let client = K8sClient::try_from(config).unwrap(); + if let Err(_) = client.apiserver_version().await { + error!("Failed to connect to Kubernetes API server."); + process::exit(1); } + let _ = K8S_CLIENT.set(client); + info!("Kubernetes client initialized successfully."); } pub async fn create( diff --git a/src/config/mod.rs b/src/config/mod.rs index fb79b658..86392902 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -50,7 +50,7 @@ pub async fn init() { pub async fn sync() { let config = crate::model::config::Entity::find() - .one(&get_db()) + .one(get_db()) .await .unwrap(); if let Some(config) = config { diff --git a/src/db/mod.rs b/src/db/mod.rs index 923b78eb..5e254ded 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -36,19 +36,19 @@ pub async fn init() { let db: DatabaseConnection = Database::connect(opt).await.unwrap(); DB.set(db).unwrap(); - migration::migrate(&get_db()).await; + migration::migrate(get_db()).await; info!("Database connection established successfully."); init_admin().await; init_config().await; } -pub fn get_db() -> DatabaseConnection { - DB.get().unwrap().clone() +pub fn get_db() -> &'static DatabaseConnection { + DB.get().unwrap() } pub async fn init_admin() { let total = crate::model::user::Entity::find() - .count(&get_db()) + .count(get_db()) .await .unwrap(); if total == 0 { @@ -64,14 +64,14 @@ pub async fn init_admin() { password: Set(hashed_password), ..Default::default() }; - user.insert(&get_db()).await.unwrap(); + user.insert(get_db()).await.unwrap(); info!("Admin user created successfully."); } } pub async fn init_config() { let total = crate::model::config::Entity::find() - .count(&get_db()) + .count(get_db()) .await .unwrap(); if total == 0 { @@ -105,7 +105,7 @@ pub async fn init_config() { }), ..Default::default() }; - config.insert(&get_db()).await.unwrap(); + config.insert(get_db()).await.unwrap(); info!("Default configuration created successfully."); } } diff --git a/src/env/mod.rs b/src/env/mod.rs index 0650796c..90ad3f1d 100644 --- a/src/env/mod.rs +++ b/src/env/mod.rs @@ -36,6 +36,6 @@ pub async fn init() { } } -pub fn get_env() -> Env { - APP_ENV.get().unwrap().clone() +pub fn get_env() -> &'static Env { + APP_ENV.get().unwrap() } diff --git a/src/model/challenge/mod.rs b/src/model/challenge/mod.rs index 33b49f27..942ec768 100644 --- a/src/model/challenge/mod.rs +++ b/src/model/challenge/mod.rs @@ -129,7 +129,7 @@ pub async fn find( sql = sql.filter(Column::IsDynamic.eq(is_dynamic)); } - let total = sql.clone().count(&get_db()).await?; + let total = sql.clone().count(get_db()).await?; if let Some(page) = page { if let Some(size) = size { @@ -138,7 +138,7 @@ pub async fn find( } } - let challenges = sql.all(&get_db()).await?; + let challenges = sql.all(get_db()).await?; Ok((challenges, total)) } @@ -146,7 +146,7 @@ pub async fn find( pub async fn find_by_ids(ids: Vec) -> Result, DbErr> { let challenges = Entity::find() .filter(Column::Id.is_in(ids)) - .all(&get_db()) + .all(get_db()) .await?; Ok(challenges) diff --git a/src/model/game/mod.rs b/src/model/game/mod.rs index 1c13fe31..11d37813 100644 --- a/src/model/game/mod.rs +++ b/src/model/game/mod.rs @@ -101,7 +101,7 @@ pub async fn find( sql = sql.filter(Column::IsEnabled.eq(is_enabled)); } - let total = sql.clone().count(&get_db()).await?; + let total = sql.clone().count(get_db()).await?; if let Some(page) = page { if let Some(size) = size { @@ -110,7 +110,7 @@ pub async fn find( } } - let games = sql.all(&get_db()).await?; + let games = sql.all(get_db()).await?; Ok((games, total)) } diff --git a/src/model/game_challenge/mod.rs b/src/model/game_challenge/mod.rs index 491b7c99..11a88181 100644 --- a/src/model/game_challenge/mod.rs +++ b/src/model/game_challenge/mod.rs @@ -86,7 +86,7 @@ impl ActiveModelBehavior for ActiveModel {} async fn preload(mut game_challenges: Vec) -> Result, DbErr> { let challenges = game_challenges - .load_one(challenge::Entity, &get_db()) + .load_one(challenge::Entity, get_db()) .await?; for (i, game_challenge) in game_challenges.iter_mut().enumerate() { @@ -113,9 +113,9 @@ pub async fn find( sql = sql.filter(Column::IsEnabled.eq(is_enabled)); } - let total = sql.clone().count(&get_db()).await?; + let total = sql.clone().count(get_db()).await?; - let mut game_challenges = sql.all(&get_db()).await?; + let mut game_challenges = sql.all(get_db()).await?; game_challenges = preload(game_challenges).await?; diff --git a/src/model/game_team/mod.rs b/src/model/game_team/mod.rs index 36484acc..2cc529fa 100644 --- a/src/model/game_team/mod.rs +++ b/src/model/game_team/mod.rs @@ -91,9 +91,9 @@ pub async fn find(game_id: Option, team_id: Option) -> Result<(Vec) -> Result, DbErr> { - let users = pods.load_one(user::Entity, &get_db()).await?; - let teams = pods.load_one(team::Entity, &get_db()).await?; - let challenges = pods.load_one(challenge::Entity, &get_db()).await?; + let users = pods.load_one(user::Entity, get_db()).await?; + let teams = pods.load_one(team::Entity, get_db()).await?; + let challenges = pods.load_one(challenge::Entity, get_db()).await?; for (i, pod) in pods.iter_mut().enumerate() { pod.user = users[i].clone(); @@ -156,9 +156,9 @@ pub async fn find( } } - let total = sql.clone().count(&get_db()).await?; + let total = sql.clone().count(get_db()).await?; - let mut pods = sql.all(&get_db()).await?; + let mut pods = sql.all(get_db()).await?; pods = preload(pods).await?; diff --git a/src/model/submission/mod.rs b/src/model/submission/mod.rs index 80c5fa52..4bf83abf 100644 --- a/src/model/submission/mod.rs +++ b/src/model/submission/mod.rs @@ -121,10 +121,10 @@ impl ActiveModelBehavior for ActiveModel { } async fn preload(mut submissions: Vec) -> Result, DbErr> { - let users = submissions.load_one(user::Entity, &get_db()).await?; - let challenges = submissions.load_one(challenge::Entity, &get_db()).await?; - let teams = submissions.load_one(team::Entity, &get_db()).await?; - let games = submissions.load_one(game::Entity, &get_db()).await?; + let users = submissions.load_one(user::Entity, get_db()).await?; + let challenges = submissions.load_one(challenge::Entity, get_db()).await?; + let teams = submissions.load_one(team::Entity, get_db()).await?; + let games = submissions.load_one(game::Entity, get_db()).await?; for (i, submission) in submissions.iter_mut().enumerate() { submission.user = users[i].clone(); @@ -174,7 +174,7 @@ pub async fn find( sql = sql.filter(Column::Status.eq(status)); } - let total = sql.clone().count(&get_db()).await?; + let total = sql.clone().count(get_db()).await?; if let Some(page) = page { if let Some(size) = size { @@ -183,7 +183,7 @@ pub async fn find( } } - let mut submissions = sql.all(&get_db()).await?; + let mut submissions = sql.all(get_db()).await?; submissions = preload(submissions).await?; @@ -194,7 +194,7 @@ pub async fn get_by_challenge_ids(challenge_ids: Vec) -> Result, let mut submissions = Entity::find() .filter(Column::ChallengeId.is_in(challenge_ids)) .order_by_asc(Column::CreatedAt) - .all(&get_db()) + .all(get_db()) .await?; submissions = preload(submissions).await?; Ok(submissions) diff --git a/src/model/team/mod.rs b/src/model/team/mod.rs index 84b15827..5c158869 100644 --- a/src/model/team/mod.rs +++ b/src/model/team/mod.rs @@ -95,7 +95,7 @@ impl ActiveModelBehavior for ActiveModel { async fn preload(mut teams: Vec) -> Result, DbErr> { let users = teams - .load_many_to_many(user::Entity, user_team::Entity, &get_db()) + .load_many_to_many(user::Entity, user_team::Entity, get_db()) .await?; for (i, team) in teams.iter_mut().enumerate() { @@ -129,7 +129,7 @@ pub async fn find( sql = sql.filter(Column::Email.eq(email)); } - let total = sql.clone().count(&get_db()).await?; + let total = sql.clone().count(get_db()).await?; if let Some(page) = page { if let Some(size) = size { @@ -138,7 +138,7 @@ pub async fn find( } } - let mut teams = sql.all(&get_db()).await?; + let mut teams = sql.all(get_db()).await?; teams = preload(teams).await?; @@ -148,7 +148,7 @@ pub async fn find( pub async fn find_by_ids(ids: Vec) -> Result, DbErr> { let mut teams = Entity::find() .filter(Column::Id.is_in(ids)) - .all(&get_db()) + .all(get_db()) .await?; teams = preload(teams).await?; @@ -163,7 +163,7 @@ pub async fn find_by_user_id(id: i64) -> Result, DbErr> { .filter(user_team::Column::UserId.eq(id)) .join(JoinType::InnerJoin, user_team::Relation::Team.def()) .into_model::() - .all(&get_db()) + .all(get_db()) .await?; teams = preload(teams).await?; diff --git a/src/model/user/mod.rs b/src/model/user/mod.rs index 4c200db9..400dfeca 100644 --- a/src/model/user/mod.rs +++ b/src/model/user/mod.rs @@ -85,7 +85,7 @@ impl ActiveModelBehavior for ActiveModel { async fn preload(mut users: Vec) -> Result, DbErr> { let teams = users - .load_many_to_many(team::Entity, user_team::Entity, &get_db()) + .load_many_to_many(team::Entity, user_team::Entity, get_db()) .await?; for (i, user) in users.iter_mut().enumerate() { @@ -125,7 +125,7 @@ pub async fn find( sql = sql.filter(Column::Email.eq(email)); } - let total = sql.clone().count(&get_db()).await?; + let total = sql.clone().count(get_db()).await?; if let Some(page) = page { if let Some(size) = size { @@ -134,7 +134,7 @@ pub async fn find( } } - let mut users = sql.all(&get_db()).await?; + let mut users = sql.all(get_db()).await?; users = preload(users).await?; diff --git a/src/model/user_team/mod.rs b/src/model/user_team/mod.rs index 062e10bb..727e973b 100644 --- a/src/model/user_team/mod.rs +++ b/src/model/user_team/mod.rs @@ -51,9 +51,9 @@ pub async fn find(user_id: Option, team_id: Option) -> Result<(Vec = OnceCell::new(); -fn get_client() -> async_nats::Client { - CLIENT.get().unwrap().clone() +fn get_client() -> &'static async_nats::Client { + CLIENT.get().unwrap() } fn get_jetstream() -> async_nats::jetstream::Context { - let client = get_client(); + let client = get_client().to_owned(); async_nats::jetstream::new(client) } diff --git a/src/web/middleware/auth.rs b/src/web/middleware/auth.rs index eef2eb9c..c92e0dcb 100644 --- a/src/web/middleware/auth.rs +++ b/src/web/middleware/auth.rs @@ -47,7 +47,7 @@ pub async fn jwt(mut req: Request, next: Next) -> Result base_pts, }); submission.rank = Set(rank as i64 + 1); - submission.update(&get_db()).await.unwrap(); + submission.update(get_db()).await.unwrap(); } let pts = match submissions.len() { @@ -83,7 +83,7 @@ pub async fn calculate(game_id: i64) { }; let mut game_challenge = game_challenge.into_active_model(); game_challenge.pts = Set(pts); - game_challenge.update(&get_db()).await.unwrap(); + game_challenge.update(get_db()).await.unwrap(); } // calculate pts and rank for each game_team @@ -93,7 +93,7 @@ pub async fn calculate(game_id: i64) { .add(crate::model::submission::Column::GameId.eq(game_id)) .add(crate::model::submission::Column::Status.eq(Status::Correct)), ) - .all(&get_db()) + .all(get_db()) .await .unwrap(); @@ -103,7 +103,7 @@ pub async fn calculate(game_id: i64) { .add(crate::model::game_team::Column::GameId.eq(game_id)) .add(crate::model::game_team::Column::IsAllowed.eq(true)), ) - .all(&get_db()) + .all(get_db()) .await .unwrap(); @@ -124,7 +124,7 @@ pub async fn calculate(game_id: i64) { let mut game_team = game_team.clone().into_active_model(); game_team.rank = Set(rank as i64 + 1); game_team.pts = Set(pts); - game_team.update(&get_db()).await.unwrap(); + game_team.update(get_db()).await.unwrap(); } } @@ -143,7 +143,7 @@ pub async fn init() { calculate(game_id).await; } else { let games = crate::model::game::Entity::find() - .all(&get_db()) + .all(get_db()) .await .unwrap(); for game in games { diff --git a/src/web/router/api/game/mod.rs b/src/web/router/api/game/mod.rs index 2e658a12..f52eff6f 100644 --- a/src/web/router/api/game/mod.rs +++ b/src/web/router/api/game/mod.rs @@ -147,7 +147,7 @@ pub async fn create( ..Default::default() } - .insert(&get_db()) + .insert(get_db()) .await?; Ok(WebResult { @@ -202,7 +202,7 @@ pub async fn update( frozed_at: body.frozed_at.map_or(NotSet, |v| Set(v)), ..Default::default() } - .update(&get_db()) + .update(get_db()) .await?; Ok(WebResult { @@ -221,7 +221,7 @@ pub async fn delete( } let _ = crate::model::game::Entity::delete_by_id(id) - .exec(&get_db()) + .exec(get_db()) .await?; Ok(WebResult { @@ -287,7 +287,7 @@ pub async fn create_challenge( third_blood_reward_ratio: body.third_blood_reward_ratio.map_or(NotSet, |v| Set(v)), ..Default::default() } - .insert(&get_db()) + .insert(get_db()) .await?; Ok(WebResult { @@ -334,7 +334,7 @@ pub async fn update_challenge( third_blood_reward_ratio: body.third_blood_reward_ratio.map_or(NotSet, |v| Set(v)), ..Default::default() } - .update(&get_db()) + .update(get_db()) .await?; Ok(WebResult { @@ -355,7 +355,7 @@ pub async fn delete_challenge( let _ = crate::model::game_challenge::Entity::delete_many() .filter(crate::model::game_challenge::Column::GameId.eq(id)) .filter(crate::model::game_challenge::Column::ChallengeId.eq(challenge_id)) - .exec(&get_db()) + .exec(get_db()) .await?; Ok(WebResult { @@ -405,7 +405,7 @@ pub async fn create_team( ..Default::default() } - .insert(&get_db()) + .insert(get_db()) .await?; Ok(WebResult { @@ -440,7 +440,7 @@ pub async fn update_team( is_allowed: body.is_allowed.map_or(NotSet, |v| Set(v)), ..Default::default() } - .update(&get_db()) + .update(get_db()) .await?; Ok(WebResult { @@ -461,7 +461,7 @@ pub async fn delete_team( let _ = crate::model::game_team::Entity::delete_many() .filter(crate::model::game_team::Column::GameId.eq(id)) .filter(crate::model::game_team::Column::TeamId.eq(team_id)) - .exec(&get_db()) + .exec(get_db()) .await?; Ok(WebResult { @@ -530,7 +530,7 @@ pub async fn calculate( // .add(crate::model::game_team::Column::GameId.eq(id)) // .add(crate::model::game_team::Column::IsAllowed.eq(true)), // ) -// .all(&get_db()) +// .all(get_db()) // .await?; // return Ok(()); diff --git a/src/web/router/api/pod/daemon.rs b/src/web/router/api/pod/daemon.rs index 463af443..d3703440 100644 --- a/src/web/router/api/pod/daemon.rs +++ b/src/web/router/api/pod/daemon.rs @@ -11,13 +11,13 @@ pub async fn init() { loop { let pods = crate::model::pod::Entity::find() .filter(crate::model::pod::Column::RemovedAt.lte(chrono::Utc::now().timestamp())) - .all(&get_db()) + .all(get_db()) .await .unwrap(); for pod in pods { cluster::delete(pod.name.clone()).await; crate::model::pod::Entity::delete_by_id(pod.id) - .exec(&get_db()) + .exec(get_db()) .await .unwrap(); info!("Cleaned up expired cluster: {0}", pod.name); diff --git a/src/web/router/api/pod/mod.rs b/src/web/router/api/pod/mod.rs index f5b54ef8..a91ba73d 100644 --- a/src/web/router/api/pod/mod.rs +++ b/src/web/router/api/pod/mod.rs @@ -89,7 +89,7 @@ pub async fn create( body.user_id = Some(operator.id); let challenge = crate::model::challenge::Entity::find_by_id(body.challenge_id) - .one(&get_db()) + .one(get_db()) .await?; let challenge = challenge.ok_or(WebError::BadRequest(String::from("challenge_not_found")))?; @@ -124,7 +124,7 @@ pub async fn create( nats: Set(nats), ..Default::default() } - .insert(&get_db()) + .insert(get_db()) .await?; pod.desensitize(); @@ -157,20 +157,20 @@ pub async fn renew( let pod = crate::model::pod::Entity::find() .filter(crate::model::pod::Column::Id.eq(id)) - .one(&get_db()) + .one(get_db()) .await? .ok_or_else(|| WebError::NotFound(String::new()))?; check_permission!(operator, pod); let challenge = crate::model::challenge::Entity::find_by_id(pod.challenge_id) - .one(&get_db()) + .one(get_db()) .await?; let challenge = challenge.unwrap(); let mut pod = pod.clone().into_active_model(); pod.removed_at = Set(chrono::Utc::now().timestamp() + challenge.duration); - let _ = pod.update(&get_db()).await; + let _ = pod.update(get_db()).await; Ok(WebResult { code: StatusCode::OK.as_u16(), @@ -184,7 +184,7 @@ pub async fn stop( let operator = ext.operator.ok_or(WebError::Unauthorized(String::new()))?; let pod = crate::model::pod::Entity::find_by_id(id) - .one(&get_db()) + .one(get_db()) .await? .ok_or_else(|| WebError::NotFound(String::new()))?; @@ -198,7 +198,7 @@ pub async fn stop( let mut pod = pod.clone().into_active_model(); pod.removed_at = Set(chrono::Utc::now().timestamp()); - let _ = pod.update(&get_db()).await?; + let _ = pod.update(get_db()).await?; Ok(WebResult { code: StatusCode::OK.as_u16(), diff --git a/src/web/router/api/submission/checker.rs b/src/web/router/api/submission/checker.rs index 34088168..c6e24e76 100644 --- a/src/web/router/api/submission/checker.rs +++ b/src/web/router/api/submission/checker.rs @@ -17,7 +17,7 @@ async fn check(id: i64) { .add(crate::model::submission::Column::Id.eq(id)) .add(crate::model::submission::Column::Status.eq(Status::Pending)), ) - .one(&get_db()) + .one(get_db()) .await .unwrap(); @@ -28,13 +28,13 @@ async fn check(id: i64) { let submission = submission.unwrap(); let user = crate::model::user::Entity::find_by_id(submission.user_id) - .one(&get_db()) + .one(get_db()) .await .unwrap(); if user.is_none() { crate::model::submission::Entity::delete_by_id(submission.id) - .exec(&get_db()) + .exec(get_db()) .await .unwrap(); return; @@ -44,13 +44,13 @@ async fn check(id: i64) { // Get related challenge let challenge = crate::model::challenge::Entity::find_by_id(submission.challenge_id) - .one(&get_db()) + .one(get_db()) .await .unwrap(); if challenge.is_none() { crate::model::submission::Entity::delete_by_id(submission.id) - .exec(&get_db()) + .exec(get_db()) .await .unwrap(); return; @@ -67,7 +67,7 @@ async fn check(id: i64) { })) .add(crate::model::submission::Column::Status.eq(Status::Correct)), ) - .all(&get_db()) + .all(get_db()) .await .unwrap(); @@ -88,7 +88,7 @@ async fn check(id: i64) { Condition::all().add(crate::model::pod::Column::GameId.eq(game_id)) })), ) - .all(&get_db()) + .all(get_db()) .await .unwrap(); @@ -136,7 +136,7 @@ async fn check(id: i64) { let mut submission_active_model = submission.clone().into_active_model(); submission_active_model.status = Set(status.clone()); - submission_active_model.update(&get_db()).await.unwrap(); + submission_active_model.update(get_db()).await.unwrap(); if submission.game_id.is_some() && status == Status::Correct { crate::queue::publish( @@ -154,7 +154,7 @@ async fn recover() { let unchecked_submissions = crate::model::submission::Entity::find() .filter(crate::model::submission::Column::Status.eq(Status::Pending)) .order_by_asc(crate::model::submission::Column::CreatedAt) - .all(&get_db()) + .all(get_db()) .await .unwrap(); diff --git a/src/web/router/api/submission/mod.rs b/src/web/router/api/submission/mod.rs index 1cc42388..1367bf22 100644 --- a/src/web/router/api/submission/mod.rs +++ b/src/web/router/api/submission/mod.rs @@ -79,7 +79,7 @@ pub async fn get_by_id( let _ = ext.operator.ok_or(WebError::Unauthorized(String::new()))?; let submission = crate::model::submission::Entity::find_by_id(id) - .one(&get_db()) + .one(get_db()) .await?; if submission.is_none() { @@ -114,7 +114,7 @@ pub async fn create( if let Some(challenge_id) = body.challenge_id { let challenge = crate::model::challenge::Entity::find_by_id(challenge_id) - .one(&get_db()) + .one(get_db()) .await?; if challenge.is_none() { @@ -124,7 +124,7 @@ pub async fn create( if let Some(game_id) = body.game_id { let game = crate::model::game::Entity::find_by_id(game_id) - .one(&get_db()) + .one(get_db()) .await?; if game.is_none() { @@ -134,7 +134,7 @@ pub async fn create( if let Some(team_id) = body.team_id { let team = crate::model::team::Entity::find_by_id(team_id) - .one(&get_db()) + .one(get_db()) .await?; if team.is_none() { @@ -151,7 +151,7 @@ pub async fn create( status: Set(Status::Pending), ..Default::default() } - .insert(&get_db()) + .insert(get_db()) .await?; crate::queue::publish("checker", submission.id).await?; @@ -172,7 +172,7 @@ pub async fn delete( } let _ = crate::model::submission::Entity::delete_by_id(id) - .exec(&get_db()) + .exec(get_db()) .await?; Ok(WebResult { diff --git a/src/web/router/api/team/mod.rs b/src/web/router/api/team/mod.rs index e0e65074..ce26b3ba 100644 --- a/src/web/router/api/team/mod.rs +++ b/src/web/router/api/team/mod.rs @@ -5,10 +5,10 @@ use axum::{ response::IntoResponse, Extension, Json, Router, }; -use mime::Mime; +use sea_orm::ActiveValue::Set; use sea_orm::{ ActiveModelTrait, ActiveValue::NotSet, ColumnTrait, EntityTrait, IntoActiveModel, QueryFilter, - QuerySelect, Set, + QuerySelect, }; use serde::{Deserialize, Serialize}; use validator::Validate; @@ -52,9 +52,9 @@ pub fn router() -> Router { fn can_modify_team(user: crate::model::user::Model, team_id: i64) -> bool { user.group == Group::Admin || user - .teams - .iter() - .any(|team| team.id == team_id && team.captain_id == user.id) + .teams + .iter() + .any(|team| team.id == team_id && team.captain_id == user.id) } #[derive(Clone, Debug, Serialize, Deserialize, Default)] @@ -77,7 +77,7 @@ pub async fn get( params.page, params.size, ) - .await?; + .await?; Ok(WebResult { code: StatusCode::OK.as_u16(), @@ -110,16 +110,16 @@ pub async fn create( slogan: body.slogan.map_or(NotSet, |v| Set(Some(v))), ..Default::default() } - .insert(&get_db()) - .await?; + .insert(get_db()) + .await?; let _ = crate::model::user_team::ActiveModel { user_id: Set(body.captain_id), team_id: Set(team.id), ..Default::default() } - .insert(&get_db()) - .await?; + .insert(get_db()) + .await?; Ok(WebResult { code: StatusCode::OK.as_u16(), @@ -155,8 +155,8 @@ pub async fn update( slogan: body.slogan.map_or(NotSet, |v| Set(Some(v))), ..Default::default() } - .insert(&get_db()) - .await?; + .update(get_db()) + .await?; Ok(WebResult { code: StatusCode::OK.as_u16(), @@ -174,8 +174,12 @@ pub async fn delete( return Err(WebError::Forbidden(String::new())); } - let _ = crate::model::team::Entity::delete_by_id(id) - .exec(&get_db()) + let _ = crate::model::team::ActiveModel { + id: Set(id), + is_deleted: Set(true), + ..Default::default() + } + .update(get_db()) .await?; Ok(WebResult { @@ -202,8 +206,8 @@ pub async fn create_user( user_id: Set(body.user_id), team_id: Set(body.team_id), } - .insert(&get_db()) - .await?; + .insert(get_db()) + .await?; Ok(WebResult { code: StatusCode::OK.as_u16(), @@ -222,7 +226,7 @@ pub async fn delete_user( let _ = crate::model::user_team::Entity::delete_many() .filter(crate::model::user_team::Column::UserId.eq(user_id)) .filter(crate::model::user_team::Column::TeamId.eq(id)) - .exec(&get_db()) + .exec(get_db()) .await?; Ok(WebResult { @@ -243,7 +247,7 @@ pub async fn get_invite_token( let team = crate::model::team::Entity::find_by_id(id) .select_only() .column(crate::model::team::Column::InviteToken) - .one(&get_db()) + .one(get_db()) .await? .ok_or_else(|| WebError::NotFound(String::new()))?; @@ -263,7 +267,7 @@ pub async fn update_invite_token( } let mut team = crate::model::team::Entity::find_by_id(id) - .one(&get_db()) + .one(get_db()) .await? .ok_or_else(|| WebError::NotFound(String::new()))? .into_active_model(); @@ -271,7 +275,7 @@ pub async fn update_invite_token( let token = uuid::Uuid::new_v4().simple().to_string(); team.invite_token = Set(Some(token.clone())); - let _ = team.update(&get_db()).await?; + let _ = team.update(get_db()).await?; Ok(WebResult { code: StatusCode::OK.as_u16(), @@ -295,12 +299,12 @@ pub async fn join( body.user_id = operator.id; let _ = crate::model::user::Entity::find_by_id(body.user_id) - .one(&get_db()) + .one(get_db()) .await? .ok_or_else(|| WebError::NotFound(String::from("invalid_user_or_team")))?; let team = crate::model::team::Entity::find_by_id(body.team_id) - .one(&get_db()) + .one(get_db()) .await? .ok_or_else(|| WebError::NotFound(String::from("invalid_user_or_team")))?; @@ -313,8 +317,8 @@ pub async fn join( team_id: Set(body.team_id), ..Default::default() } - .insert(&get_db()) - .await?; + .insert(get_db()) + .await?; Ok(WebResult { code: StatusCode::OK.as_u16(), diff --git a/src/web/router/api/user/mod.rs b/src/web/router/api/user/mod.rs index a6944764..11a0b4d0 100644 --- a/src/web/router/api/user/mod.rs +++ b/src/web/router/api/user/mod.rs @@ -9,11 +9,11 @@ use axum::{ response::IntoResponse, Extension, Json, Router, }; -use mime::Mime; use reqwest::StatusCode; +use sea_orm::ActiveValue::Set; use sea_orm::{ prelude::Expr, sea_query::Func, ActiveModelTrait, ActiveValue::NotSet, Condition, EntityTrait, - PaginatorTrait, QueryFilter, Set, + PaginatorTrait, QueryFilter, }; use serde::{Deserialize, Serialize}; use validator::Validate; @@ -75,7 +75,7 @@ pub async fn get( params.page, params.size, ) - .await?; + .await?; for user in users.iter_mut() { user.desensitize(); @@ -124,8 +124,8 @@ pub async fn create( group: Set(body.group), ..Default::default() } - .insert(&get_db()) - .await?; + .insert(get_db()) + .await?; user.desensitize(); @@ -156,7 +156,7 @@ pub async fn update( body.id = Some(id); if !(operator.group == Group::Admin || (operator.id == body.id.unwrap_or(0) - && (body.group.clone().is_none() || operator.group == body.group.clone().unwrap()))) + && (body.group.clone().is_none() || operator.group == body.group.clone().unwrap()))) { return Err(WebError::Forbidden(String::new())); } @@ -178,8 +178,8 @@ pub async fn update( group: body.group.map_or(NotSet, |v| Set(v)), ..Default::default() } - .update(&get_db()) - .await?; + .update(get_db()) + .await?; Ok(WebResult { code: StatusCode::OK.as_u16(), @@ -196,8 +196,12 @@ pub async fn delete( return Err(WebError::Forbidden(String::new())); } - let _ = crate::model::user::Entity::delete_by_id(id) - .exec(&get_db()) + let _ = crate::model::user::ActiveModel { + id: Set(id), + is_deleted: Set(true), + ..Default::default() + } + .update(get_db()) .await?; Ok(WebResult { @@ -241,7 +245,7 @@ pub async fn login(Json(mut body): Json) -> Result) -> Result 0; @@ -333,8 +337,8 @@ pub async fn register( group: Set(Group::User), ..Default::default() } - .insert(&get_db()) - .await?; + .insert(get_db()) + .await?; Ok(WebResult { code: StatusCode::OK.as_u16(),