Skip to content

Commit

Permalink
feat: json logger
Browse files Browse the repository at this point in the history
Signed-off-by: blu3beri <[email protected]>
  • Loading branch information
berendsliedrecht committed Apr 28, 2023
1 parent d8b6128 commit 204a1ff
Show file tree
Hide file tree
Showing 32 changed files with 367 additions and 257 deletions.
3 changes: 2 additions & 1 deletion .cargo/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ rustflags = ["-D", "clippy::all",
"-D", "clippy::missing_docs_in_private_items",
"-A", "clippy::only_used_in_recursion",
"-A", "clippy::struct_excessive_bools",
"-A", "clippy::module_name_repetitions"]
"-A", "clippy::module_name_repetitions",
"-A", "clippy::almost_swapped"]
9 changes: 9 additions & 0 deletions .github/workflows/check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ name: Check
permissions:
contents: read

env:
RUST_VERSION: "1.60.0"
CROSS_VERSION: "0.2.4"

on:
pull_request:
push:
Expand Down Expand Up @@ -39,6 +43,7 @@ jobs:
- name: Install stable
uses: dtolnay/rust-toolchain@stable
with:
toolchain: ${{ env.RUST_VERSION }}
components: clippy

- name: Cache cargo resources
Expand All @@ -59,6 +64,8 @@ jobs:
- uses: actions/checkout@v3
- name: Install stable
uses: dtolnay/rust-toolchain@stable
with:
toolchain: ${{ env.RUST_VERSION }}

- name: Cache cargo resources
uses: Swatinem/rust-cache@v2
Expand All @@ -78,6 +85,8 @@ jobs:
- uses: actions/checkout@v3
- name: Install stable
uses: dtolnay/rust-toolchain@stable
with:
toolchain: ${{ env.RUST_VERSION }}

- name: Cache cargo resources
uses: Swatinem/rust-cache@v2
Expand Down
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion crates/afj-rest/src/cloudagent/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ impl ConnectionModule for CloudAgentAfjRest {
);

if has_defined_value {
log_warn!("Additional options are ignored on this endpoint.");
warn!({ "message": "Additional options are ignored on this endpoint"});
}
let url = self.create_url(&["connections"])?;

Expand Down
19 changes: 7 additions & 12 deletions crates/afj-rest/src/web.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@ impl CloudAgentAfjRest {
None => Client::new().get(url),
};

log_trace!("Get request query:");
log_trace!("{:#?}", query);
trace!({ "message": "Get request query", "query": query });

self.send::<T>(client).await
}
Expand All @@ -45,10 +44,7 @@ impl CloudAgentAfjRest {
None => client,
};

log_trace!("Post request body:");
log_trace!("{:#?}", body);
log_trace!("Post request query:");
log_trace!("{:#?}", query);
trace!({ "message": "Post request body", "body": body, "query": query });

self.send::<T>(client).await
}
Expand All @@ -59,16 +55,15 @@ impl CloudAgentAfjRest {
///
/// When it could not fulfill the given request
pub async fn send<T: DeserializeOwned>(&self, client: RequestBuilder) -> Result<T> {
log_trace!("About to send request:");
log_trace!("{:#?}", client);
trace!({ "message": "About to send request" });

match client.send().await {
Ok(res) => {
let status_code = res.status().as_u16();
log_trace!("Got {} response:", status_code);
log_trace!("{:#?}", res);
debug!({ "status_code": status_code });
match status_code {
200..=299 => res.json().await.map_err(|e| {
log_warn!("{}", e);
warn!({"error": e.to_string() });
Error::UnableToParseResponse.into()
}),
// Issue credential message when attributes are not correct
Expand All @@ -84,7 +79,7 @@ impl CloudAgentAfjRest {
}
}
Err(e) => {
log_warn!("Request failed {}", e);
warn!({ "message": "request failed", "error": e.to_string()});
Err(Error::UnreachableUrl.into())
}
}
Expand Down
2 changes: 1 addition & 1 deletion crates/agent/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ impl Display for Error {
Error::AuthorizationFailed => write!(f, "Failed to authorize. Api-key or authorization token is either wrong or missing."),
Error::UnableToParseResponse => write!(f, "Unable to parse the response from the server. Is the cloudagent the correct version?"),
Error::UrlDoesNotExist => write!(f, "Path does not exist on agent URL. This can happen when querying by id and the id is not valid or when attempting to use a feature that is not supported on the cloudagent."),
Error::UnknownResponseStatusCode(msg) => write!(f, "Received unknown status code from the server. Agent URL is likely incorrect. If the agent URL is correct, please report this error at https://github.com/animo/siera/issues/new \nAdditional info: {msg}"),
Error::UnknownResponseStatusCode(msg) => write!(f, "Received unknown status code from the server. Agent URL is likely incorrect. If the agent URL is correct, please report this error at https://github.com/animo/siera/issues/new Additional info: {msg}"),
Error::InternalServerError(status, msg) => write!(f, "Internal Server Error (status code: {status})! Message: {msg}"),
Error::UnreachableUrl => write!(f, "Provided url is unreachable. Is the provided agent URL valid?"),
Error::HttpServiceUnavailable => write!(f, "Cloudagent is currently unavailable. Are you sure the agent is online?"),
Expand Down
17 changes: 5 additions & 12 deletions crates/automations/src/automations/create_credential_definition.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
use crate::error::Result;
use siera_agent::modules::credential_definition::CredentialDefinitionCreateOptions;
use siera_agent::modules::credential_definition::CredentialDefinitionCreateResponse;
use siera_agent::modules::credential_definition::CredentialDefinitionModule;
use siera_agent::modules::schema::{SchemaCreateOptions, SchemaModule};

use colored::Colorize;

use crate::error::Result;

/// Automation for creating a credential definition
pub struct CreateCredentialDefinition<'a> {
/// Schema name
Expand Down Expand Up @@ -51,16 +48,12 @@ impl<'a> CreateCredentialDefinition<'a> {
..CredentialDefinitionCreateOptions::default()
};

log!("{} the credential definition...", "Registering".cyan());
info!({"message": "Registering the credential definition"});
// Create or fetch the credential definition
let credential_definition = CredentialDefinitionModule::create(agent, options).await?;

log!(
"{} credential definition with id {}",
"Created".green(),
String::from(&credential_definition.credential_definition_id).green()
);
copy!("{}", credential_definition.credential_definition_id);
let id = credential_definition.credential_definition_id.clone();
info!({ "message": "Created credential definition", "credential_definition_id": &id});
copy!("{}", &id);
Ok(credential_definition)
}
}
27 changes: 19 additions & 8 deletions crates/automations/src/automations/credential_offer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use crate::{
automations::create_credential_definition::CreateCredentialDefinition,
error::{Error, Result},
};
use colored::Colorize;
use siera_agent::modules::{
connection::ConnectionModule,
credential::{CredentialModule, CredentialOfferOptions},
Expand Down Expand Up @@ -40,9 +39,11 @@ impl CredentialOfferAutomation {
+ Send
+ Sync,
) -> Result<()> {
log_trace!("Starting automation CredentialOfferAutomation");
log_trace!("{}", self.connection_id);
log_trace!("{:#?}", self.attributes);
info!({ "message": "Starting automation CredentialOfferAutomation" });
trace!({
"connection_id": self.connection_id,
"attributes": self.attributes
});
let attribute_keys: Vec<&str> = self
.attributes
.keys()
Expand All @@ -51,7 +52,10 @@ impl CredentialOfferAutomation {
let attribute_values: Vec<String> = self.attributes.values().cloned().collect();

// Check if it as a valid connection
log!("{} the connection...", "Fetching".cyan());
info! ({
"message": "Fetching the connection..."
});

let connection = ConnectionModule::get_by_id(&agent, self.connection_id.clone()).await?;
if connection.state != "active" && connection.state != "response" {
return Err(Error::ConnectionNotReady.into());
Expand All @@ -65,7 +69,10 @@ impl CredentialOfferAutomation {

let credential_definition = create_credential_definition.execute(&agent).await?;

log!("{} the credential...", "Offering".cyan());
info!({
"message": "Offering the credential..."
});

let credential_offer_response = agent
.send_offer(CredentialOfferOptions {
keys: attribute_keys.iter().map(|x| String::from(*x)).collect(),
Expand All @@ -75,8 +82,12 @@ impl CredentialOfferAutomation {
})
.await?;

log_trace!("Automation completed and offered a credential");
log_trace!("{:#?}", credential_offer_response);
trace!({
"message": "Automation completed and offered a credential"
});

trace!({ "credential_offer_response": credential_offer_response });

Ok(())
}
}
4 changes: 4 additions & 0 deletions crates/cli/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ pub struct Cli {
#[clap(long, short, help = HelpStrings::Copy)]
pub copy: bool,

/// Whether specific output should be copied to the clipboard
#[clap(long = "json", short = 'j', help = HelpStrings::OutputJson)]
pub output_json: bool,

/// Whether the output should be quiet
#[clap(long, short, help = HelpStrings::Quiet, conflicts_with = "verbose")]
pub quiet: bool,
Expand Down
2 changes: 2 additions & 0 deletions crates/cli/src/help_strings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ pub enum HelpStrings {
Agent,
ApiKey,
Copy,
OutputJson,
Quiet,
Verbose,
Config,
Expand Down Expand Up @@ -161,6 +162,7 @@ impl HelpStrings {
Self::Agent => "Type of Aries agent (aca-py or afj) [default: aca-py]",
Self::ApiKey => "This API key will be passed to the agent",
Self::Copy => "Copy output to your clipboard",
Self::OutputJson => "Output format will be JSON",
Self::Quiet => "Suppresses most output",
Self::Verbose => "Print debug logs",
Self::Config => "Supply a path to your configuration file to use that instead of the default",
Expand Down
2 changes: 1 addition & 1 deletion crates/cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ async fn main() {
match register().await {
Ok(_) => (),
Err(e) => {
log_error!("{}", e);
error!({"error": e.to_string()});
std::process::exit(1);
}
}
Expand Down
59 changes: 31 additions & 28 deletions crates/cli/src/modules/automation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,52 +99,55 @@ pub async fn parse_automation_args(
agent.receive_invitation(invitation_object).await?;
} else {
if !no_qr {
log!("{} the QR code to accept the invitation", "Scan".bold(),);
info!({ "message": "Scan the QR code to accept the invitation"});
qr::print_qr_code(&connection.invitation_url)?;
}
log!();
log!();
log!("================");
log!("{}", "Credential offer".bold());
log!("================");
log!();
println!();
println!();
info!({ "message": "Credential offer" });
println!();

log!(
"{} invitation with connection id {}.",
"Created".green(),
connection.id.bold()
);
log!();
log!("Use this URL:\n\n{}", connection.invitation_url);
log!();
log!();
log!(
"{} for the invitation to be accepted. Timeout is {} seconds...",
"Waiting".cyan(),
timeout
);
info!({
"message":
format!(
"{} invitation with connection id {}.",
"Created".green(),
connection.id.bold()
)
});
println!();
info!({"message": "Use this URL", "invitation_url": connection.invitation_url });
println!();
println!();
info!({
"message":
format!(
"{} for the invitation to be accepted. Timeout is {timeout} seconds...",
"Waiting".cyan(),
)
});
copy!("{}", connection.invitation_url);
}
log_debug!("Looping {} times", timeout);
debug!({ "message": format!("Looping {timeout} times") });
for i in 1..=*timeout {
let connection =
ConnectionModule::get_by_id(&agent, connection.id.clone()).await?;
if connection.state != "active" && connection.state != "response" {
log_trace!(
trace!({ "message":
"Connection state is not active, waiting 1 second then trying again..."
);
});
std::thread::sleep(std::time::Duration::from_millis(1000));
} else {
log!("Invitation {}!", "accepted".green());
info!({ "message": format!("Invitation {}!", "accepted".green()) });
credential_offer(connection.id, agent).await?;
break;
}
if i == *timeout {
return Err(Error::InactiveConnection.into());
}
}
log_info!("Successfully executed automation");
log!("It might take a few seconds for the credential to arrive",);
info!({ "message": "Successfully executed automation"});
info!({ "message": "It might take a few seconds for the credential to arrive"});
loader.stop();
}
},
Expand Down Expand Up @@ -187,7 +190,7 @@ async fn credential_offer(
);
attributes.insert(String::from("Security Code"), String::from("063"));
attributes.insert(String::from("Valid Until"), String::from("20251212"));
log_debug!("Mock credential:\n{:#?}", attributes);
debug!({ "message": "Mock credential", "attributes": attributes });

let automation = CredentialOfferAutomation {
connection_id,
Expand Down
2 changes: 1 addition & 1 deletion crates/cli/src/modules/basic_message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,6 @@ pub async fn parse_basic_message_args(
};
agent.send_message(send_options).await.map(|_| {
loader.stop();
log!("Successfully sent message");
info!({ "message": "Successfully sent message"});
})
}
Loading

0 comments on commit 204a1ff

Please sign in to comment.