Skip to content

Commit

Permalink
refactor: [#852] enrich field types in Configuration struct
Browse files Browse the repository at this point in the history
  • Loading branch information
josecelano committed May 10, 2024
1 parent ceb3074 commit 7519ecc
Show file tree
Hide file tree
Showing 7 changed files with 46 additions and 27 deletions.
17 changes: 17 additions & 0 deletions packages/configuration/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,3 +171,20 @@ pub struct TslConfig {
#[serde_as(as = "NoneAsEmptyString")]
pub ssl_key_path: Option<Utf8PathBuf>,
}

#[derive(Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
#[serde(rename_all = "lowercase")]
pub enum LogLevel {
/// A level lower than all log levels.
Off,
/// Corresponds to the `Error` log level.
Error,
/// Corresponds to the `Warn` log level.
Warn,
/// Corresponds to the `Info` log level.
Info,
/// Corresponds to the `Debug` log level.
Debug,
/// Corresponds to the `Trace` log level.
Trace,
}
25 changes: 10 additions & 15 deletions packages/configuration/src/v1/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,8 +236,7 @@ pub mod tracker_api;
pub mod udp_tracker;

use std::fs;
use std::net::IpAddr;
use std::str::FromStr;
use std::net::{IpAddr, Ipv4Addr};

use figment::providers::{Env, Format, Serialized, Toml};
use figment::Figment;
Expand All @@ -248,15 +247,15 @@ use self::health_check_api::HealthCheckApi;
use self::http_tracker::HttpTracker;
use self::tracker_api::HttpApi;
use self::udp_tracker::UdpTracker;
use crate::{AnnouncePolicy, Error, Info};
use crate::{AnnouncePolicy, Error, Info, LogLevel};

/// Core configuration for the tracker.
#[allow(clippy::struct_excessive_bools)]
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]
pub struct Configuration {
/// Logging level. Possible values are: `Off`, `Error`, `Warn`, `Info`,
/// `Debug` and `Trace`. Default is `Info`.
pub log_level: Option<String>,
pub log_level: Option<LogLevel>,
/// Tracker mode. See [`TrackerMode`] for more information.
pub mode: TrackerMode,

Expand Down Expand Up @@ -284,7 +283,7 @@ pub struct Configuration {
/// is using a loopback IP address, the tracker assumes that the peer is
/// in the same network as the tracker and will use the tracker's IP
/// address instead.
pub external_ip: Option<String>,
pub external_ip: Option<IpAddr>,
/// Weather the tracker should collect statistics about tracker usage.
/// If enabled, the tracker will collect statistics like the number of
/// connections handled, the number of announce requests handled, etc.
Expand Down Expand Up @@ -330,15 +329,15 @@ impl Default for Configuration {
let announce_policy = AnnouncePolicy::default();

let mut configuration = Configuration {
log_level: Option::from(String::from("info")),
log_level: Some(LogLevel::Info),
mode: TrackerMode::Public,
db_driver: DatabaseDriver::Sqlite3,
db_path: String::from("./storage/tracker/lib/database/sqlite3.db"),
announce_interval: announce_policy.interval,
min_announce_interval: announce_policy.interval_min,
max_peer_timeout: 900,
on_reverse_proxy: false,
external_ip: Some(String::from("0.0.0.0")),
external_ip: Some(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0))),
tracker_usage_statistics: true,
persistent_torrent_completed_stat: false,
inactive_peer_cleanup_interval: 600,
Expand All @@ -363,13 +362,7 @@ impl Configuration {
/// and `None` otherwise.
#[must_use]
pub fn get_ext_ip(&self) -> Option<IpAddr> {
match &self.external_ip {
None => None,
Some(external_ip) => match IpAddr::from_str(external_ip) {
Ok(external_ip) => Some(external_ip),
Err(_) => None,
},
}
self.external_ip.as_ref().map(|external_ip| *external_ip)
}

/// Saves the default configuration at the given path.
Expand Down Expand Up @@ -432,6 +425,8 @@ impl Configuration {
#[cfg(test)]
mod tests {

use std::net::{IpAddr, Ipv4Addr};

use crate::v1::Configuration;
use crate::Info;

Expand Down Expand Up @@ -495,7 +490,7 @@ mod tests {
fn configuration_should_contain_the_external_ip() {
let configuration = Configuration::default();

assert_eq!(configuration.external_ip, Some(String::from("0.0.0.0")));
assert_eq!(configuration.external_ip, Some(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0))));
}

#[test]
Expand Down
6 changes: 3 additions & 3 deletions packages/test-helpers/src/configuration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
use std::env;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};

use torrust_tracker_configuration::Configuration;
use torrust_tracker_configuration::{Configuration, LogLevel};
use torrust_tracker_primitives::TrackerMode;

use crate::random;
Expand All @@ -28,7 +28,7 @@ pub fn ephemeral() -> Configuration {
// For example: a test for the UDP tracker should disable the API and HTTP tracker.

let mut config = Configuration {
log_level: Some("off".to_owned()), // Change to `debug` for tests debugging
log_level: Some(LogLevel::Off), // Change to `debug` for tests debugging
..Default::default()
};

Expand Down Expand Up @@ -125,7 +125,7 @@ pub fn ephemeral_mode_private_whitelisted() -> Configuration {
pub fn ephemeral_with_external_ip(ip: IpAddr) -> Configuration {
let mut cfg = ephemeral();

cfg.external_ip = Some(ip.to_string());
cfg.external_ip = Some(ip);

cfg
}
Expand Down
14 changes: 10 additions & 4 deletions src/bootstrap/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,10 @@
//! - `Trace`
//!
//! Refer to the [configuration crate documentation](https://docs.rs/torrust-tracker-configuration) to know how to change log settings.
use std::str::FromStr;
use std::sync::Once;

use log::{info, LevelFilter};
use torrust_tracker_configuration::Configuration;
use torrust_tracker_configuration::{Configuration, LogLevel};

static INIT: Once = Once::new();

Expand All @@ -31,10 +30,17 @@ pub fn setup(cfg: &Configuration) {
});
}

fn config_level_or_default(log_level: &Option<String>) -> LevelFilter {
fn config_level_or_default(log_level: &Option<LogLevel>) -> LevelFilter {
match log_level {
None => log::LevelFilter::Info,
Some(level) => LevelFilter::from_str(level).unwrap(),
Some(level) => match level {
LogLevel::Off => LevelFilter::Off,
LogLevel::Error => LevelFilter::Error,
LogLevel::Warn => LevelFilter::Warn,
LogLevel::Info => LevelFilter::Info,
LogLevel::Debug => LevelFilter::Debug,
LogLevel::Trace => LevelFilter::Trace,
},
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/servers/apis/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,8 @@
//! > **NOTICE**: You can generate a self-signed certificate for localhost using
//! OpenSSL. See [Let's Encrypt](https://letsencrypt.org/docs/certificates-for-localhost/).
//! That's particularly useful for testing purposes. Once you have the certificate
//! you need to set the [`ssl_cert_path`](torrust_tracker_configuration::HttpApi::ssl_cert_path)
//! and [`ssl_key_path`](torrust_tracker_configuration::HttpApi::ssl_key_path)
//! you need to set the [`ssl_cert_path`](torrust_tracker_configuration::HttpApi::tsl_config.ssl_cert_path)
//! and [`ssl_key_path`](torrust_tracker_configuration::HttpApi::tsl_config.ssl_key_path)
//! options in the configuration file with the paths to the certificate
//! (`localhost.crt`) and key (`localhost.key`) files.
//!
Expand Down
5 changes: 3 additions & 2 deletions src/servers/http/v1/services/announce.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,8 +145,9 @@ mod tests {

fn tracker_with_an_ipv6_external_ip(stats_event_sender: Box<dyn statistics::EventSender>) -> Tracker {
let mut configuration = configuration::ephemeral();
configuration.external_ip =
Some(IpAddr::V6(Ipv6Addr::new(0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969)).to_string());
configuration.external_ip = Some(IpAddr::V6(Ipv6Addr::new(
0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969, 0x6969,
)));

Tracker::new(&configuration, Some(stats_event_sender), statistics::Repo::new()).unwrap()
}
Expand Down
2 changes: 1 addition & 1 deletion src/servers/udp/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -426,7 +426,7 @@ mod tests {
}

pub fn with_external_ip(mut self, external_ip: &str) -> Self {
self.configuration.external_ip = Some(external_ip.to_owned());
self.configuration.external_ip = Some(external_ip.to_owned().parse().expect("valid IP address"));
self
}

Expand Down

0 comments on commit 7519ecc

Please sign in to comment.