chore: use dprint

This commit is contained in:
Einliterflasche 2024-08-20 14:52:43 +02:00
parent 6fd5ac8690
commit 2d9ed8f8fe
9 changed files with 66 additions and 47 deletions

View file

@ -10,8 +10,6 @@ use crate::seed::Seed;
use crate::{bitcoin, common, monero}; use crate::{bitcoin, common, monero};
use anyhow::{bail, Context as AnyContext, Error, Result}; use anyhow::{bail, Context as AnyContext, Error, Result};
use futures::future::try_join_all; use futures::future::try_join_all;
use tracing::level_filters::LevelFilter;
use tracing::Level;
use std::fmt; use std::fmt;
use std::future::Future; use std::future::Future;
use std::net::SocketAddr; use std::net::SocketAddr;
@ -19,6 +17,8 @@ use std::path::PathBuf;
use std::sync::{Arc, Once}; use std::sync::{Arc, Once};
use tokio::sync::{broadcast, broadcast::Sender, Mutex, RwLock}; use tokio::sync::{broadcast, broadcast::Sender, Mutex, RwLock};
use tokio::task::JoinHandle; use tokio::task::JoinHandle;
use tracing::level_filters::LevelFilter;
use tracing::Level;
use url::Url; use url::Url;
static START: Once = Once::new(); static START: Once = Once::new();

View file

@ -53,7 +53,7 @@ pub enum Method {
Logs { Logs {
logs_dir: Option<PathBuf>, logs_dir: Option<PathBuf>,
redact: bool, redact: bool,
swap_id: Option<Uuid> swap_id: Option<Uuid>,
}, },
Config, Config,
WithdrawBtc { WithdrawBtc {
@ -747,7 +747,11 @@ impl Request {
Ok(json!({"swaps": json_results})) 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 dir = logs_dir.unwrap_or(context.config.data_dir.join("logs"));
let logs = get_logs(dir, swap_id, redact).await?; let logs = get_logs(dir, swap_id, redact).await?;

View file

@ -292,9 +292,9 @@ pub enum RawCommand {
#[structopt( #[structopt(
long = "swap-id", long = "swap-id",
help = "Filter for logs concerning this swap.", 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.")] #[structopt(about = "Prints swap-id and the state of each swap ever made.")]
History { History {

View file

@ -18,13 +18,12 @@ use libp2p::core::multiaddr::Protocol;
use libp2p::core::Multiaddr; use libp2p::core::Multiaddr;
use libp2p::swarm::AddressScore; use libp2p::swarm::AddressScore;
use libp2p::Swarm; use libp2p::Swarm;
use swap::common::tracing_util::Format;
use rust_decimal::prelude::FromPrimitive; use rust_decimal::prelude::FromPrimitive;
use rust_decimal::Decimal; use rust_decimal::Decimal;
use std::convert::TryInto; use std::convert::TryInto;
use std::env;
use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::sync::Arc; use std::sync::Arc;
use std::env;
use structopt::clap; use structopt::clap;
use structopt::clap::ErrorKind; use structopt::clap::ErrorKind;
use swap::asb::command::{parse_args, Arguments, Command}; 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, 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::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::common::{self, check_latest_version, get_logs};
use swap::database::{open_db, AccessMode}; use swap::database::{open_db, AccessMode};
use swap::network::rendezvous::XmrBtcNamespace; use swap::network::rendezvous::XmrBtcNamespace;
@ -86,8 +86,7 @@ async fn main() -> Result<()> {
// initialize tracing // initialize tracing
let format = if json { Format::Json } else { Format::Raw }; let format = if json { Format::Json } else { Format::Raw };
let log_dir = config.data.dir.join("logs"); let log_dir = config.data.dir.join("logs");
common::tracing_util::init(LevelFilter::DEBUG, format, log_dir) common::tracing_util::init(LevelFilter::DEBUG, format, log_dir).expect("initialize tracing");
.expect("initialize tracing");
// check for conflicting env / config values // check for conflicting env / config values
if config.monero.network != env_config.monero_network { if config.monero.network != env_config.monero_network {

View file

@ -108,10 +108,16 @@ where
CliCommand::Logs { CliCommand::Logs {
logs_dir, logs_dir,
redact, redact,
swap_id swap_id,
} => { } => {
let request = Request::new(Method::Logs { logs_dir, redact, swap_id }); let request = Request::new(Method::Logs {
let context = Context::build(None, None, None, data, is_testnet, debug, json, None, false).await?; logs_dir,
redact,
swap_id,
});
let context =
Context::build(None, None, None, data, is_testnet, debug, json, None, false)
.await?;
(context, request) (context, request)
} }
@ -366,9 +372,9 @@ enum CliCommand {
#[structopt( #[structopt(
long = "swap-id", long = "swap-id",
help = "Filter for logs concerning this swap.", 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")] #[structopt(about = "Prints the current config")]
Config, Config,

View file

@ -3,7 +3,10 @@ pub mod tracing_util;
use std::{collections::HashMap, path::PathBuf}; use std::{collections::HashMap, path::PathBuf};
use anyhow::anyhow; use anyhow::anyhow;
use tokio::{fs::{read_dir, File}, io::{AsyncBufReadExt, BufReader}}; use tokio::{
fs::{read_dir, File},
io::{AsyncBufReadExt, BufReader},
};
use uuid::Uuid; use uuid::Uuid;
const LATEST_RELEASE_URL: &str = "https://github.com/comit-network/xmr-btc-swap/releases/latest"; const LATEST_RELEASE_URL: &str = "https://github.com/comit-network/xmr-btc-swap/releases/latest";
@ -71,7 +74,11 @@ macro_rules! regex_find_placeholders {
/// to the specified path or the terminal. /// to the specified path or the terminal.
/// ///
/// If specified, filter by swap id or redact addresses. /// 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()); tracing::debug!("reading logfiles from {}", logs_dir.display());
// get all files in the directory // get all files in the directory
@ -111,7 +118,11 @@ pub async fn get_logs(logs_dir: PathBuf, swap_id: Option<Uuid>, redact_addresses
} }
// redact if necessary // 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 // save redacted message
log_messages.push(line); log_messages.push(line);
} }

View file

@ -5,8 +5,8 @@ use anyhow::Result;
use tracing_subscriber::filter::{Directive, LevelFilter}; use tracing_subscriber::filter::{Directive, LevelFilter};
use tracing_subscriber::fmt::time::UtcTime; use tracing_subscriber::fmt::time::UtcTime;
use tracing_subscriber::layer::SubscriberExt; use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::{fmt, EnvFilter, Layer};
use tracing_subscriber::util::SubscriberInitExt; use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::{fmt, EnvFilter, Layer};
/// Output formats for logging messages. /// Output formats for logging messages.
pub enum Format { pub enum Format {
@ -20,18 +20,9 @@ pub enum Format {
/// Besides printing to `stdout`, this will append to a log file. /// Besides printing to `stdout`, this will append to a log file.
/// Said file will contain JSON-formatted logs of all levels, /// Said file will contain JSON-formatted logs of all levels,
/// disregarding the arguments to this function. /// disregarding the arguments to this function.
pub fn init( pub fn init(level_filter: LevelFilter, format: Format, dir: impl AsRef<Path>) -> Result<()> {
level_filter: LevelFilter,
format: Format,
dir: impl AsRef<Path>,
) -> Result<()> {
let env_filter = EnvFilter::from_default_env() let env_filter = EnvFilter::from_default_env()
.add_directive(Directive::from_str( .add_directive(Directive::from_str(&format!("asb={}", &level_filter,))?)
&format!(
"asb={}",
&level_filter,
)
)?)
.add_directive(Directive::from_str(&format!("swap={}", &level_filter))?); .add_directive(Directive::from_str(&format!("swap={}", &level_filter))?);
// file logger will always write in JSON format and with timestamps // file logger will always write in JSON format and with timestamps

View file

@ -26,8 +26,7 @@ impl SqliteDatabase {
let read_only = matches!(access_mode, AccessMode::ReadOnly); let read_only = matches!(access_mode, AccessMode::ReadOnly);
let path_str = format!("sqlite:{}", path.as_ref().display()); let path_str = format!("sqlite:{}", path.as_ref().display());
let mut options = SqliteConnectOptions::from_str(&path_str)? let mut options = SqliteConnectOptions::from_str(&path_str)?.read_only(read_only);
.read_only(read_only);
options.disable_statement_logging(); options.disable_statement_logging();
let pool = SqlitePool::connect_with(options).await?; let pool = SqlitePool::connect_with(options).await?;

View file

@ -59,12 +59,21 @@ pub fn register_modules(context: Arc<Context>) -> Result<RpcModule<Arc<Context>>
struct Params { struct Params {
swap_id: Option<Uuid>, swap_id: Option<Uuid>,
logs_dir: Option<PathBuf>, logs_dir: Option<PathBuf>,
redact: bool redact: bool,
} }
let params: Params = params_raw.parse()?; 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 { module.register_async_method("get_raw_states", |params, context| async move {