From f9468c780f241aae39d419a9c06e8139a097871f Mon Sep 17 00:00:00 2001 From: Andrei <92177534+andrei-21@users.noreply.github.com> Date: Fri, 1 Dec 2023 10:42:51 +0000 Subject: [PATCH] Use perro macros (#81) --- crow/src/lib.rs | 43 +++++++++------------ graphql/Cargo.toml | 2 +- graphql/src/lib.rs | 16 ++++---- honey-badger/src/asynchronous/provider.rs | 38 +++++++++--------- honey-badger/src/provider.rs | 39 +++++++++---------- squirrel/src/lib.rs | 47 ++++++++++------------- 6 files changed, 85 insertions(+), 100 deletions(-) diff --git a/crow/src/lib.rs b/crow/src/lib.rs index d255976..f5513a8 100644 --- a/crow/src/lib.rs +++ b/crow/src/lib.rs @@ -1,4 +1,4 @@ -use graphql::perro::permanent_failure; +use graphql::perro::{ensure, permanent_failure}; use graphql::schema::list_uncompleted_topups::{topup_status_enum, ListUncompletedTopupsTopup}; use graphql::schema::{ hide_topup, list_uncompleted_topups, register_notification_token, register_topup, HideTopup, @@ -77,12 +77,13 @@ impl OfferManager { let access_token = self.auth.query_token()?; let client = build_client(Some(&access_token))?; let data = post_blocking::(&client, &self.backend_url, variables)?; - if !matches!( - data.register_topup, - Some(register_topup::RegisterTopupRegisterTopup { .. }) - ) { - return Err(permanent_failure("Backend rejected topup registration")); - } + ensure!( + matches!( + data.register_topup, + Some(register_topup::RegisterTopupRegisterTopup { .. }) + ), + permanent_failure("Backend rejected topup registration") + ); Ok(()) } @@ -100,17 +101,12 @@ impl OfferManager { let client = build_client(Some(&access_token))?; let data = post_blocking::(&client, &self.backend_url, variables)?; - if !matches!( + ensure!(matches!( data.register_notification_token, Some( register_notification_token::RegisterNotificationTokenRegisterNotificationToken { .. } ) - ) { - return Err(permanent_failure( - "Backend rejected notification token registration", - )); - } - + ), permanent_failure("Backend rejected notification token registration")); Ok(()) } @@ -147,8 +143,7 @@ fn to_topup_info(topup: ListUncompletedTopupsTopup) -> graphql::Result Some(parse_from_rfc3339(&e)?), None => None, }; @@ -160,19 +155,17 @@ fn to_topup_info(topup: ListUncompletedTopupsTopup) -> graphql::Result TopupStatus::REFUNDED, topup_status_enum::SETTLED => TopupStatus::SETTLED, topup_status_enum::REFUND_HIDDEN => { - return Err(runtime_error( + runtime_error!( graphql::GraphQlRuntimeErrorCode::CorruptData, - "The backend returned the unexpected status: REFUND_HIDDEN".to_string(), - )) + "The backend returned the unexpected status: REFUND_HIDDEN", + ); } topup_status_enum::Other(_) => { - return Err(runtime_error( + runtime_error!( graphql::GraphQlRuntimeErrorCode::CorruptData, - format!( - "The backend returned an unknown topup status: {:?}", - topup.status - ), - )) + "The backend returned an unknown topup status: {:?}", + topup.status + ); } }; diff --git a/graphql/Cargo.toml b/graphql/Cargo.toml index 66c045d..197cb19 100644 --- a/graphql/Cargo.toml +++ b/graphql/Cargo.toml @@ -10,4 +10,4 @@ log = "0.4.17" reqwest = { version = "0.11", default-features = false, features = ["json", "blocking", "rustls-tls"]} serde = { version = "1.0", features = ["derive"]} -perro = {git = "https://github.com/getlipa/perro", tag = "v1.1.0" } +perro = {git = "https://github.com/getlipa/perro", tag = "v1.2.0" } diff --git a/graphql/src/lib.rs b/graphql/src/lib.rs index 6559b40..d551661 100644 --- a/graphql/src/lib.rs +++ b/graphql/src/lib.rs @@ -67,15 +67,15 @@ pub fn post_blocking( Err(e) => { if is_502_status(e.status()) || e.to_string().contains("502") { // checking for the error containing 502 because reqwest is unexpectedly returning a decode error instead of status error - return Err(runtime_error( + runtime_error!( GraphQlRuntimeErrorCode::RemoteServiceUnavailable, "The remote server returned status 502", - )); + ); } - return Err(runtime_error( + runtime_error!( GraphQlRuntimeErrorCode::NetworkError, "Failed to execute the query", - )); + ); } }; get_response_data(response, backend_url) @@ -91,15 +91,15 @@ pub async fn post( Err(e) => { if is_502_status(e.status()) || e.to_string().contains("502") { // checking for the error containing 502 because reqwest is unexpectedly returning a decode error instead of status error - return Err(runtime_error( + runtime_error!( GraphQlRuntimeErrorCode::RemoteServiceUnavailable, "The remote server returned status 502", - )); + ); } - return Err(runtime_error( + runtime_error!( GraphQlRuntimeErrorCode::NetworkError, "Failed to execute the query", - )); + ); } }; get_response_data(response, backend_url) diff --git a/honey-badger/src/asynchronous/provider.rs b/honey-badger/src/asynchronous/provider.rs index d8dbd08..c18982d 100644 --- a/honey-badger/src/asynchronous/provider.rs +++ b/honey-badger/src/asynchronous/provider.rs @@ -3,7 +3,7 @@ use crate::signing::sign; use crate::provider::{add_bitcoin_message_prefix, add_hex_prefix}; use crate::{AuthLevel, TermsAndConditions}; -use graphql::perro::{invalid_input, permanent_failure, runtime_error, OptionToError}; +use graphql::perro::{ensure, invalid_input, permanent_failure, runtime_error, OptionToError}; use graphql::reqwest::Client; use graphql::schema::*; use graphql::{build_async_client, post}; @@ -68,25 +68,25 @@ impl AuthProvider { terms: TermsAndConditions, ) -> Result<()> { info!("Accepting T&C ({:?})...", terms); - if self.auth_level != AuthLevel::Pseudonymous { - return Err(invalid_input( - "Accepting T&C not supported for auth levels other than Pseudonymous", - )); - } + ensure!( + self.auth_level == AuthLevel::Pseudonymous, + invalid_input("Accepting T&C not supported for auth levels other than Pseudonymous") + ); let variables = accept_terms_and_conditions::Variables { service_provider: terms.into(), }; let client = build_async_client(Some(&access_token))?; let data = post::(&client, &self.backend_url, variables).await?; - if !matches!( - data.accept_terms_conditions, - Some(accept_terms_and_conditions::AcceptTermsAndConditionsAcceptTermsConditions { .. }) - ) { - return Err(permanent_failure( - "Backend rejected accepting Terms and Conditions", - )); - } + ensure!( + matches!( + data.accept_terms_conditions, + Some( + accept_terms_and_conditions::AcceptTermsAndConditionsAcceptTermsConditions { .. } + ) + ), + permanent_failure("Backend rejected accepting Terms and Conditions") + ); Ok(()) } @@ -226,12 +226,10 @@ impl AuthProvider { if let Some(access_expires_at) = result.access_expires_at.as_ref() { let access_expires_at = parse_from_rfc3339(access_expires_at)?; - if SystemTime::now() > access_expires_at { - return Err(runtime_error( - GraphQlRuntimeErrorCode::AccessExpired, - "Access expired", - )); - } + ensure!( + SystemTime::now() <= access_expires_at, + runtime_error(GraphQlRuntimeErrorCode::AccessExpired, "Access expired") + ); } info!("Owner: {:?}", result.owner_wallet_pub_key_id); Ok(result.owner_wallet_pub_key_id.clone()) diff --git a/honey-badger/src/provider.rs b/honey-badger/src/provider.rs index 656a446..7296e1b 100644 --- a/honey-badger/src/provider.rs +++ b/honey-badger/src/provider.rs @@ -1,7 +1,7 @@ use crate::secrets::KeyPair; use crate::signing::sign; -use graphql::perro::{invalid_input, permanent_failure, runtime_error, OptionToError}; +use graphql::perro::{ensure, invalid_input, permanent_failure, runtime_error, OptionToError}; use graphql::reqwest::blocking::Client; use graphql::schema::*; use graphql::{build_client, post_blocking}; @@ -89,11 +89,10 @@ impl AuthProvider { terms: TermsAndConditions, ) -> Result<()> { info!("Accepting T&C ({:?})...", terms); - if self.auth_level != AuthLevel::Pseudonymous { - return Err(invalid_input( - "Accepting T&C not supported for auth levels other than Pseudonymous", - )); - } + ensure!( + self.auth_level == AuthLevel::Pseudonymous, + invalid_input("Accepting T&C not supported for auth levels other than Pseudonymous") + ); let variables = accept_terms_and_conditions::Variables { service_provider: terms.into(), @@ -101,14 +100,16 @@ impl AuthProvider { let client = build_client(Some(&access_token))?; let data = post_blocking::(&client, &self.backend_url, variables)?; - if !matches!( - data.accept_terms_conditions, - Some(accept_terms_and_conditions::AcceptTermsAndConditionsAcceptTermsConditions { .. }) - ) { - return Err(permanent_failure( - "Backend rejected accepting Terms and Conditions", - )); - } + ensure!( + matches!( + data.accept_terms_conditions, + Some( + accept_terms_and_conditions::AcceptTermsAndConditionsAcceptTermsConditions { .. } + ) + ), + permanent_failure("Backend rejected accepting Terms and Conditions") + ); + Ok(()) } @@ -243,12 +244,10 @@ impl AuthProvider { if let Some(access_expires_at) = result.access_expires_at.as_ref() { let access_expires_at = parse_from_rfc3339(access_expires_at)?; - if SystemTime::now() > access_expires_at { - return Err(runtime_error( - GraphQlRuntimeErrorCode::AccessExpired, - "Access expired", - )); - } + ensure!( + SystemTime::now() <= access_expires_at, + runtime_error(GraphQlRuntimeErrorCode::AccessExpired, "Access expired") + ); } info!("Owner: {:?}", result.owner_wallet_pub_key_id); Ok(result.owner_wallet_pub_key_id.clone()) diff --git a/squirrel/src/lib.rs b/squirrel/src/lib.rs index e1cc33a..1558433 100644 --- a/squirrel/src/lib.rs +++ b/squirrel/src/lib.rs @@ -1,5 +1,5 @@ use graphql::errors::*; -use graphql::perro::{runtime_error, MapToError, OptionToError}; +use graphql::perro::{MapToError, OptionToError}; use graphql::schema::*; use graphql::{build_async_client, post}; use honey_badger::asynchronous::Auth; @@ -43,31 +43,26 @@ impl RemoteBackupClient { }; let data = post::(&client, &self.backend_url, variables).await?; - match data.recover_backup { - None => Err(runtime_error( - GraphQlRuntimeErrorCode::ObjectNotFound, - "No backup found with the provided schema name", - )), - Some(d) => { - let encrypted_backup = - graphql_hex_decode(&d.encrypted_backup.ok_or_runtime_error( - GraphQlRuntimeErrorCode::ObjectNotFound, - "No backup found with the provided schema name", - )?) - .map_to_runtime_error( - GraphQlRuntimeErrorCode::CorruptData, - "Encrypted backup invalid hex", - )?; - let schema_version = d.schema_version.ok_or_permanent_failure( - "Backend returned encrypted backup but no schema version", - )?; - Ok(Backup { - encrypted_backup, - schema_name: schema_name.to_string(), - schema_version, - }) - } - } + let d = data.recover_backup.ok_or_runtime_error( + GraphQlRuntimeErrorCode::ObjectNotFound, + "No backup found with the provided schema name", + )?; + let encrypted_backup = graphql_hex_decode(&d.encrypted_backup.ok_or_runtime_error( + GraphQlRuntimeErrorCode::ObjectNotFound, + "No backup found with the provided schema name", + )?) + .map_to_runtime_error( + GraphQlRuntimeErrorCode::CorruptData, + "Encrypted backup invalid hex", + )?; + let schema_version = d + .schema_version + .ok_or_permanent_failure("Backend returned encrypted backup but no schema version")?; + Ok(Backup { + encrypted_backup, + schema_name: schema_name.to_string(), + schema_version, + }) } }