Skip to content

Commit

Permalink
use clap + config (replace toml)
Browse files Browse the repository at this point in the history
  • Loading branch information
plebhash committed Mar 29, 2024
1 parent f8aa15f commit a7f746f
Show file tree
Hide file tree
Showing 29 changed files with 731 additions and 588 deletions.
442 changes: 418 additions & 24 deletions roles/Cargo.lock

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion roles/jd-client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,10 @@ roles_logic_sv2 = { version = "^1.0.0", path = "../../protocols/v2/roles-logic-s
serde = { version = "1.0.89", default-features = false, features = ["derive", "alloc"] }
futures = "0.3.25"
tokio = { version = "1", features = ["full"] }
toml = { version = "0.5.6", git = "https://github.com/diondokter/toml-rs", default-features = false, rev = "c4161aa" }
tracing = { version = "0.1" }
tracing-subscriber = { version = "0.3" }
error_handling = { version = "1.0.0", path = "../../utils/error-handling" }
nohash-hasher = "0.2.0"
key-utils = { version = "^1.0.0", path = "../../utils/key-utils" }
clap = { version = "^4.5.4", features = ["derive"] }
config = { version = "0.14.0", features = ["toml"] }
91 changes: 24 additions & 67 deletions roles/jd-client/src/args.rs
Original file line number Diff line number Diff line change
@@ -1,78 +1,35 @@
use crate::lib::{
error::{JdcError, JdcResult},
error::JdcResult,
jdc_config::JdcConfig,
};
use std::path::PathBuf;
use tracing::error;

#[derive(Debug)]
pub struct Args {
pub config_path: PathBuf,
use clap::Parser;

#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Args {
#[arg(
short,
long,
help = "Path to TOML configuration file"
)]
config_path: String,
}

enum ArgsState {
Next,
ExpectPath,
Done,
}

enum ArgsResult {
Config(PathBuf),
None,
Help(String),
}

impl Args {
const DEFAULT_CONFIG_PATH: &'static str = "jdc-config.toml";
const HELP_MSG: &'static str = "Usage: -h/--help, -c/--config <path|default jdc-config.toml>";

pub fn from_args() -> Result<Self, String> {
let cli_args = std::env::args();

if cli_args.len() == 1 {
println!("Using default config path: {}", Self::DEFAULT_CONFIG_PATH);
println!("{}\n", Self::HELP_MSG);
}

let config_path = cli_args
.scan(ArgsState::Next, |state, item| {
match std::mem::replace(state, ArgsState::Done) {
ArgsState::Next => match item.as_str() {
"-c" | "--config" => {
*state = ArgsState::ExpectPath;
Some(ArgsResult::None)
}
"-h" | "--help" => Some(ArgsResult::Help(Self::HELP_MSG.to_string())),
_ => {
*state = ArgsState::Next;

Some(ArgsResult::None)
}
},
ArgsState::ExpectPath => Some(ArgsResult::Config(PathBuf::from(item))),
ArgsState::Done => None,
}
})
.last();
let config_path = match config_path {
Some(ArgsResult::Config(p)) => p,
Some(ArgsResult::Help(h)) => return Err(h),
_ => PathBuf::from(Self::DEFAULT_CONFIG_PATH),
};
Ok(Self { config_path })
}
}

/// Process CLI args, if any.
#[allow(clippy::result_large_err)]
pub fn process_cli_args<'a>() -> JdcResult<'a, JdcConfig> {
let args = match Args::from_args() {
let args = Args::parse();
let config = match config::Config::builder()
.add_source(config::File::with_name(&args.config_path))
.build() {
Ok(cfg) => cfg,
Err(help) => {
error!("{}", help);
return Err(JdcError::BadCliArgs);
Err(e) => {
tracing::error!("{:?}", e);
std::process::exit(1)
}
};
let config_file = std::fs::read_to_string(args.config_path)?;
Ok(toml::from_str::<JdcConfig>(&config_file)?)
}

let jdc_config: JdcConfig = config.try_deserialize()?;

Ok(jdc_config)
}
18 changes: 6 additions & 12 deletions roles/jd-client/src/lib/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,7 @@ pub enum ChannelSendError<'a> {
#[derive(Debug)]
pub enum JdcError<'a> {
VecToSlice32(Vec<u8>),
/// Errors on bad CLI argument input.
BadCliArgs,
/// Errors on bad `toml` deserialize.
BadTomlDeserialize(toml::de::Error),
ConfigError(config::ConfigError),
/// Errors from `binary_sv2` crate.
BinarySv2(binary_sv2::Error),
/// Errors on bad noise handshake.
Expand Down Expand Up @@ -62,8 +59,7 @@ impl<'a> fmt::Display for JdcError<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use JdcError::*;
match self {
BadCliArgs => write!(f, "Bad CLI arg input"),
BadTomlDeserialize(ref e) => write!(f, "Bad `toml` deserialize: `{:?}`", e),
ConfigError(e) => write!(f, "Config error: {:?}", e),
BinarySv2(ref e) => write!(f, "Binary SV2 error: `{:?}`", e),
CodecNoise(ref e) => write!(f, "Noise error: `{:?}", e),
FramingSv2(ref e) => write!(f, "Framing SV2 error: `{:?}`", e),
Expand All @@ -83,6 +79,10 @@ impl<'a> fmt::Display for JdcError<'a> {
}
}

impl<'a> From<config::ConfigError> for JdcError<'a> {
fn from(e: config::ConfigError) -> JdcError<'a> { JdcError::ConfigError(e) }
}

impl<'a> From<binary_sv2::Error> for JdcError<'a> {
fn from(e: binary_sv2::Error) -> Self {
JdcError::BinarySv2(e)
Expand Down Expand Up @@ -119,12 +119,6 @@ impl<'a> From<roles_logic_sv2::errors::Error> for JdcError<'a> {
}
}

impl<'a> From<toml::de::Error> for JdcError<'a> {
fn from(e: toml::de::Error) -> Self {
JdcError::BadTomlDeserialize(e)
}
}

impl<'a> From<async_channel::RecvError> for JdcError<'a> {
fn from(e: async_channel::RecvError) -> Self {
JdcError::ChannelErrorReceiver(e)
Expand Down
9 changes: 2 additions & 7 deletions roles/jd-client/src/lib/status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,8 @@ pub async fn handle_error(
match e {
JdcError::VecToSlice32(_) => {
send_status(sender, e, error_handling::ErrorBranch::Break).await
}
// Errors on bad CLI argument input.
JdcError::BadCliArgs => send_status(sender, e, error_handling::ErrorBranch::Break).await,
// Errors on bad `toml` deserialize.
JdcError::BadTomlDeserialize(_) => {
send_status(sender, e, error_handling::ErrorBranch::Break).await
}
},
JdcError::ConfigError(_) => send_status(sender, e, error_handling::ErrorBranch::Break).await,
// Errors from `binary_sv2` crate.
JdcError::BinarySv2(_) => send_status(sender, e, error_handling::ErrorBranch::Break).await,
// Errors on bad noise handshake.
Expand Down
3 changes: 2 additions & 1 deletion roles/jd-server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ noise_sv2 = { version = "1.1.0", path = "../../protocols/v2/noise-sv2" }
rand = "0.8.4"
roles_logic_sv2 = { version = "^1.0.0", path = "../../protocols/v2/roles-logic-sv2" }
tokio = { version = "1", features = ["full"] }
toml = { version = "0.5.6", git = "https://github.com/diondokter/toml-rs", default-features = false, rev = "c4161aa" }
tracing = { version = "0.1" }
tracing-subscriber = "0.3"
error_handling = { version = "1.0.0", path = "../../utils/error-handling" }
Expand All @@ -33,3 +32,5 @@ key-utils = { version = "^1.0.0", path = "../../utils/key-utils" }
secp256k1 = { version = "0.28.2", default-features = false, features =["alloc","rand","rand-std"] }
rpc_sv2 = { version = "1.0.0", path = "../roles-utils/rpc" }
hex = "0.4.3"
clap = { version = "^4.5.4", features = ["derive"] }
config = { version = "0.14.0", features = ["toml"] }
92 changes: 24 additions & 68 deletions roles/jd-server/src/args.rs
Original file line number Diff line number Diff line change
@@ -1,78 +1,34 @@
use crate::lib::{
error::{JdsError, JdsResult},
error::JdsResult,
jds_config::JdsConfig,
};
use std::path::PathBuf;
use tracing::error;

#[derive(Debug)]
pub struct Args {
pub config_path: PathBuf,
}

enum ArgsState {
Next,
ExpectPath,
Done,
}

enum ArgsResult {
Config(PathBuf),
None,
Help(String),
use clap::Parser;

#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Args {
#[arg(
short,
long,
help = "Path to TOML configuration file"
)]
config_path: String,
}

impl Args {
const DEFAULT_CONFIG_PATH: &'static str = "jds-config.toml";
const HELP_MSG: &'static str = "Usage: -h/--help, -c/--config <path|default jds-config.toml>";

pub fn from_args() -> Result<Self, String> {
let cli_args = std::env::args();

if cli_args.len() == 1 {
println!("Using default config path: {}", Self::DEFAULT_CONFIG_PATH);
println!("{}\n", Self::HELP_MSG);
}

let config_path = cli_args
.scan(ArgsState::Next, |state, item| {
match std::mem::replace(state, ArgsState::Done) {
ArgsState::Next => match item.as_str() {
"-c" | "--config" => {
*state = ArgsState::ExpectPath;
Some(ArgsResult::None)
}
"-h" | "--help" => Some(ArgsResult::Help(Self::HELP_MSG.to_string())),
_ => {
*state = ArgsState::Next;

Some(ArgsResult::None)
}
},
ArgsState::ExpectPath => Some(ArgsResult::Config(PathBuf::from(item))),
ArgsState::Done => None,
}
})
.last();
let config_path = match config_path {
Some(ArgsResult::Config(p)) => p,
Some(ArgsResult::Help(h)) => return Err(h),
_ => PathBuf::from(Self::DEFAULT_CONFIG_PATH),
};
Ok(Self { config_path })
}
}

/// Process CLI args, if any.
#[allow(clippy::result_large_err)]
pub fn process_cli_args() -> JdsResult<JdsConfig> {
let args = match Args::from_args() {
let args = Args::parse();
let config = match config::Config::builder()
.add_source(config::File::with_name(&args.config_path))
.build() {
Ok(cfg) => cfg,
Err(help) => {
error!("{}", help);
return Err(JdsError::BadCliArgs);
Err(e) => {
tracing::error!("{:?}", e);
std::process::exit(1)
}
};
let config_file = std::fs::read_to_string(args.config_path)?;
Ok(toml::from_str::<JdsConfig>(&config_file)?)
}

let jds_config: JdsConfig = config.try_deserialize()?;

Ok(jds_config)
}
16 changes: 6 additions & 10 deletions roles/jd-server/src/lib/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ pub type JdsResult<T> = core::result::Result<T, JdsError>;

#[derive(std::fmt::Debug)]
pub enum JdsError {
BadCliArgs,
BadTomlDeserialize(toml::de::Error),
ConfigError(config::ConfigError),
Io(std::io::Error),
ChannelSend(Box<dyn std::marker::Send + Debug>),
ChannelRecv(async_channel::RecvError),
Expand All @@ -34,8 +33,7 @@ impl std::fmt::Display for JdsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use JdsError::*;
match self {
BadCliArgs => write!(f, "Bad CLI arg input"),
BadTomlDeserialize(ref e) => write!(f, "Bad `toml` deserialize: `{:?}`", e),
ConfigError(e) => write!(f, "Config error: {:?}", e),
Io(ref e) => write!(f, "I/O error: `{:?}", e),
ChannelSend(ref e) => write!(f, "Channel send failed: `{:?}`", e),
ChannelRecv(ref e) => write!(f, "Channel recv failed: `{:?}`", e),
Expand All @@ -58,6 +56,10 @@ impl std::fmt::Display for JdsError {
}
}

impl From<config::ConfigError> for JdsError {
fn from(e: config::ConfigError) -> JdsError { JdsError::ConfigError(e) }
}

impl From<std::io::Error> for JdsError {
fn from(e: std::io::Error) -> JdsError {
JdsError::Io(e)
Expand Down Expand Up @@ -94,12 +96,6 @@ impl From<roles_logic_sv2::Error> for JdsError {
}
}

impl From<toml::de::Error> for JdsError {
fn from(e: toml::de::Error) -> Self {
JdsError::BadTomlDeserialize(e)
}
}

impl<T: 'static + std::marker::Send + Debug> From<async_channel::SendError<T>> for JdsError {
fn from(e: async_channel::SendError<T>) -> JdsError {
JdsError::ChannelSend(Box::new(e))
Expand Down
5 changes: 1 addition & 4 deletions roles/jd-server/src/lib/status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,10 +98,7 @@ async fn send_status(
pub async fn handle_error(sender: &Sender, e: JdsError) -> error_handling::ErrorBranch {
tracing::debug!("Error: {:?}", &e);
match e {
JdsError::BadCliArgs => send_status(sender, e, error_handling::ErrorBranch::Break).await,
JdsError::BadTomlDeserialize(_) => {
send_status(sender, e, error_handling::ErrorBranch::Break).await
}
JdsError::ConfigError(_) => send_status(sender, e, error_handling::ErrorBranch::Break).await,
JdsError::Io(_) => send_status(sender, e, error_handling::ErrorBranch::Break).await,
JdsError::ChannelSend(_) => {
//This should be a continue because if we fail to send to 1 downstream we should continue
Expand Down
3 changes: 2 additions & 1 deletion roles/mining-proxy/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,9 @@ once_cell = "1.12.0"
roles_logic_sv2 = { version = "^1.0.0", path = "../../protocols/v2/roles-logic-sv2" }
serde = { version = "1.0.89", features = ["derive", "alloc"], default-features = false }
tokio = { version = "1", features = ["full"] }
toml = { version = "0.5.6", git = "https://github.com/diondokter/toml-rs", default-features = false, rev = "c4161aa" }
tracing = {version = "0.1"}
tracing-subscriber = {version = "0.3"}
nohash-hasher = "0.2.0"
key-utils = { version = "^1.0.0", path = "../../utils/key-utils" }
clap = { version = "^4.5.4", features = ["derive"] }
config = { version = "0.14.0", features = ["toml"] }
Loading

0 comments on commit a7f746f

Please sign in to comment.