Skip to content

Commit

Permalink
Use perro macros (#81)
Browse files Browse the repository at this point in the history
  • Loading branch information
andrei-21 authored Dec 1, 2023
1 parent 0e0acc2 commit f9468c7
Show file tree
Hide file tree
Showing 6 changed files with 85 additions and 100 deletions.
43 changes: 18 additions & 25 deletions crow/src/lib.rs
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -77,12 +77,13 @@ impl OfferManager {
let access_token = self.auth.query_token()?;
let client = build_client(Some(&access_token))?;
let data = post_blocking::<RegisterTopup>(&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(())
}

Expand All @@ -100,17 +101,12 @@ impl OfferManager {
let client = build_client(Some(&access_token))?;
let data =
post_blocking::<RegisterNotificationToken>(&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(())
}

Expand Down Expand Up @@ -147,8 +143,7 @@ fn to_topup_info(topup: ListUncompletedTopupsTopup) -> graphql::Result<TopupInfo
let topup_value_minor_units = (topup.amount_user_currency * 100_f64).round() as u64;
let exchange_fee_rate_permyriad = (topup.exchange_fee_rate * 10_000_f64).round() as u16;
let exchange_fee_minor_units = (topup.exchange_fee_user_currency * 100_f64).round() as u64;
let expires_at = topup.expires_at;
let expires_at = match expires_at {
let expires_at = match topup.expires_at {
Some(e) => Some(parse_from_rfc3339(&e)?),
None => None,
};
Expand All @@ -160,19 +155,17 @@ fn to_topup_info(topup: ListUncompletedTopupsTopup) -> graphql::Result<TopupInfo
topup_status_enum::REFUNDED => 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
);
}
};

Expand Down
2 changes: 1 addition & 1 deletion graphql/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
16 changes: 8 additions & 8 deletions graphql/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,15 +67,15 @@ pub fn post_blocking<Query: graphql_client::GraphQLQuery>(
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)
Expand All @@ -91,15 +91,15 @@ pub async fn post<Query: graphql_client::GraphQLQuery>(
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)
Expand Down
38 changes: 18 additions & 20 deletions honey-badger/src/asynchronous/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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::<AcceptTermsAndConditions>(&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(())
}

Expand Down Expand Up @@ -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())
Expand Down
39 changes: 19 additions & 20 deletions honey-badger/src/provider.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand Down Expand Up @@ -89,26 +89,27 @@ 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_client(Some(&access_token))?;
let data =
post_blocking::<AcceptTermsAndConditions>(&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(())
}

Expand Down Expand Up @@ -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())
Expand Down
47 changes: 21 additions & 26 deletions squirrel/src/lib.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -43,31 +43,26 @@ impl RemoteBackupClient {
};
let data = post::<RecoverBackup>(&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,
})
}
}

Expand Down

0 comments on commit f9468c7

Please sign in to comment.