Skip to content

Commit

Permalink
fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
dzlk17 committed Dec 2, 2024
1 parent fc65164 commit 142da43
Show file tree
Hide file tree
Showing 16 changed files with 78 additions and 127 deletions.
3 changes: 2 additions & 1 deletion database/src/tables/requests/table_struct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ impl FromRow<'_, PgRow> for Request {
request_type: RequestType::from_str(row.get("request_type"))
.map_err(|_| sqlx::Error::Decode(format!("Invalid request_type")))?,
session_id: row.get("session_id"),
request_status: row.get("request_status"),
request_status: RequestStatus::from_str(row.get("request_status"))
.map_err(|_| sqlx::Error::Decode(format!("Invalid request_status")))?,
network: row.get("network"),
creation_timestamp: row.get("creation_timestamp"),
})
Expand Down
10 changes: 7 additions & 3 deletions database/src/tables/team/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,9 +127,11 @@ impl Db {
}
}

pub async fn delete_all_user_teams(&self,
pub async fn delete_all_user_teams(
&self,
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
user_id: &str) -> Result<(), DbError> {
user_id: &str,
) -> Result<(), DbError> {
let query_body = format!(
"UPDATE {TEAM_TABLE_NAME} SET deactivated_at = $1 WHERE team_admin_id = $2 AND deactivated_at IS NULL",
);
Expand All @@ -150,7 +152,9 @@ impl Db {
#[cfg(feature = "cloud_integration_tests")]
#[cfg(test)]
mod tests {
use crate::tables::{team::table_struct::Team, utils::to_microsecond_precision};
use crate::tables::{
team::table_struct::Team, test_utils::test_utils::to_microsecond_precision,
};
use sqlx::types::chrono::Utc;

#[tokio::test]
Expand Down
11 changes: 10 additions & 1 deletion database/src/tables/test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ pub mod test_utils {
structs::{db_error::DbError, privilege_level::PrivilegeLevel},
tables::{
registered_app::table_struct::DbRegisteredApp, team::table_struct::Team,
user_app_privileges::table_struct::UserAppPrivilege,
user_app_privileges::table_struct::UserAppPrivilege, utils::get_current_datetime,
},
};
use chrono::TimeZone;
use sqlx::{
types::chrono::{DateTime, Utc},
Row, Transaction,
Expand Down Expand Up @@ -159,4 +160,12 @@ pub mod test_utils {
Ok(())
}
}

pub fn to_microsecond_precision(datetime: &DateTime<Utc>) -> DateTime<Utc> {
// Should never fail as we are converting from a valid DateTime<Utc>
match Utc.timestamp_micros(datetime.timestamp_micros()) {
chrono::LocalResult::Single(dt) => dt,
_ => get_current_datetime(),
}
}
}
3 changes: 2 additions & 1 deletion database/src/tables/user_app_privileges/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,8 @@ mod tests {
structs::privilege_level::PrivilegeLevel,
tables::{
registered_app::table_struct::DbRegisteredApp, team::table_struct::Team,
user_app_privileges::table_struct::UserAppPrivilege, utils::to_microsecond_precision,
test_utils::test_utils::to_microsecond_precision,
user_app_privileges::table_struct::UserAppPrivilege,
},
};
use sqlx::types::chrono::Utc;
Expand Down
4 changes: 3 additions & 1 deletion database/src/tables/users/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,9 @@ impl Db {
#[cfg(feature = "cloud_integration_tests")]
#[cfg(test)]
mod tests {
use crate::tables::{users::table_struct::User, utils::to_microsecond_precision};
use crate::tables::{
test_utils::test_utils::to_microsecond_precision, users::table_struct::User,
};
use sqlx::types::chrono::Utc;

#[tokio::test]
Expand Down
20 changes: 1 addition & 19 deletions database/src/tables/utils.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,9 @@
use log::error;
use sqlx::types::chrono::{DateTime, TimeZone, Utc};
use std::time::{SystemTime, UNIX_EPOCH};

pub fn get_timestamp_in_milliseconds() -> u64 {
let now = SystemTime::now();
let since_the_epoch = match now.duration_since(UNIX_EPOCH) {
Ok(duration) => duration,
Err(err) => {
error!(
"Error getting timestamp in milliseconds: {}. Time went backwards",
err
);
return 0;
}
};
let since_the_epoch = now.duration_since(UNIX_EPOCH).expect("Time went backwards");
since_the_epoch.as_millis() as u64
}

Expand All @@ -25,14 +15,6 @@ pub fn get_current_datetime() -> DateTime<Utc> {
Utc::now()
}

pub fn to_microsecond_precision(datetime: &DateTime<Utc>) -> DateTime<Utc> {
// Should never fail as we are converting from a valid DateTime<Utc>
match Utc.timestamp_micros(datetime.timestamp_micros()) {
chrono::LocalResult::Single(dt) => dt,
_ => get_current_datetime(),
}
}

// This function is used to format the keys of a table to be used in a view query
pub fn format_view_keys(prefix: &str, keys: &[(&'static str, bool)]) -> String {
keys.iter()
Expand Down
13 changes: 2 additions & 11 deletions server/src/http/cloud/accept_team_invite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use super::{
};
use crate::{
env::is_env_production, middlewares::auth_middleware::UserId,
structs::cloud::api_cloud_errors::CloudApiErrors,
structs::cloud::api_cloud_errors::CloudApiErrors, utils::start_transaction,
};
use axum::{extract::State, http::StatusCode, Extension, Json};
use database::db::Db;
Expand Down Expand Up @@ -140,16 +140,7 @@ pub async fn accept_team_invite(
};
}
// Accept invite
let mut tx = match db.connection_pool.begin().await {
Ok(tx) => tx,
Err(err) => {
error!("Failed to start transaction: {:?}", err);
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
CloudApiErrors::DatabaseError.to_string(),
));
}
};
let mut tx = start_transaction(&db).await?;

// Accept invite
if let Err(err) = db
Expand Down
9 changes: 2 additions & 7 deletions server/src/http/cloud/change_user_privileges.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use crate::{
structs::cloud::{
api_cloud_errors::CloudApiErrors, new_user_privilege_level::NewUserPrivilegeLevel,
},
utils::start_transaction,
};
use axum::{extract::State, http::StatusCode, Extension, Json};
use database::{
Expand Down Expand Up @@ -125,13 +126,7 @@ pub async fn change_user_privileges(
.collect();

// Start transaction to update users privileges
let mut tx = db.connection_pool.begin().await.map_err(|err| {
error!("Failed to start transaction: {:?}", err);
(
StatusCode::INTERNAL_SERVER_ERROR,
CloudApiErrors::DatabaseError.to_string(),
)
})?;
let mut tx = start_transaction(&db).await?;

// Update users privileges
for requested_change in request.privileges_changes {
Expand Down
9 changes: 2 additions & 7 deletions server/src/http/cloud/delete_account_finish.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use crate::{
cloud::api_cloud_errors::CloudApiErrors,
session_cache::{ApiSessionsCache, SessionCache, SessionsCacheKey},
},
utils::start_transaction,
};
use axum::{extract::State, http::StatusCode, Extension, Json};
use database::db::Db;
Expand Down Expand Up @@ -82,13 +83,7 @@ pub async fn delete_account_finish(
sessions_cache.remove(&sessions_key);

// Start transaction to update users privileges
let mut tx = db.connection_pool.begin().await.map_err(|err| {
error!("Failed to start transaction: {:?}", err);
(
StatusCode::INTERNAL_SERVER_ERROR,
CloudApiErrors::DatabaseError.to_string(),
)
})?;
let mut tx = start_transaction(&db).await?;

let mut owned_team_grafana_ids = Vec::new();
let mut non_owned_team_grafana_ids = Vec::new();
Expand Down
12 changes: 2 additions & 10 deletions server/src/http/cloud/delete_app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use crate::{
env::is_env_production,
http::cloud::grafana_utils::delete_registered_app::handle_grafana_delete_app,
middlewares::auth_middleware::UserId, structs::cloud::api_cloud_errors::CloudApiErrors,
utils::start_transaction,
};
use axum::{extract::State, http::StatusCode, Extension, Json};
use database::{db::Db, structs::privilege_level::PrivilegeLevel};
Expand Down Expand Up @@ -70,16 +71,7 @@ pub async fn delete_app(
}
// Delete the app
// Start a transaction
let mut tx = match db.connection_pool.begin().await {
Ok(tx) => tx,
Err(err) => {
error!("Failed to start transaction: {:?}", err);
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
CloudApiErrors::DatabaseError.to_string(),
));
}
};
let mut tx = start_transaction(&db).await?;

if let Err(err) = db
.remove_privileges_for_inactive_app_within_tx(&mut tx, &request.app_id)
Expand Down
12 changes: 2 additions & 10 deletions server/src/http/cloud/delete_team.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use crate::{
http::cloud::grafana_utils::delete_team::handle_grafana_delete_team,
middlewares::auth_middleware::UserId,
structs::cloud::{api_cloud_errors::CloudApiErrors, app_info::AppInfo},
utils::start_transaction,
};
use axum::{extract::State, http::StatusCode, Extension, Json};
use database::db::Db;
Expand Down Expand Up @@ -32,16 +33,7 @@ pub async fn delete_team(
validate_request(&request, &())?;
warn!("Delete team request: {:?}", request);
// Start a transaction
let mut tx = match db.connection_pool.begin().await {
Ok(tx) => tx,
Err(err) => {
error!("Failed to start transaction: {:?}", err);
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
CloudApiErrors::DatabaseError.to_string(),
));
}
};
let mut tx = start_transaction(&db).await?;

// First check if team exists
let team = match db.get_team_by_team_id(None, &request.team_id).await {
Expand Down
12 changes: 2 additions & 10 deletions server/src/http/cloud/domains/remove_whitelisted_domain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::{
http::cloud::utils::{custom_validate_domain_name, custom_validate_uuid},
middlewares::auth_middleware::UserId,
structs::cloud::api_cloud_errors::CloudApiErrors,
utils::start_transaction,
};
use axum::{extract::State, http::StatusCode, Extension, Json};
use database::{db::Db, structs::privilege_level::PrivilegeLevel};
Expand Down Expand Up @@ -105,16 +106,7 @@ pub async fn remove_whitelisted_domain(
));
}

let mut tx = match db.connection_pool.begin().await {
Ok(tx) => tx,
Err(err) => {
error!("Failed to start transaction: {:?}", err);
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
CloudApiErrors::DatabaseError.to_string(),
));
}
};
let mut tx = start_transaction(&db).await?;

// Remove domain from whitelisted domains
if let Err(err) = db
Expand Down
12 changes: 2 additions & 10 deletions server/src/http/cloud/domains/verify_domain_finish.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use crate::{
http::cloud::utils::{custom_validate_domain_name, custom_validate_uuid},
middlewares::auth_middleware::UserId,
structs::cloud::api_cloud_errors::CloudApiErrors,
utils::start_transaction,
};
use anyhow::bail;
use axum::{extract::State, http::StatusCode, Extension, Json};
Expand Down Expand Up @@ -183,16 +184,7 @@ pub async fn verify_domain_finish(
}

// Add domain to whitelist
let mut tx = match db.connection_pool.begin().await {
Ok(tx) => tx,
Err(err) => {
error!("Failed to start transaction: {:?}", err);
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
CloudApiErrors::DatabaseError.to_string(),
));
}
};
let mut tx = start_transaction(&db).await?;

if let Err(err) = db
.add_new_whitelisted_domain(&mut tx, &request.app_id, &domain_name)
Expand Down
13 changes: 2 additions & 11 deletions server/src/http/cloud/register_new_app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use super::{
use crate::{
env::is_env_production, middlewares::auth_middleware::UserId,
statics::REGISTERED_APPS_LIMIT_PER_TEAM, structs::cloud::api_cloud_errors::CloudApiErrors,
test_env::is_test_env,
utils::start_transaction,
};
use axum::{extract::State, http::StatusCode, Extension, Json};
use database::{
Expand Down Expand Up @@ -140,16 +140,7 @@ pub async fn register_new_app(

// Register a new app under this team
// Start a transaction
let mut tx = match db.connection_pool.begin().await {
Ok(tx) => tx,
Err(err) => {
error!("Failed to start transaction: {:?}", err);
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
CloudApiErrors::DatabaseError.to_string(),
));
}
};
let mut tx = start_transaction(&db).await?;

// Register a new app
let db_registered_app =
Expand Down
35 changes: 23 additions & 12 deletions server/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,15 @@ use crate::{
setup_database_datasource::setup_database_datasource,
setup_template_folder::setup_templates_folder,
},
structs::{wallet_metadata::WalletMetadata, wallets::*},
structs::{
cloud::api_cloud_errors::CloudApiErrors, wallet_metadata::WalletMetadata, wallets::*,
},
};
use axum::http::{header, Method};
use axum::http::{header, Method, StatusCode};
use database::db::Db;
use log::error;
use openapi::apis::configuration::Configuration;
use sqlx::{Postgres, Transaction};
use std::{
sync::Arc,
time::{Duration, SystemTime, UNIX_EPOCH},
Expand All @@ -17,18 +21,10 @@ use tower_http::cors::{Any, CorsLayer};

pub fn get_timestamp_in_milliseconds() -> u64 {
let now = SystemTime::now();
let since_the_epoch = match now.duration_since(UNIX_EPOCH) {
Ok(duration) => duration,
Err(err) => {
error!(
"Error getting timestamp in milliseconds: {}. Time went backwards",
err
);
return 0;
}
};
let since_the_epoch = now.duration_since(UNIX_EPOCH).expect("Time went backwards");
since_the_epoch.as_millis() as u64
}

pub fn get_cors() -> CorsLayer {
CorsLayer::new()
.allow_methods([Method::GET, Method::POST, Method::OPTIONS])
Expand Down Expand Up @@ -56,6 +52,21 @@ pub fn get_wallets_metadata_vec() -> Vec<WalletMetadata> {
]
}

pub async fn start_transaction(
db: &Arc<Db>,
) -> Result<Transaction<'static, Postgres>, (StatusCode, String)> {
match db.connection_pool.begin().await {
Ok(tx) => Ok(tx),
Err(err) => {
error!("Failed to start transaction: {:?}", err);
Err((
StatusCode::INTERNAL_SERVER_ERROR,
CloudApiErrors::DatabaseError.to_string(),
))
}
}
}

// CHECK THIS - used only at the begginning - better to have error
pub async fn import_template_dashboards(grafana_client: &Arc<Configuration>) {
// Check if folder exists if not create it
Expand Down
Loading

0 comments on commit 142da43

Please sign in to comment.