Skip to content

Commit

Permalink
refactor: Tracker Checker: use clap and anyhow
Browse files Browse the repository at this point in the history
  • Loading branch information
josecelano committed Jan 30, 2024
1 parent 75a502f commit 8543190
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 48 deletions.
60 changes: 22 additions & 38 deletions src/checker/app.rs
Original file line number Diff line number Diff line change
@@ -1,57 +1,41 @@
use std::path::PathBuf;
use std::sync::Arc;

use anyhow::Context;
use clap::Parser;

use super::config::Configuration;
use super::console::Console;
use super::service::{CheckError, Service};
use super::service::{CheckResult, Service};
use crate::checker::config::parse_from_json;

pub const NUMBER_OF_ARGUMENTS: usize = 2;
#[derive(Parser, Debug)]

Check warning on line 12 in src/checker/app.rs

View check run for this annotation

Codecov / codecov/patch

src/checker/app.rs#L12

Added line #L12 was not covered by tests
#[clap(author, version, about, long_about = None)]
struct Args {
config_path: PathBuf,

Check warning on line 15 in src/checker/app.rs

View check run for this annotation

Codecov / codecov/patch

src/checker/app.rs#L15

Added line #L15 was not covered by tests
}

/// # Errors
///
/// If some checks fails it will return a vector with all failing checks.
///
/// # Panics
///
/// Will panic if:
///
/// - It can't read the json configuration file.
/// - The configuration file is invalid.
pub async fn run() -> Result<(), Vec<CheckError>> {
let args = parse_arguments();
let config = setup_config(&args);
/// Will return an error if it can't read or parse the configuration file.
pub async fn run() -> anyhow::Result<Vec<CheckResult>> {

Check warning on line 21 in src/checker/app.rs

View check run for this annotation

Codecov / codecov/patch

src/checker/app.rs#L21

Added line #L21 was not covered by tests
let args = Args::parse();

let config = setup_config(&args)?;

let console_printer = Console {};

let service = Service {
config: Arc::new(config),
console: console_printer,
};

service.run_checks().await
}

pub struct Arguments {
pub config_path: String,
}

fn parse_arguments() -> Arguments {
let args: Vec<String> = std::env::args().collect();

if args.len() < NUMBER_OF_ARGUMENTS {
eprintln!("Usage: cargo run --bin tracker_checker <PATH_TO_CONFIG_FILE>");
eprintln!("For example: cargo run --bin tracker_checker ./share/default/config/tracker_checker.json");
std::process::exit(1);
}

let config_path = &args[1];

Arguments {
config_path: config_path.to_string(),
}
Ok(service.run_checks().await)
}

fn setup_config(args: &Arguments) -> Configuration {
let file_content = std::fs::read_to_string(args.config_path.clone())
.unwrap_or_else(|_| panic!("Can't read config file {}", args.config_path));
fn setup_config(args: &Args) -> anyhow::Result<Configuration> {
let file_content =
std::fs::read_to_string(&args.config_path).with_context(|| format!("can't read config file {:?}", args.config_path))?;

Check warning on line 38 in src/checker/app.rs

View check run for this annotation

Codecov / codecov/patch

src/checker/app.rs#L36-L38

Added lines #L36 - L38 were not covered by tests

parse_from_json(&file_content).expect("Invalid config format")
parse_from_json(&file_content).context("invalid config format")

Check warning on line 40 in src/checker/app.rs

View check run for this annotation

Codecov / codecov/patch

src/checker/app.rs#L40

Added line #L40 was not covered by tests
}
3 changes: 3 additions & 0 deletions src/checker/config.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::error::Error;
use std::fmt;
use std::net::SocketAddr;

Expand Down Expand Up @@ -43,6 +44,8 @@ pub enum ConfigurationError {
InvalidUrl(url::ParseError),
}

impl Error for ConfigurationError {}

impl fmt::Display for ConfigurationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Expand Down
18 changes: 8 additions & 10 deletions src/checker/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ pub struct Service {
pub(crate) console: Console,
}

pub type CheckResult = Result<(), CheckError>;

#[derive(Debug)]
pub enum CheckError {
UdpError,
Expand All @@ -25,7 +27,7 @@ impl Service {
/// # Errors
///
/// Will return OK is all checks pass or an array with the check errors.
pub async fn run_checks(&self) -> Result<(), Vec<CheckError>> {
pub async fn run_checks(&self) -> Vec<CheckResult> {

Check warning on line 30 in src/checker/service.rs

View check run for this annotation

Codecov / codecov/patch

src/checker/service.rs#L30

Added line #L30 was not covered by tests
self.console.println("Running checks for trackers ...");

self.check_udp_trackers();
Expand All @@ -50,23 +52,19 @@ impl Service {
}
}

async fn run_health_checks(&self) -> Result<(), Vec<CheckError>> {
async fn run_health_checks(&self) -> Vec<CheckResult> {

Check warning on line 55 in src/checker/service.rs

View check run for this annotation

Codecov / codecov/patch

src/checker/service.rs#L55

Added line #L55 was not covered by tests
self.console.println("Health checks ...");

let mut check_errors = vec![];
let mut check_results = vec![];

for health_check_url in &self.config.health_checks {
match self.run_health_check(health_check_url.clone()).await {
Ok(()) => {}
Err(err) => check_errors.push(err),
Ok(()) => check_results.push(Ok(())),
Err(err) => check_results.push(Err(err)),
}
}

if check_errors.is_empty() {
Ok(())
} else {
Err(check_errors)
}
check_results
}

fn check_udp_tracker(&self, address: &SocketAddr) {
Expand Down

0 comments on commit 8543190

Please sign in to comment.