Skip to content

Commit

Permalink
Get rid of the matches (#247)
Browse files Browse the repository at this point in the history
Co-authored-by: Filip Lelek <filip.lelek@neti-soft.com>
  • Loading branch information
Filip-L and filip-neti authored Jan 14, 2025
1 parent 029890d commit e2e7ab4
Show file tree
Hide file tree
Showing 15 changed files with 1,290 additions and 1,671 deletions.
8 changes: 3 additions & 5 deletions fplus-database/src/database/allocators.rs
Original file line number Diff line number Diff line change
Expand Up @@ -275,11 +275,9 @@ pub async fn update_allocator_threshold(
*/
pub async fn delete_allocator(owner: &str, repo: &str) -> Result<(), sea_orm::DbErr> {
let conn = get_database_connection().await?;
let allocator = get_allocator(owner, repo).await?;
let allocator = match allocator {
Some(allocator) => allocator,
None => return Err(DbErr::Custom("Allocator not found".to_string())),
};
let allocator = get_allocator(owner, repo)
.await?
.ok_or(DbErr::Custom("Allocator not found".to_string()))?;
allocator.delete(&conn).await?;
Ok(())
}
77 changes: 32 additions & 45 deletions fplus-database/src/database/applications.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,15 +174,13 @@ pub async fn get_application(
query = query.filter(Column::PrNumber.eq(number as i64));
}

let result = query
let application = query
.order_by(Column::PrNumber, Order::Desc)
.one(&conn)
.await?;
.await?
.ok_or(DbErr::Custom("Application not found".to_string()))?;

match result {
Some(application) => Ok(application),
None => Err(DbErr::Custom("Application not found".to_string())),
}
Ok(application)
}

/**
Expand All @@ -202,17 +200,15 @@ pub async fn get_application_by_pr_number(
pr_number: u64,
) -> Result<ApplicationModel, sea_orm::DbErr> {
let conn = get_database_connection().await?;
let result = Application::find()
let application = Application::find()
.filter(Column::Owner.contains(owner))
.filter(Column::Repo.contains(repo))
.filter(Column::PrNumber.eq(pr_number as i64))
.one(&conn)
.await?;
.await?
.ok_or(DbErr::Custom("Application not found".to_string()))?;

match result {
Some(application) => Ok(application),
None => Err(DbErr::Custom("Application not found".to_string())),
}
Ok(application)
}

/**
Expand Down Expand Up @@ -312,36 +308,32 @@ pub async fn update_application(
) -> Result<ApplicationModel, sea_orm::DbErr> {
let conn = get_database_connection().await?;

match get_application(id.clone(), owner.clone(), repo.clone(), Some(pr_number)).await {
Ok(existing_application) => {
let mut active_application: ActiveModel = existing_application.into_active_model();
active_application.application = Set(Some(app_file.clone()));
let file_sha = sha.unwrap_or_else(|| {
//Calculate SHA
let mut hasher = Sha1::new();
let application = format!("blob {}\x00{}", app_file.len(), app_file);
hasher.update(application.as_bytes());
format!("{:x}", hasher.finalize())
});
active_application.sha = Set(Some(file_sha));
let existing_application =
get_application(id.clone(), owner.clone(), repo.clone(), Some(pr_number)).await?;

if let Some(path) = path {
active_application.path = Set(Some(path));
};
let mut active_application: ActiveModel = existing_application.into_active_model();
active_application.application = Set(Some(app_file.clone()));
let file_sha = sha.unwrap_or_else(|| {
//Calculate SHA
let mut hasher = Sha1::new();
let application = format!("blob {}\x00{}", app_file.len(), app_file);
hasher.update(application.as_bytes());
format!("{:x}", hasher.finalize())
});
active_application.sha = Set(Some(file_sha));

if let Some(client_contract_address) = client_contract_address {
active_application.client_contract_address = Set(Some(client_contract_address));
} else {
active_application.client_contract_address = Set(None);
}
if let Some(path) = path {
active_application.path = Set(Some(path));
};

let updated_application = active_application.update(&conn).await?;
Ok(updated_application)
}
Err(_) => Err(sea_orm::DbErr::Custom(
"Failed to find the application to update.".into(),
)),
if let Some(client_contract_address) = client_contract_address {
active_application.client_contract_address = Set(Some(client_contract_address));
} else {
active_application.client_contract_address = Set(None);
}

let updated_application = active_application.update(&conn).await?;
Ok(updated_application)
}

/**
Expand Down Expand Up @@ -387,13 +379,8 @@ pub async fn create_application(
..Default::default()
};

match new_application.insert(&conn).await {
Ok(application) => Ok(application),
Err(e) => Err(sea_orm::DbErr::Custom(format!(
"Failed to insert new application: {}",
e
))),
}
let application = new_application.insert(&conn).await?;
Ok(application)
}

/**
Expand Down
50 changes: 21 additions & 29 deletions fplus-http-server/src/middleware/verifier_auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,36 +88,28 @@ where
.header("Authorization", format!("Bearer {}", token))
.header("User-Agent", "Actix-web")
.send()
.await;

match user_info_result {
Ok(response) => {
//Raise an actix test error
if response.status().is_success() {
let user_info = response
.json::<serde_json::Value>()
.await
.expect("Failed to parse JSON");

if let Some(login) = user_info.get("login").and_then(|v| v.as_str()) {
user_handle = login.to_string();
} else {
println!("GitHub handle information not found.");
return Err(actix_web::error::ErrorInternalServerError(
"GitHub handle information not found.",
));
}
} else {
println!("Failed to get GitHub user info");
return Err(actix_web::error::ErrorUnauthorized(
"Failed to get GitHub user info.",
));
}
}
Err(e) => {
println!("Request error: {:?}", e);
return Err(actix_web::error::ErrorBadRequest(e));
.await
.map_err(actix_web::error::ErrorBadRequest)?;

if user_info_result.status().is_success() {
let user_info = user_info_result
.json::<serde_json::Value>()
.await
.expect("Failed to parse JSON");

if let Some(login) = user_info.get("login").and_then(|v| v.as_str()) {
user_handle = login.to_string();
} else {
println!("GitHub handle information not found.");
return Err(actix_web::error::ErrorInternalServerError(
"GitHub handle information not found.",
));
}
} else {
println!("Failed to get GitHub user info");
return Err(actix_web::error::ErrorUnauthorized(
"Failed to get GitHub user info.",
));
}
}

Expand Down
110 changes: 49 additions & 61 deletions fplus-http-server/src/router/allocator.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
use actix_web::{delete, get, post, web, HttpResponse, Responder};
use actix_web::{
delete,
error::{ErrorInternalServerError, ErrorNotFound},
get, post, web, HttpResponse, Responder,
};
use fplus_database::database::allocators as allocators_db;
use fplus_lib::core::{
allocator::{
Expand All @@ -15,15 +19,11 @@ use reqwest::Client;
* @return HttpResponse - The result of the operation
*/
#[get("/allocators")]
pub async fn allocators() -> impl Responder {
let allocators = allocators_db::get_allocators().await;
match allocators {
Ok(allocators) => HttpResponse::Ok().json(allocators),
Err(e) => {
log::error!("Failed to fetch allocators: {}", e);
HttpResponse::InternalServerError().body(e.to_string())
}
}
pub async fn allocators() -> actix_web::Result<impl Responder> {
let allocators = allocators_db::get_allocators()
.await
.map_err(ErrorNotFound)?;
Ok(HttpResponse::Ok().json(allocators))
}
/**
* Creates new Allocator in the db from a JSON file in the repository
Expand All @@ -35,15 +35,17 @@ pub async fn allocators() -> impl Responder {
* @return HttpResponse - The result of the operation
*/
#[post("/allocator/create")]
pub async fn create_allocator_from_json(files: web::Json<ChangedAllocators>) -> impl Responder {
pub async fn create_allocator_from_json(
files: web::Json<ChangedAllocators>,
) -> actix_web::Result<impl Responder> {
let ChangedAllocators { files_changed } = files.into_inner();
match create_allocator_from_file(files_changed).await {
Ok(_) => HttpResponse::Ok().body(
serde_json::to_string_pretty("All files processed successfully")
.expect("Serialization of static string should succeed"),
),
Err(e) => HttpResponse::BadRequest().body(e.to_string()),
}
create_allocator_from_file(files_changed)
.await
.map_err(ErrorInternalServerError)?;
Ok(HttpResponse::Ok().body(
serde_json::to_string_pretty("All files processed successfully")
.expect("Serialization of static string should succeed"),
))
}

/**
Expand All @@ -56,14 +58,15 @@ pub async fn create_allocator_from_json(files: web::Json<ChangedAllocators>) ->
* @return HttpResponse - The result of the operation
*/
#[get("/allocator/{owner}/{repo}")]
pub async fn allocator(path: web::Path<(String, String)>) -> impl Responder {
pub async fn allocator(path: web::Path<(String, String)>) -> actix_web::Result<impl Responder> {
let (owner, repo) = path.into_inner();
match allocators_db::get_allocator(&owner, &repo).await {
Ok(allocator) => match allocator {
Some(allocator) => HttpResponse::Ok().json(allocator),
None => HttpResponse::NotFound().finish(),
},
Err(e) => HttpResponse::InternalServerError().body(e.to_string()),
let allocator = allocators_db::get_allocator(&owner, &repo)
.await
.map_err(ErrorInternalServerError)?;
if let Some(allocator) = allocator {
Ok(HttpResponse::Ok().json(allocator))
} else {
Err(ErrorNotFound("Allocator not found"))
}
}

Expand All @@ -77,17 +80,12 @@ pub async fn allocator(path: web::Path<(String, String)>) -> impl Responder {
* @return HttpResponse - The result of the operation
*/
#[delete("/allocator/{owner}/{repo}")]
pub async fn delete(path: web::Path<(String, String)>) -> impl Responder {
pub async fn delete(path: web::Path<(String, String)>) -> actix_web::Result<impl Responder> {
let (owner, repo) = path.into_inner();
match allocators_db::delete_allocator(&owner, &repo).await {
Ok(_) => HttpResponse::Ok().finish(),
Err(e) => {
if e.to_string().contains("Allocator not found") {
return HttpResponse::NotFound().body(e.to_string());
}
HttpResponse::InternalServerError().body(e.to_string())
}
}
allocators_db::delete_allocator(&owner, &repo)
.await
.map_err(ErrorInternalServerError)?;
Ok(HttpResponse::Ok().finish())
}

/**
Expand All @@ -99,42 +97,32 @@ pub async fn delete(path: web::Path<(String, String)>) -> impl Responder {
* @param AllocatorUpdateForceInfo - The list of changed JSON file names and allocators to update
*/
#[post("/allocator/update/force")]
pub async fn update_allocator_force(body: web::Json<AllocatorUpdateForceInfo>) -> impl Responder {
pub async fn update_allocator_force(
body: web::Json<AllocatorUpdateForceInfo>,
) -> actix_web::Result<impl Responder> {
// First we need to deconstruct the body
let AllocatorUpdateForceInfo {
files,
allocators: affected_allocators,
} = body.into_inner();

// Logic will be implemented in allocator::update_allocator_force
match force_update_allocators(files, affected_allocators).await {
Ok(results) => HttpResponse::Ok().json(results),
Err(e) => {
log::error!("Failed to update allocators: {}", e);
HttpResponse::InternalServerError().body(format!("{}", e))
}
}
force_update_allocators(files, affected_allocators)
.await
.map_err(ErrorInternalServerError)?;
Ok(HttpResponse::Ok().json(()))
}

#[get("/get_installation_ids")]
pub async fn get_installation_ids() -> impl Responder {
pub async fn get_installation_ids() -> actix_web::Result<impl Responder> {
let client = Client::new();
let jwt = match generate_github_app_jwt().await {
Ok(jwt) => jwt,
Err(e) => {
log::error!("Failed to generate GitHub App JWT: {}", e);
return HttpResponse::InternalServerError().finish(); // Ensure to call .finish()
}
};
let jwt = generate_github_app_jwt()
.await
.map_err(ErrorInternalServerError)?;

match fetch_installation_ids(&client, &jwt).await {
Ok(ids) => {
// Assuming `ids` can be serialized directly; adjust based on your actual data structure
HttpResponse::Ok().json(ids)
}
Err(e) => {
log::error!("Failed to fetch installation IDs: {}", e);
HttpResponse::InternalServerError().finish()
}
}
let ids = fetch_installation_ids(&client, &jwt).await.map_err(|e| {
log::error!("Failed to generate GitHub App JWT: {}", e);
ErrorInternalServerError(e)
})?;
Ok(HttpResponse::Ok().json(ids))
}
Loading

0 comments on commit e2e7ab4

Please sign in to comment.