Skip to content

Commit

Permalink
chore: use dprint
Browse files Browse the repository at this point in the history
  • Loading branch information
Einliterflasche committed Aug 20, 2024
1 parent 6fd5ac8 commit 2d9ed8f
Show file tree
Hide file tree
Showing 9 changed files with 66 additions and 47 deletions.
4 changes: 2 additions & 2 deletions swap/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@ 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;
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();
Expand Down
14 changes: 9 additions & 5 deletions swap/src/api/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ pub enum Method {
Logs {
logs_dir: Option<PathBuf>,
redact: bool,
swap_id: Option<Uuid>
swap_id: Option<Uuid>,
},
Config,
WithdrawBtc {
Expand Down Expand Up @@ -134,8 +134,8 @@ impl Method {
}
Method::Logs { .. } => {
debug_span!(
"method",
method_name = "Logs",
"method",
method_name = "Logs",
log_reference_id = field::Empty
)
}
Expand Down Expand Up @@ -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?;

Expand Down Expand Up @@ -944,7 +948,7 @@ impl Request {

pub async fn call(self, context: Arc<Context>) -> Result<serde_json::Value> {
let method_span = self.cmd.get_tracing_span(self.log_reference.clone());

self.handle_cmd(context)
.instrument(method_span.clone())
.await
Expand Down
4 changes: 2 additions & 2 deletions swap/src/asb/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Uuid>
swap_id: Option<Uuid>,
},
#[structopt(about = "Prints swap-id and the state of each swap ever made.")]
History {
Expand Down
11 changes: 5 additions & 6 deletions swap/src/bin/asb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,20 @@ 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};
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;
Expand Down Expand Up @@ -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())? {
Expand All @@ -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!(
Expand Down
16 changes: 11 additions & 5 deletions swap/src/cli/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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<Uuid>
swap_id: Option<Uuid>,
},
#[structopt(about = "Prints the current config")]
Config,
Expand Down
25 changes: 18 additions & 7 deletions swap/src/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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<Uuid>, redact_addresses: bool) -> anyhow::Result<Vec<String>> {
pub async fn get_logs(
logs_dir: PathBuf,
swap_id: Option<Uuid>,
redact_addresses: bool,
) -> anyhow::Result<Vec<String>> {
tracing::debug!("reading logfiles from {}", logs_dir.display());

// get all files in the directory
Expand Down Expand Up @@ -107,11 +114,15 @@ pub async fn get_logs(logs_dir: PathBuf, swap_id: Option<Uuid>, 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);
}
Expand All @@ -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, String>) -> String {
// TODO: verify regex patterns
Expand Down
23 changes: 7 additions & 16 deletions swap/src/common/tracing_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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<Path>,
) -> Result<()> {
pub fn init(level_filter: LevelFilter, format: Format, dir: impl AsRef<Path>) -> 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
Expand All @@ -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)
Expand All @@ -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");

Expand Down
3 changes: 1 addition & 2 deletions swap/src/database/sqlite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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?;
Expand Down
13 changes: 11 additions & 2 deletions swap/src/rpc/methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,21 @@ pub fn register_modules(context: Arc<Context>) -> Result<RpcModule<Arc<Context>>
struct Params {
swap_id: Option<Uuid>,
logs_dir: Option<PathBuf>,
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 {
Expand Down

0 comments on commit 2d9ed8f

Please sign in to comment.