Skip to content

Commit

Permalink
chore: once_lock to once_cell
Browse files Browse the repository at this point in the history
  • Loading branch information
ElaBosak233 committed Nov 17, 2024
1 parent 883256a commit a7f389c
Show file tree
Hide file tree
Showing 25 changed files with 155 additions and 145 deletions.
28 changes: 15 additions & 13 deletions src/cluster/mod.rs
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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<K8sClient> = OnceLock::new();
static K8S_CLIENT: OnceCell<K8sClient> = 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(
Expand Down
2 changes: 1 addition & 1 deletion src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
14 changes: 7 additions & 7 deletions src/db/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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 {
Expand Down Expand Up @@ -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.");
}
}
4 changes: 2 additions & 2 deletions src/env/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
6 changes: 3 additions & 3 deletions src/model/challenge/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -138,15 +138,15 @@ pub async fn find(
}
}

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

Ok(challenges)
Expand Down
4 changes: 2 additions & 2 deletions src/model/game/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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))
}
6 changes: 3 additions & 3 deletions src/model/game_challenge/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ 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())
.load_one(challenge::Entity, get_db())
.await?;

for (i, game_challenge) in game_challenges.iter_mut().enumerate() {
Expand All @@ -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?;

Expand Down
4 changes: 2 additions & 2 deletions src/model/game_team/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,9 @@ pub async fn find(game_id: Option<i64>, team_id: Option<i64>) -> Result<(Vec<Mod
sql = sql.filter(Column::TeamId.eq(team_id));
}

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

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

game_teams = preload(game_teams).await?;

Expand Down
10 changes: 5 additions & 5 deletions src/model/pod/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,9 +107,9 @@ impl ActiveModelBehavior for ActiveModel {
}

async fn preload(mut pods: Vec<Model>) -> Result<Vec<Model>, 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();
Expand Down Expand Up @@ -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?;

Expand Down
14 changes: 7 additions & 7 deletions src/model/submission/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,10 +121,10 @@ impl ActiveModelBehavior for ActiveModel {
}

async fn preload(mut submissions: Vec<Model>) -> Result<Vec<Model>, 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();
Expand Down Expand Up @@ -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 {
Expand All @@ -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?;

Expand All @@ -194,7 +194,7 @@ pub async fn get_by_challenge_ids(challenge_ids: Vec<i64>) -> Result<Vec<Model>,
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)
Expand Down
10 changes: 5 additions & 5 deletions src/model/team/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ impl ActiveModelBehavior for ActiveModel {

async fn preload(mut teams: Vec<Model>) -> Result<Vec<Model>, 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() {
Expand Down Expand Up @@ -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 {
Expand All @@ -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?;

Expand All @@ -148,7 +148,7 @@ pub async fn find(
pub async fn find_by_ids(ids: Vec<i64>) -> Result<Vec<Model>, DbErr> {
let mut teams = Entity::find()
.filter(Column::Id.is_in(ids))
.all(&get_db())
.all(get_db())
.await?;

teams = preload(teams).await?;
Expand All @@ -163,7 +163,7 @@ pub async fn find_by_user_id(id: i64) -> Result<Vec<Model>, DbErr> {
.filter(user_team::Column::UserId.eq(id))
.join(JoinType::InnerJoin, user_team::Relation::Team.def())
.into_model::<Model>()
.all(&get_db())
.all(get_db())
.await?;

teams = preload(teams).await?;
Expand Down
6 changes: 3 additions & 3 deletions src/model/user/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ impl ActiveModelBehavior for ActiveModel {

async fn preload(mut users: Vec<Model>) -> Result<Vec<Model>, 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() {
Expand Down Expand Up @@ -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 {
Expand All @@ -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?;

Expand Down
4 changes: 2 additions & 2 deletions src/model/user_team/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,9 @@ pub async fn find(user_id: Option<i64>, team_id: Option<i64>) -> Result<(Vec<Mod
sql = sql.filter(Column::TeamId.eq(team_id));
}

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

let user_teams = sql.all(&get_db()).await?;
let user_teams = sql.all(get_db()).await?;

Ok((user_teams, total))
}
6 changes: 3 additions & 3 deletions src/queue/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ use traits::QueueError;

static CLIENT: OnceCell<async_nats::Client> = 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)
}

Expand Down
2 changes: 1 addition & 1 deletion src/web/middleware/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ pub async fn jwt(mut req: Request<Body>, next: Next) -> Result<Response, WebErro

if let Ok(data) = result {
user = crate::model::user::Entity::find_by_id(data.claims.id)
.one(&get_db())
.one(get_db())
.await?;

if user.is_none() {
Expand Down
Loading

0 comments on commit a7f389c

Please sign in to comment.