Skip to content

Commit

Permalink
Move httpmocks, rename error to AgencyClientError
Browse files Browse the repository at this point in the history
Signed-off-by: Miroslav Kovar <miroslavkovar@protonmail.com>
  • Loading branch information
mirgee committed Nov 13, 2020
1 parent 63af688 commit ec6cc7a
Show file tree
Hide file tree
Showing 21 changed files with 234 additions and 242 deletions.
40 changes: 16 additions & 24 deletions agency_client/src/agency_settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::sync::RwLock;
use serde_json::Value;
use url::Url;

use crate::utils::error::{AgencyCommErrorKind, AgencyCommError, VcxResult};
use crate::utils::error::{AgencyClientErrorKind, AgencyClientError, VcxResult};
use crate::utils::{error_utils, validation};

pub static CONFIG_AGENCY_ENDPOINT: &str = "agency_endpoint";
Expand Down Expand Up @@ -33,20 +33,12 @@ lazy_static! {
}


fn validate_mandatory_config_val<F, S, E>(val: Option<&String>, err: AgencyCommErrorKind, closure: F) -> VcxResult<u32>
where F: Fn(&str) -> Result<S, E> {
closure(val.as_ref().ok_or(AgencyCommError::from(err))?)
.or(Err(AgencyCommError::from(err)))?;

Ok(error_utils::SUCCESS.code_num)
}

fn validate_optional_config_val<F, S, E>(val: Option<&String>, err: AgencyCommErrorKind, closure: F) -> VcxResult<u32>
fn validate_optional_config_val<F, S, E>(val: Option<&String>, err: AgencyClientErrorKind, closure: F) -> VcxResult<u32>
where F: Fn(&str) -> Result<S, E> {
if val.is_none() { return Ok(error_utils::SUCCESS.code_num); }

closure(val.as_ref().ok_or(AgencyCommError::from(AgencyCommErrorKind::InvalidConfiguration))?)
.or(Err(AgencyCommError::from(err)))?;
closure(val.as_ref().ok_or(AgencyClientError::from(AgencyClientErrorKind::InvalidConfiguration))?)
.or(Err(AgencyClientError::from(err)))?;

Ok(error_utils::SUCCESS.code_num)
}
Expand Down Expand Up @@ -82,16 +74,16 @@ pub fn validate_agency_config(config: &HashMap<String, String>) -> VcxResult<u32
trace!("validate_agency_config >>> config: {:?}", config);

// todo: Since we scope these setting to agency module, these are not really optional anymore!
validate_optional_config_val(config.get(CONFIG_AGENCY_DID), AgencyCommErrorKind::InvalidDid, validation::validate_did)?;
validate_optional_config_val(config.get(CONFIG_AGENCY_VERKEY), AgencyCommErrorKind::InvalidVerkey, validation::validate_verkey)?;
validate_optional_config_val(config.get(CONFIG_AGENCY_DID), AgencyClientErrorKind::InvalidDid, validation::validate_did)?;
validate_optional_config_val(config.get(CONFIG_AGENCY_VERKEY), AgencyClientErrorKind::InvalidVerkey, validation::validate_verkey)?;

validate_optional_config_val(config.get(CONFIG_SDK_TO_REMOTE_DID), AgencyCommErrorKind::InvalidDid, validation::validate_did)?;
validate_optional_config_val(config.get(CONFIG_SDK_TO_REMOTE_VERKEY), AgencyCommErrorKind::InvalidVerkey, validation::validate_verkey)?;
validate_optional_config_val(config.get(CONFIG_SDK_TO_REMOTE_DID), AgencyClientErrorKind::InvalidDid, validation::validate_did)?;
validate_optional_config_val(config.get(CONFIG_SDK_TO_REMOTE_VERKEY), AgencyClientErrorKind::InvalidVerkey, validation::validate_verkey)?;

validate_optional_config_val(config.get(CONFIG_REMOTE_TO_SDK_DID), AgencyCommErrorKind::InvalidDid, validation::validate_did)?;
validate_optional_config_val(config.get(CONFIG_REMOTE_TO_SDK_VERKEY), AgencyCommErrorKind::InvalidVerkey, validation::validate_verkey)?;
validate_optional_config_val(config.get(CONFIG_REMOTE_TO_SDK_DID), AgencyClientErrorKind::InvalidDid, validation::validate_did)?;
validate_optional_config_val(config.get(CONFIG_REMOTE_TO_SDK_VERKEY), AgencyClientErrorKind::InvalidVerkey, validation::validate_verkey)?;

validate_optional_config_val(config.get(CONFIG_AGENCY_ENDPOINT), AgencyCommErrorKind::InvalidUrl, Url::parse)?;
validate_optional_config_val(config.get(CONFIG_AGENCY_ENDPOINT), AgencyClientErrorKind::InvalidUrl, Url::parse)?;

Ok(error_utils::SUCCESS.code_num)
}
Expand All @@ -101,7 +93,7 @@ pub fn process_agency_config_string(config: &str, do_validation: bool) -> VcxRes
trace!("process_config_string >>> config {}", config);

let configuration: Value = serde_json::from_str(config)
.map_err(|err| AgencyCommError::from_msg(AgencyCommErrorKind::InvalidJson, format!("Cannot parse config: {}", err)))?;
.map_err(|err| AgencyClientError::from_msg(AgencyClientErrorKind::InvalidJson, format!("Cannot parse config: {}", err)))?;

if let Value::Object(ref map) = configuration {
for (key, value) in map {
Expand All @@ -111,7 +103,7 @@ pub fn process_agency_config_string(config: &str, do_validation: bool) -> VcxRes
match value {
Value::String(value_) => set_config_value(key, &value_),
Value::Bool(value_) => set_config_value(key, &json!(value_).to_string()),
_ => return Err(AgencyCommError::from_msg(AgencyCommErrorKind::InvalidJson,
_ => return Err(AgencyClientError::from_msg(AgencyClientErrorKind::InvalidJson,
format!("Invalid agency config value for key {}", key))),
}
}
Expand All @@ -120,7 +112,7 @@ pub fn process_agency_config_string(config: &str, do_validation: bool) -> VcxRes

if do_validation {
let setting = AGENCY_SETTINGS.read()
.or(Err(AgencyCommError::from(AgencyCommErrorKind::InvalidConfiguration)))?;
.or(Err(AgencyClientError::from(AgencyClientErrorKind::InvalidConfiguration)))?;
validate_agency_config(&setting.borrow())
} else {
Ok(error_utils::SUCCESS.code_num)
Expand All @@ -133,10 +125,10 @@ pub fn get_config_value(key: &str) -> VcxResult<String> {

AGENCY_SETTINGS
.read()
.or(Err(AgencyCommError::from_msg(AgencyCommErrorKind::InvalidConfiguration, "Cannot read AGENCY_SETTINGS")))?
.or(Err(AgencyClientError::from_msg(AgencyClientErrorKind::InvalidConfiguration, "Cannot read AGENCY_SETTINGS")))?
.get(key)
.map(|v| v.to_string())
.ok_or(AgencyCommError::from_msg(AgencyCommErrorKind::InvalidConfiguration, format!("Cannot read \"{}\" from AGENCY_SETTINGS", key)))
.ok_or(AgencyClientError::from_msg(AgencyClientErrorKind::InvalidConfiguration, format!("Cannot read \"{}\" from AGENCY_SETTINGS", key)))
}

pub fn set_config_value(key: &str, value: &str) {
Expand Down
8 changes: 4 additions & 4 deletions agency_client/src/create_key.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::utils::error::{AgencyCommErrorKind, VcxResult, AgencyCommError};
use crate::utils::error::{AgencyClientErrorKind, VcxResult, AgencyClientError};
use crate::{A2AMessageV2, A2AMessage, parse_response_from_agency, prepare_message_for_agency, agency_settings, A2AMessageKinds, mocking};
use crate::message_type::MessageTypes;
use crate::utils::comm::post_to_agency;
Expand Down Expand Up @@ -88,15 +88,15 @@ impl CreateKeyBuilder {
let mut response = parse_response_from_agency(response)?;
match response.remove(0) {
A2AMessage::Version2(A2AMessageV2::CreateKeyResponse(res)) => Ok((res.for_did, res.for_verkey)),
_ => Err(AgencyCommError::from(AgencyCommErrorKind::InvalidHttpResponse))
_ => Err(AgencyClientError::from(AgencyClientErrorKind::InvalidHttpResponse))
}
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::utils::error::AgencyCommErrorKind;
use crate::utils::error::AgencyClientErrorKind;
use crate::create_keys;
use crate::utils::constants;
use crate::utils::test_utils::SetupMocks;
Expand Down Expand Up @@ -145,7 +145,7 @@ mod tests {
let res = CreateKeyBuilder::create()
.for_did(for_did)
.unwrap_err();
assert_eq!(res.kind(), AgencyCommErrorKind::InvalidDid);
assert_eq!(res.kind(), AgencyClientErrorKind::InvalidDid);
}
}

16 changes: 8 additions & 8 deletions agency_client/src/get_message.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::{get_messages, MessageStatusCode, prepare_message_for_agent, A2AMessageKinds, A2AMessageV2, A2AMessage, GeneralMessage, parse_response_from_agency, prepare_message_for_agency, agency_settings, mocking};
use crate::utils::error::{VcxResult, AgencyCommErrorKind, AgencyCommError};
use crate::utils::error::{VcxResult, AgencyClientErrorKind, AgencyClientError};
use crate::utils::encryption_envelope::EncryptionEnvelope;
use crate::utils::comm::post_to_agency;
use crate::message_type::MessageTypes;
Expand Down Expand Up @@ -137,7 +137,7 @@ impl GetMessagesBuilder {
trace!("Interpreting response as V2");
Ok(res.msgs)
}
_ => Err(AgencyCommError::from_msg(AgencyCommErrorKind::InvalidHttpResponse, "Message does not match any variant of GetMessagesResponse"))
_ => Err(AgencyClientError::from_msg(AgencyClientErrorKind::InvalidHttpResponse, "Message does not match any variant of GetMessagesResponse"))
}
}

Expand Down Expand Up @@ -180,7 +180,7 @@ impl GetMessagesBuilder {
trace!("parse_download_messages_response: parsed response {:?}", response);
let msgs = match response.remove(0) {
A2AMessage::Version2(A2AMessageV2::GetMessagesByConnectionsResponse(res)) => res.msgs,
_ => return Err(AgencyCommError::from_msg(AgencyCommErrorKind::InvalidHttpResponse, "Message does not match any variant of GetMessagesByConnectionsResponse"))
_ => return Err(AgencyClientError::from_msg(AgencyClientErrorKind::InvalidHttpResponse, "Message does not match any variant of GetMessagesByConnectionsResponse"))
};

msgs
Expand Down Expand Up @@ -257,8 +257,8 @@ macro_rules! convert_aries_message {
impl Message {
pub fn payload(&self) -> VcxResult<Vec<u8>> {
match self.payload {
Some(MessagePayload::V2(ref payload)) => serde_json::to_vec(payload).map_err(|err| AgencyCommError::from_msg(AgencyCommErrorKind::InvalidHttpResponse, err)),
_ => Err(AgencyCommError::from(AgencyCommErrorKind::InvalidState)),
Some(MessagePayload::V2(ref payload)) => serde_json::to_vec(payload).map_err(|err| AgencyClientError::from_msg(AgencyClientErrorKind::InvalidHttpResponse, err)),
_ => Err(AgencyClientError::from(AgencyClientErrorKind::InvalidState)),
}
}

Expand Down Expand Up @@ -303,7 +303,7 @@ pub fn get_connection_messages(pw_did: &str, pw_vk: &str, agent_did: &str, agent
.uid(msg_uid)?
.status_codes(status_codes)?
.send_secure()
.map_err(|err| err.map(AgencyCommErrorKind::PostMessageFailed, "Cannot get messages"))?;
.map_err(|err| err.map(AgencyClientErrorKind::PostMessageFailed, "Cannot get messages"))?;

trace!("message returned: {:?}", response);
Ok(response)
Expand All @@ -316,7 +316,7 @@ pub fn parse_status_codes(status_codes: Option<Vec<String>>) -> VcxResult<Option
.iter()
.map(|code|
::serde_json::from_str::<MessageStatusCode>(&format!("\"{}\"", code))
.map_err(|err| AgencyCommError::from_msg(AgencyCommErrorKind::InvalidJson, format!("Cannot parse message status code: {}", err)))
.map_err(|err| AgencyClientError::from_msg(AgencyClientErrorKind::InvalidJson, format!("Cannot parse message status code: {}", err)))
).collect::<VcxResult<Vec<MessageStatusCode>>>()?;
Ok(Some(codes))
}
Expand All @@ -330,7 +330,7 @@ pub fn parse_connection_handles(conn_handles: Vec<String>) -> VcxResult<Vec<u32>
.iter()
.map(|handle|
::serde_json::from_str::<u32>(handle)
.map_err(|err| AgencyCommError::from_msg(AgencyCommErrorKind::InvalidJson, format!("Cannot parse connection handles: {}", err)))
.map_err(|err| AgencyClientError::from_msg(AgencyClientErrorKind::InvalidJson, format!("Cannot parse connection handles: {}", err)))
).collect::<VcxResult<Vec<u32>>>()?;
Ok(codes)
}
Expand Down
39 changes: 6 additions & 33 deletions agency_client/src/httpclient.rs
Original file line number Diff line number Diff line change
@@ -1,39 +1,12 @@
use std::env;
use std::io::Read;
use std::sync::Mutex;

use reqwest;
use reqwest::header::CONTENT_TYPE;

use crate::utils::error::{AgencyCommErrorKind, AgencyCommError, VcxResult};
use crate::mocking::{AgencyMock, AgencyMockDecrypted};
use crate::utils::error::{AgencyClientErrorKind, AgencyClientError, VcxResult};
use crate::mocking::{AgencyMock, AgencyMockDecrypted, HttpClientMockResponse};
use crate::mocking;

lazy_static! {
static ref HTTPCLIENT_MOCK_RESPONSES: Mutex<HttpClientMockResponse> = Mutex::new(HttpClientMockResponse::default());
}

#[derive(Default)]
pub struct HttpClientMockResponse {
responses: Vec<VcxResult<Vec<u8>>>
}

impl HttpClientMockResponse {
pub fn set_next_response(response: VcxResult<Vec<u8>>) {
if mocking::agency_mocks_enabled() {
HTTPCLIENT_MOCK_RESPONSES.lock().unwrap().responses.push(response);
}
}

pub fn has_response() -> bool {
HTTPCLIENT_MOCK_RESPONSES.lock().unwrap().responses.len() > 0
}

pub fn get_response() -> VcxResult<Vec<u8>> {
HTTPCLIENT_MOCK_RESPONSES.lock().unwrap().responses.pop().unwrap()
}
}

pub fn post_message(body_content: &Vec<u8>, url: &str) -> VcxResult<Vec<u8>> {
// todo: this function should be general, not knowing that agency exists -> move agency mocks to agency module
if mocking::agency_mocks_enabled() {
Expand All @@ -57,7 +30,7 @@ pub fn post_message(body_content: &Vec<u8>, url: &str) -> VcxResult<Vec<u8>> {
}
let client = reqwest::ClientBuilder::new().timeout(crate::utils::timeout::TimeoutUtils::long_timeout()).build().map_err(|err| {
error!("error: {}", err);
AgencyCommError::from_msg(AgencyCommErrorKind::PostMessageFailed, format!("Building reqwest client failed: {:?}", err))
AgencyClientError::from_msg(AgencyClientErrorKind::PostMessageFailed, format!("Building reqwest client failed: {:?}", err))
})?;
debug!("Posting encrypted bundle to: \"{}\"", url);

Expand All @@ -68,7 +41,7 @@ pub fn post_message(body_content: &Vec<u8>, url: &str) -> VcxResult<Vec<u8>> {
.send()
.map_err(|err| {
error!("error: {}", err);
AgencyCommError::from_msg(AgencyCommErrorKind::PostMessageFailed, format!("Could not connect {:?}", err))
AgencyClientError::from_msg(AgencyClientErrorKind::PostMessageFailed, format!("Could not connect {:?}", err))
})?;

trace!("Response Header: {:?}", response);
Expand All @@ -78,12 +51,12 @@ pub fn post_message(body_content: &Vec<u8>, url: &str) -> VcxResult<Vec<u8>> {
Ok(_) => info!("Request failed: {}", content),
Err(_) => info!("could not read response"),
};
return Err(AgencyCommError::from_msg(AgencyCommErrorKind::PostMessageFailed, format!("POST failed with: {}", content)));
return Err(AgencyClientError::from_msg(AgencyClientErrorKind::PostMessageFailed, format!("POST failed with: {}", content)));
}

let mut content = Vec::new();
response.read_to_end(&mut content)
.or(Err(AgencyCommError::from_msg(AgencyCommErrorKind::PostMessageFailed, "could not read response")))?;
.or(Err(AgencyClientError::from_msg(AgencyClientErrorKind::PostMessageFailed, "could not read response")))?;

Ok(content)
}
Expand Down
Loading

0 comments on commit ec6cc7a

Please sign in to comment.