From 2d9ed8f8fe3766ccfc87e9e32ffb09898af3b891 Mon Sep 17 00:00:00 2001 From: Einliterflasche Date: Tue, 20 Aug 2024 14:52:43 +0200 Subject: [PATCH] chore: use dprint --- swap/src/api.rs | 4 ++-- swap/src/api/request.rs | 14 +++++++++----- swap/src/asb/command.rs | 4 ++-- swap/src/bin/asb.rs | 11 +++++------ swap/src/cli/command.rs | 16 +++++++++++----- swap/src/common/mod.rs | 25 ++++++++++++++++++------- swap/src/common/tracing_util.rs | 23 +++++++---------------- swap/src/database/sqlite.rs | 3 +-- swap/src/rpc/methods.rs | 13 +++++++++++-- 9 files changed, 66 insertions(+), 47 deletions(-) diff --git a/swap/src/api.rs b/swap/src/api.rs index c2b6f73aa..ea87aae39 100644 --- a/swap/src/api.rs +++ b/swap/src/api.rs @@ -10,8 +10,6 @@ use crate::seed::Seed; use crate::{bitcoin, common, monero}; use anyhow::{bail, Context as AnyContext, Error, Result}; use futures::future::try_join_all; -use tracing::level_filters::LevelFilter; -use tracing::Level; use std::fmt; use std::future::Future; use std::net::SocketAddr; @@ -19,6 +17,8 @@ use std::path::PathBuf; use std::sync::{Arc, Once}; use tokio::sync::{broadcast, broadcast::Sender, Mutex, RwLock}; use tokio::task::JoinHandle; +use tracing::level_filters::LevelFilter; +use tracing::Level; use url::Url; static START: Once = Once::new(); diff --git a/swap/src/api/request.rs b/swap/src/api/request.rs index 863737da0..33e261d34 100644 --- a/swap/src/api/request.rs +++ b/swap/src/api/request.rs @@ -53,7 +53,7 @@ pub enum Method { Logs { logs_dir: Option, redact: bool, - swap_id: Option + swap_id: Option, }, Config, WithdrawBtc { @@ -134,8 +134,8 @@ impl Method { } Method::Logs { .. } => { debug_span!( - "method", - method_name = "Logs", + "method", + method_name = "Logs", log_reference_id = field::Empty ) } @@ -747,7 +747,11 @@ impl Request { Ok(json!({"swaps": json_results})) } - Method::Logs { logs_dir, redact, swap_id } => { + Method::Logs { + logs_dir, + redact, + swap_id, + } => { let dir = logs_dir.unwrap_or(context.config.data_dir.join("logs")); let logs = get_logs(dir, swap_id, redact).await?; @@ -944,7 +948,7 @@ impl Request { pub async fn call(self, context: Arc) -> Result { let method_span = self.cmd.get_tracing_span(self.log_reference.clone()); - + self.handle_cmd(context) .instrument(method_span.clone()) .await diff --git a/swap/src/asb/command.rs b/swap/src/asb/command.rs index 7e78bc9d3..675650656 100644 --- a/swap/src/asb/command.rs +++ b/swap/src/asb/command.rs @@ -292,9 +292,9 @@ pub enum RawCommand { #[structopt( long = "swap-id", help = "Filter for logs concerning this swap.", - long_help = "This checks whether each logging message contains the swap id. Some messages might be skipped when they don't contain the swap id even though they're relevant.", + long_help = "This checks whether each logging message contains the swap id. Some messages might be skipped when they don't contain the swap id even though they're relevant." )] - swap_id: Option + swap_id: Option, }, #[structopt(about = "Prints swap-id and the state of each swap ever made.")] History { diff --git a/swap/src/bin/asb.rs b/swap/src/bin/asb.rs index 0876fbc96..3a0d2dd44 100644 --- a/swap/src/bin/asb.rs +++ b/swap/src/bin/asb.rs @@ -18,13 +18,12 @@ use libp2p::core::multiaddr::Protocol; use libp2p::core::Multiaddr; use libp2p::swarm::AddressScore; use libp2p::Swarm; -use swap::common::tracing_util::Format; use rust_decimal::prelude::FromPrimitive; use rust_decimal::Decimal; use std::convert::TryInto; +use std::env; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::Arc; -use std::env; use structopt::clap; use structopt::clap::ErrorKind; use swap::asb::command::{parse_args, Arguments, Command}; @@ -32,6 +31,7 @@ use swap::asb::config::{ initial_setup, query_user_for_initial_config, read_config, Config, ConfigNotInitialized, }; use swap::asb::{cancel, punish, redeem, refund, safely_abort, EventLoop, Finality, KrakenRate}; +use swap::common::tracing_util::Format; use swap::common::{self, check_latest_version, get_logs}; use swap::database::{open_db, AccessMode}; use swap::network::rendezvous::XmrBtcNamespace; @@ -72,7 +72,7 @@ async fn main() -> Result<()> { // warn if we're not on the latest version if let Err(e) = check_latest_version(env!("CARGO_PKG_VERSION")).await { eprintln!("{}", e); - } + } // read config from the specified path let config = match read_config(config_path.clone())? { @@ -86,9 +86,8 @@ async fn main() -> Result<()> { // initialize tracing let format = if json { Format::Json } else { Format::Raw }; let log_dir = config.data.dir.join("logs"); - common::tracing_util::init(LevelFilter::DEBUG, format, log_dir) - .expect("initialize tracing"); - + common::tracing_util::init(LevelFilter::DEBUG, format, log_dir).expect("initialize tracing"); + // check for conflicting env / config values if config.monero.network != env_config.monero_network { bail!(format!( diff --git a/swap/src/cli/command.rs b/swap/src/cli/command.rs index f7dadc3c6..acce7a50c 100644 --- a/swap/src/cli/command.rs +++ b/swap/src/cli/command.rs @@ -108,10 +108,16 @@ where CliCommand::Logs { logs_dir, redact, - swap_id + swap_id, } => { - let request = Request::new(Method::Logs { logs_dir, redact, swap_id }); - let context = Context::build(None, None, None, data, is_testnet, debug, json, None, false).await?; + let request = Request::new(Method::Logs { + logs_dir, + redact, + swap_id, + }); + let context = + Context::build(None, None, None, data, is_testnet, debug, json, None, false) + .await?; (context, request) } @@ -366,9 +372,9 @@ enum CliCommand { #[structopt( long = "swap-id", help = "Filter for logs concerning this swap.", - long_help = "This checks whether each logging message contains the swap id. Some messages might be skipped when they don't contain the swap id even though they're relevant.", + long_help = "This checks whether each logging message contains the swap id. Some messages might be skipped when they don't contain the swap id even though they're relevant." )] - swap_id: Option + swap_id: Option, }, #[structopt(about = "Prints the current config")] Config, diff --git a/swap/src/common/mod.rs b/swap/src/common/mod.rs index 1935814ec..1341692c2 100644 --- a/swap/src/common/mod.rs +++ b/swap/src/common/mod.rs @@ -3,7 +3,10 @@ pub mod tracing_util; use std::{collections::HashMap, path::PathBuf}; use anyhow::anyhow; -use tokio::{fs::{read_dir, File}, io::{AsyncBufReadExt, BufReader}}; +use tokio::{ + fs::{read_dir, File}, + io::{AsyncBufReadExt, BufReader}, +}; use uuid::Uuid; const LATEST_RELEASE_URL: &str = "https://github.com/comit-network/xmr-btc-swap/releases/latest"; @@ -67,11 +70,15 @@ macro_rules! regex_find_placeholders { }}; } -/// Print the logs from the specified logs or from the default location +/// Print the logs from the specified logs or from the default location /// to the specified path or the terminal. -/// +/// /// If specified, filter by swap id or redact addresses. -pub async fn get_logs(logs_dir: PathBuf, swap_id: Option, redact_addresses: bool) -> anyhow::Result> { +pub async fn get_logs( + logs_dir: PathBuf, + swap_id: Option, + redact_addresses: bool, +) -> anyhow::Result> { tracing::debug!("reading logfiles from {}", logs_dir.display()); // get all files in the directory @@ -107,11 +114,15 @@ pub async fn get_logs(logs_dir: PathBuf, swap_id: Option, redact_addresses // we only want lines which contain the swap id if !line.contains(&swap_id.to_string()) { continue; - } + } } // redact if necessary - let line = if redact_addresses { redact_with(&line, &mut placeholders) } else { line }; + let line = if redact_addresses { + redact_with(&line, &mut placeholders) + } else { + line + }; // save redacted message log_messages.push(line); } @@ -135,7 +146,7 @@ pub fn redact(input: &str) -> String { redact_with(input, &mut replacements) } -/// Same as [`redact`] but retrieves palceholders from and stores them +/// Same as [`redact`] but retrieves palceholders from and stores them /// in a specified hashmap. pub fn redact_with(input: &str, replacements: &mut HashMap) -> String { // TODO: verify regex patterns diff --git a/swap/src/common/tracing_util.rs b/swap/src/common/tracing_util.rs index 372d3b201..3308085e7 100644 --- a/swap/src/common/tracing_util.rs +++ b/swap/src/common/tracing_util.rs @@ -5,8 +5,8 @@ use anyhow::Result; use tracing_subscriber::filter::{Directive, LevelFilter}; use tracing_subscriber::fmt::time::UtcTime; use tracing_subscriber::layer::SubscriberExt; -use tracing_subscriber::{fmt, EnvFilter, Layer}; use tracing_subscriber::util::SubscriberInitExt; +use tracing_subscriber::{fmt, EnvFilter, Layer}; /// Output formats for logging messages. pub enum Format { @@ -17,21 +17,12 @@ pub enum Format { } /// Initialize tracing and enable logging messages according to these options. -/// Besides printing to `stdout`, this will append to a log file. -/// Said file will contain JSON-formatted logs of all levels, +/// Besides printing to `stdout`, this will append to a log file. +/// Said file will contain JSON-formatted logs of all levels, /// disregarding the arguments to this function. -pub fn init( - level_filter: LevelFilter, - format: Format, - dir: impl AsRef, -) -> Result<()> { +pub fn init(level_filter: LevelFilter, format: Format, dir: impl AsRef) -> Result<()> { let env_filter = EnvFilter::from_default_env() - .add_directive(Directive::from_str( - &format!( - "asb={}", - &level_filter, - ) - )?) + .add_directive(Directive::from_str(&format!("asb={}", &level_filter,))?) .add_directive(Directive::from_str(&format!("swap={}", &level_filter))?); // file logger will always write in JSON format and with timestamps @@ -53,7 +44,7 @@ pub fn init( .with_timer(UtcTime::rfc_3339()) .with_target(false); - // combine the layers and start logging, format with json if specified + // combine the layers and start logging, format with json if specified if let Format::Json = format { tracing_subscriber::registry() .with(file_layer) @@ -65,7 +56,7 @@ pub fn init( .with(terminal_layer.with_filter(level_filter)) .init(); } - + // now we can use the tracing macros to log messages tracing::info!(%level_filter, logs_dir=%dir.as_ref().display(), "Initialized tracing"); diff --git a/swap/src/database/sqlite.rs b/swap/src/database/sqlite.rs index d35ffa4d5..ce455b6c2 100644 --- a/swap/src/database/sqlite.rs +++ b/swap/src/database/sqlite.rs @@ -26,8 +26,7 @@ impl SqliteDatabase { let read_only = matches!(access_mode, AccessMode::ReadOnly); let path_str = format!("sqlite:{}", path.as_ref().display()); - let mut options = SqliteConnectOptions::from_str(&path_str)? - .read_only(read_only); + let mut options = SqliteConnectOptions::from_str(&path_str)?.read_only(read_only); options.disable_statement_logging(); let pool = SqlitePool::connect_with(options).await?; diff --git a/swap/src/rpc/methods.rs b/swap/src/rpc/methods.rs index 0577bf673..dd3d9a620 100644 --- a/swap/src/rpc/methods.rs +++ b/swap/src/rpc/methods.rs @@ -59,12 +59,21 @@ pub fn register_modules(context: Arc) -> Result> struct Params { swap_id: Option, logs_dir: Option, - redact: bool + redact: bool, } let params: Params = params_raw.parse()?; - execute_request(params_raw, Method::Logs { swap_id: params.swap_id, logs_dir: params.logs_dir, redact: params.redact }, &context).await + execute_request( + params_raw, + Method::Logs { + swap_id: params.swap_id, + logs_dir: params.logs_dir, + redact: params.redact, + }, + &context, + ) + .await })?; module.register_async_method("get_raw_states", |params, context| async move {