Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get rid of unwrap #246

Merged
merged 1 commit into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions fplus-database/src/database/allocators.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,9 +201,9 @@ pub async fn create_or_update_allocator(
let conn = get_database_connection()
.await
.expect("Failed to get DB connection");
let insert_result = new_allocator.insert(&conn).await;
let insert_result = new_allocator.insert(&conn).await?;
println!("Allocator inserted: {:?}", insert_result);
Ok(insert_result.unwrap())
Ok(insert_result)
}
}

Expand Down
70 changes: 33 additions & 37 deletions fplus-database/src/database/applications.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::get_database_connection;
use crate::models::applications::{
ActiveModel, Column, Entity as Application, Model as ApplicationModel,
};
use chrono::{DateTime, TimeZone, Utc};
use chrono::{DateTime, Utc};
use sea_orm::{entity::*, query::*, DbBackend, DbErr};
use sha1::{Digest, Sha1};

Expand Down Expand Up @@ -44,45 +44,41 @@ pub async fn get_applications() -> Result<Vec<ApplicationModel>, sea_orm::DbErr>
.all(&conn)
.await?;

//Iterate over the results and convert them to ApplicationModel
let mut applications: Vec<ApplicationModel> = Vec::new();
for app in app_data {
applications.push(ApplicationModel {
id: app.get("id").unwrap().as_str().unwrap().to_string(),
owner: app.get("owner").unwrap().as_str().unwrap().to_string(),
repo: app.get("repo").unwrap().as_str().unwrap().to_string(),
pr_number: app.get("pr_number").unwrap().as_i64().unwrap(),
issue_number: app
.get("issue_number")
.expect("Issue number should be in the application data")
.as_i64()
.expect("Issue number must exist"),
application: Some(
app.get("application")
.unwrap()
.as_str()
.unwrap()
.to_string(),
),
updated_at: Utc.from_utc_datetime(
&app.get("updated_at")
.unwrap()
.as_str()
.unwrap()
.parse::<DateTime<Utc>>()
.unwrap()
.naive_utc(),
),
sha: Some(app.get("sha").unwrap().as_str().unwrap().to_string()),
path: Some(app.get("path").unwrap().as_str().unwrap().to_string()),
client_contract_address: app
.get("client_contract_address")
.map(|client_contract_address| client_contract_address.to_string()),
});
}
let applications = app_data
.into_iter()
.map(|app| ApplicationModel {
Filip-L marked this conversation as resolved.
Show resolved Hide resolved
id: get_string_field(&app, "id").expect("ID must exist"),
owner: get_string_field(&app, "owner").expect("Owner must exist"),
repo: get_string_field(&app, "repo").expect("Repo must exist"),
pr_number: get_i64_field(&app, "pr_number").expect("PR number must exist"),
issue_number: get_i64_field(&app, "issue_number").expect("Issue number must exist"),
Filip-L marked this conversation as resolved.
Show resolved Hide resolved
application: get_string_field(&app, "application"),
updated_at: parse_datetime_field(&app, "updated_at")
.expect("Updated_at must be a valid datetime"),
sha: get_string_field(&app, "sha"),
path: get_string_field(&app, "path"),
client_contract_address: get_string_field(&app, "client_contract_address"),
})
.collect();

Ok(applications)
}

fn get_string_field(json: &JsonValue, field: &str) -> Option<String> {
json.get(field)?.as_str().map(|s| s.to_string())
}

/// Retrieves an i64 field from a JSON value, if it exists.
fn get_i64_field(json: &JsonValue, field: &str) -> Option<i64> {
json.get(field)?.as_i64()
}

fn parse_datetime_field(json: &JsonValue, field: &str) -> Option<DateTime<Utc>> {
json.get(field)?
.as_str()
.and_then(|s| s.parse::<DateTime<Utc>>().ok())
}

/**
* Get merged applications from the database
*
Expand Down
8 changes: 6 additions & 2 deletions fplus-database/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ pub async fn setup() -> Result<(), DbErr> {
params.to_url()
});
let db_conn = Database::connect(&database_url).await?;
let mut db_conn_global = DB_CONN.lock().unwrap();
let mut db_conn_global = DB_CONN
.lock()
.map_err(|e| DbErr::Custom(format!("Failed to lock database connection: {}", e)))?;
*db_conn_global = Some(db_conn);
Ok(())
}
Expand All @@ -50,7 +52,9 @@ pub async fn setup() -> Result<(), DbErr> {
* @return Result<DatabaseConnection, &'static str> - The database connection or an error message
*/
pub async fn get_database_connection() -> Result<DatabaseConnection, DbErr> {
let db_conn = DB_CONN.lock().unwrap();
let db_conn = DB_CONN
.lock()
.map_err(|e| DbErr::Custom(format!("Failed to lock database connection: {}", e)))?;
if let Some(ref conn) = *db_conn {
Ok(conn.clone())
} else {
Expand Down
6 changes: 4 additions & 2 deletions fplus-http-server/src/router/allocator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,10 @@ pub async fn allocators() -> impl Responder {
pub async fn create_allocator_from_json(files: web::Json<ChangedAllocators>) -> 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").unwrap()),
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()),
}
}
Expand Down
111 changes: 89 additions & 22 deletions fplus-http-server/src/router/application.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,12 @@ pub async fn create(info: web::Json<CreateApplicationInfo>) -> impl Responder {
pub async fn single(query: web::Query<ApplicationQueryParams>) -> impl Responder {
let ApplicationQueryParams { id, owner, repo } = query.into_inner();
match LDNApplication::load_from_db(id, owner, repo).await {
Ok(app_file) => HttpResponse::Ok().body(serde_json::to_string_pretty(&app_file).unwrap()),
Ok(app_file) => match serde_json::to_string_pretty(&app_file) {
Ok(response) => HttpResponse::Ok().body(response),
Err(_) => {
HttpResponse::InternalServerError().body("Failed to serialize success message")
}
},
Err(e) => HttpResponse::BadRequest().body(e.to_string()),
}
}
Expand Down Expand Up @@ -68,7 +73,12 @@ pub async fn trigger(
)
.await
{
Ok(app) => HttpResponse::Ok().body(serde_json::to_string_pretty(&app).unwrap()),
Ok(app) => match serde_json::to_string_pretty(&app) {
Ok(response) => HttpResponse::Ok().body(response),
Err(_) => {
HttpResponse::InternalServerError().body("Failed to serialize success message")
}
},
Err(e) => HttpResponse::BadRequest()
.body(format!("Application is not in the correct state {}", e)),
}
Expand All @@ -89,7 +99,12 @@ pub async fn approve_changes(query: web::Query<VerifierActionsQueryParams>) -> i
.approve_changes(query.owner.clone(), query.repo.clone())
.await
{
Ok(result) => HttpResponse::Ok().body(result),
Ok(result) => match serde_json::to_string_pretty(&result) {
Ok(response) => HttpResponse::Ok().body(response),
Err(_) => {
HttpResponse::InternalServerError().body("Failed to serialize success message")
}
},
Err(e) => HttpResponse::BadRequest().body(e.to_string()),
}
}
Expand Down Expand Up @@ -129,7 +144,12 @@ pub async fn propose(
)
.await
{
Ok(app) => HttpResponse::Ok().body(serde_json::to_string_pretty(&app).unwrap()),
Ok(app) => match serde_json::to_string_pretty(&app) {
Ok(response) => HttpResponse::Ok().body(response),
Err(_) => {
HttpResponse::InternalServerError().body("Failed to serialize success message")
}
},
Err(e) => HttpResponse::BadRequest().body(e.to_string()),
}
}
Expand Down Expand Up @@ -170,7 +190,10 @@ pub async fn propose_storage_providers(
)
.await
{
Ok(_) => HttpResponse::Ok().body(serde_json::to_string_pretty("Success").unwrap()),
Ok(_) => HttpResponse::Ok().body(
serde_json::to_string_pretty("Success")
.expect("Serialization of static string should succeed"),
),
Err(e) => HttpResponse::BadRequest().body(e.to_string()),
}
}
Expand Down Expand Up @@ -205,7 +228,10 @@ pub async fn approve_storage_providers(
)
.await
{
Ok(_) => HttpResponse::Ok().body(serde_json::to_string_pretty("Success").unwrap()),
Ok(_) => HttpResponse::Ok().body(
serde_json::to_string_pretty("Success")
.expect("Serialization of static string should succeed"),
),
Err(e) => HttpResponse::BadRequest().body(e.to_string()),
}
}
Expand Down Expand Up @@ -241,7 +267,12 @@ pub async fn approve(
)
.await
{
Ok(app) => HttpResponse::Ok().body(serde_json::to_string_pretty(&app).unwrap()),
Ok(app) => match serde_json::to_string_pretty(&app) {
Ok(response) => HttpResponse::Ok().body(response),
Err(_) => {
HttpResponse::InternalServerError().body("Failed to serialize success message")
}
},
Err(e) => HttpResponse::BadRequest().body(e.to_string()),
}
}
Expand All @@ -260,7 +291,12 @@ pub async fn decline(query: web::Query<VerifierActionsQueryParams>) -> impl Resp
.decline_application(query.owner.clone(), query.repo.clone())
.await
{
Ok(app) => HttpResponse::Ok().body(serde_json::to_string_pretty(&app).unwrap()),
Ok(app) => match serde_json::to_string_pretty(&app) {
Ok(response) => HttpResponse::Ok().body(response),
Err(_) => {
HttpResponse::InternalServerError().body("Failed to serialize success message")
}
},
Err(_) => HttpResponse::BadRequest().body("Application is not in the correct state"),
}
}
Expand All @@ -283,7 +319,12 @@ pub async fn additional_info_required(
.additional_info_required(query.owner.clone(), query.repo.clone(), verifier_message)
.await
{
Ok(app) => HttpResponse::Ok().body(serde_json::to_string_pretty(&app).unwrap()),
Ok(app) => match serde_json::to_string_pretty(&app) {
Ok(response) => HttpResponse::Ok().body(response),
Err(_) => {
HttpResponse::InternalServerError().body("Failed to serialize success message")
}
},
Err(_) => HttpResponse::BadRequest().body("Application is not in the correct state"),
}
}
Expand Down Expand Up @@ -311,26 +352,38 @@ pub async fn all_applications() -> impl Responder {
#[get("/application/active")]
pub async fn active(query: web::Query<GithubQueryParams>) -> impl Responder {
let GithubQueryParams { owner, repo } = query.into_inner();
let apps = match LDNApplication::active(owner, repo, None).await {
Ok(app) => app,
Err(e) => return HttpResponse::BadRequest().body(e.to_string()),
};
HttpResponse::Ok().body(serde_json::to_string_pretty(&apps).unwrap())
match LDNApplication::active(owner, repo, None).await {
Ok(app) => match serde_json::to_string_pretty(&app) {
Ok(response) => HttpResponse::Ok().body(response),
Err(_) => {
HttpResponse::InternalServerError().body("Failed to serialize success message")
}
},
Err(e) => HttpResponse::BadRequest().body(e.to_string()),
}
}

#[get("/application/merged")]
pub async fn merged(query: web::Query<GithubQueryParams>) -> actix_web::Result<impl Responder> {
let GithubQueryParams { owner, repo } = query.into_inner();
match LDNApplication::merged(owner, repo).await {
Ok(apps) => Ok(HttpResponse::Ok().body(serde_json::to_string_pretty(&apps).unwrap())),
Ok(apps) => match serde_json::to_string_pretty(&apps) {
Ok(response) => Ok(HttpResponse::Ok().body(response)),
Err(_) => {
Ok(HttpResponse::InternalServerError().body("Failed to serialize success message"))
}
},
Err(e) => Ok(HttpResponse::InternalServerError().body(e.to_string())),
}
}

#[post("/application/notify_refill")]
pub async fn notify_refill(info: web::Json<NotifyRefillInfo>) -> impl Responder {
match LDNApplication::notify_refill(info.into_inner()).await {
Ok(()) => HttpResponse::Ok().body(serde_json::to_string_pretty("Success").unwrap()),
Ok(_) => HttpResponse::Ok().body(
serde_json::to_string_pretty("Success")
.expect("Serialization of static string should succeed"),
),
Err(e) => HttpResponse::BadRequest().body(e.to_string()),
}
}
Expand Down Expand Up @@ -523,8 +576,10 @@ pub async fn submit_kyc(info: web::Json<SubmitKYCInfo>) -> impl Responder {
Err(e) => return HttpResponse::BadRequest().body(e.to_string()),
};
match ldn_application.submit_kyc(&info.into_inner()).await {
Ok(()) => HttpResponse::Ok()
.body(serde_json::to_string_pretty("Address verified with score").unwrap()),
Ok(_) => HttpResponse::Ok().body(
serde_json::to_string_pretty("Address verified with score")
.expect("Serialization of static string should succeed"),
),
Err(e) => HttpResponse::BadRequest().body(e.to_string()),
}
}
Expand All @@ -546,7 +601,10 @@ pub async fn request_kyc(query: web::Query<VerifierActionsQueryParams>) -> impl
.request_kyc(&query.id, &query.owner, &query.repo)
.await
{
Ok(()) => HttpResponse::Ok().body(serde_json::to_string_pretty("Success").unwrap()),
Ok(_) => HttpResponse::Ok().body(
serde_json::to_string_pretty("Success")
.expect("Serialization of static string should succeed"),
),
Err(e) => HttpResponse::BadRequest().body(e.to_string()),
}
}
Expand All @@ -565,7 +623,10 @@ pub async fn trigger_ssa(
)
.await
{
Ok(()) => HttpResponse::Ok().body(serde_json::to_string_pretty("Success").unwrap()),
Ok(_) => HttpResponse::Ok().body(
serde_json::to_string_pretty("Success")
.expect("Serialization of static string should succeed"),
),
Err(e) => HttpResponse::BadRequest().body(e.to_string()),
}
}
Expand All @@ -584,7 +645,10 @@ pub async fn remove_pending_allocation(
.remove_pending_allocation(&query.id, &query.owner, &query.repo)
.await
{
Ok(()) => HttpResponse::Ok().body(serde_json::to_string_pretty("Success").unwrap()),
Ok(_) => HttpResponse::Ok().body(
serde_json::to_string_pretty("Success")
.expect("Serialization of static string should succeed"),
),
Err(e) => HttpResponse::BadRequest().body(e.to_string()),
}
}
Expand All @@ -601,7 +665,10 @@ pub async fn allocation_failed(query: web::Query<VerifierActionsQueryParams>) ->
.revert_to_ready_to_sign(&query.id, &query.owner, &query.repo)
.await
{
Ok(()) => HttpResponse::Ok().body(serde_json::to_string_pretty("Success").unwrap()),
Ok(_) => HttpResponse::Ok().body(
serde_json::to_string_pretty("Success")
.expect("Serialization of static string should succeed"),
),
Err(e) => HttpResponse::BadRequest().body(e.to_string()),
}
}
14 changes: 10 additions & 4 deletions fplus-http-server/src/router/autoallocator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,23 @@ pub async fn last_client_allocation(
query: web::Query<LastAutoallocationQueryParams>,
) -> impl Responder {
match autoallocations_db::get_last_client_autoallocation(query.evm_wallet_address).await {
Ok(last_client_allocation) => {
HttpResponse::Ok().body(serde_json::to_string_pretty(&last_client_allocation).unwrap())
}
Ok(last_client_allocation) => match serde_json::to_string_pretty(&last_client_allocation) {
Ok(response) => HttpResponse::Ok().body(response),
Err(_) => {
HttpResponse::InternalServerError().body("Failed to serialize success message")
}
},
Err(e) => HttpResponse::BadRequest().body(e.to_string()),
}
}

#[post("autoallocator/trigger_autoallocation")]
pub async fn trigger_autoallocation(info: web::Json<TriggerAutoallocationInfo>) -> impl Responder {
match autoallocator::trigger_autoallocation(&info.into_inner()).await {
Ok(()) => HttpResponse::Ok().body(serde_json::to_string_pretty("Success").unwrap()),
Ok(_) => HttpResponse::Ok().body(
serde_json::to_string_pretty("Success")
.expect("Serialization of static string should succeed"),
),
Err(e) => HttpResponse::BadRequest().body(e.to_string()),
}
}
Loading
Loading