Skip to content

Commit

Permalink
refactor: [#143] remove duplicate or unneeded code
Browse files Browse the repository at this point in the history
  • Loading branch information
josecelano committed Jan 3, 2023
1 parent 0615c9f commit 0f99f7b
Show file tree
Hide file tree
Showing 9 changed files with 55 additions and 102 deletions.
35 changes: 35 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use std::str::FromStr;
use std::{env, fs};

use config::{Config, ConfigError, File, FileFormat};
use rand::{thread_rng, Rng};
use serde::{Deserialize, Serialize};
use serde_with::{serde_as, NoneAsEmptyString};
use {std, toml};
Expand Down Expand Up @@ -73,6 +74,40 @@ pub enum Error {
TrackerModeIncompatible,
}

/// This configuration is used for testing. It generates random config values so they do not collide
/// if you run more than one tracker at the same time.
///
/// # Panics
///
/// Will panic if it can't convert the temp file path to string
#[must_use]
pub fn ephemeral_configuration() -> Configuration {
let mut config = Configuration {
log_level: Some("off".to_owned()),
..Default::default()
};

// Ephemeral socket addresses
let api_port = random_port();
config.http_api.bind_address = format!("127.0.0.1:{}", &api_port);
let upd_port = random_port();
config.udp_trackers[0].bind_address = format!("127.0.0.1:{}", &upd_port);

// Ephemeral sqlite database
let temp_directory = env::temp_dir();
let temp_file = temp_directory.join(format!("data_{}_{}.db", &api_port, &upd_port));
config.db_path = temp_file.to_str().unwrap().to_owned();

config
}

fn random_port() -> u16 {
// todo: this may produce random test failures because two tests can try to bind the same port.
// We could create a pool of available ports (with read/write lock)
let mut rng = thread_rng();
rng.gen_range(49152..65535)
}

impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Expand Down
1 change: 1 addition & 0 deletions src/tracker/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ pub struct Tracker {
database: Box<dyn Database>,
}

#[derive(Debug, PartialEq, Default)]
pub struct TorrentsMetrics {
pub seeders: u64,
pub completed: u64,
Expand Down
1 change: 1 addition & 0 deletions src/tracker/services/statistics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::sync::Arc;
use crate::tracker::statistics::Metrics;
use crate::tracker::{TorrentsMetrics, Tracker};

#[derive(Debug, PartialEq)]
pub struct TrackerMetrics {
pub torrents_metrics: TorrentsMetrics,
pub protocol_metrics: Metrics,
Expand Down
32 changes: 3 additions & 29 deletions src/tracker/statistics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ pub enum Event {
Udp6Scrape,
}

#[derive(Debug)]
#[derive(Debug, PartialEq, Default)]
pub struct Metrics {
pub tcp4_connections_handled: u64,
pub tcp4_announces_handled: u64,
Expand All @@ -39,32 +39,6 @@ pub struct Metrics {
pub udp6_scrapes_handled: u64,
}

impl Default for Metrics {
fn default() -> Self {
Self::new()
}
}

impl Metrics {
#[must_use]
pub fn new() -> Self {
Self {
tcp4_connections_handled: 0,
tcp4_announces_handled: 0,
tcp4_scrapes_handled: 0,
tcp6_connections_handled: 0,
tcp6_announces_handled: 0,
tcp6_scrapes_handled: 0,
udp4_connections_handled: 0,
udp4_announces_handled: 0,
udp4_scrapes_handled: 0,
udp6_connections_handled: 0,
udp6_announces_handled: 0,
udp6_scrapes_handled: 0,
}
}
}

pub struct Keeper {
pub repository: Repo,
}
Expand Down Expand Up @@ -187,7 +161,7 @@ impl Repo {
#[must_use]
pub fn new() -> Self {
Self {
stats: Arc::new(RwLock::new(Metrics::new())),
stats: Arc::new(RwLock::new(Metrics::default())),
}
}

Expand Down Expand Up @@ -280,7 +254,7 @@ mod tests {

let stats = stats_tracker.repository.get_stats().await;

assert_eq!(stats.tcp4_announces_handled, Metrics::new().tcp4_announces_handled);
assert_eq!(stats.tcp4_announces_handled, Metrics::default().tcp4_announces_handled);
}

#[tokio::test]
Expand Down
28 changes: 3 additions & 25 deletions src/udp/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,14 +239,13 @@ fn handle_error(e: &Error, transaction_id: TransactionId) -> Response {

#[cfg(test)]
mod tests {
use std::env;

use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::sync::Arc;

use aquatic_udp_protocol::{AnnounceEvent, NumberOfBytes};
use rand::{thread_rng, Rng};

use crate::config::Configuration;
use crate::config::{ephemeral_configuration, Configuration};
use crate::protocol::clock::{Current, Time};
use crate::tracker::{self, mode, peer, statistics};

Expand All @@ -255,28 +254,7 @@ mod tests {
}

fn default_testing_tracker_configuration() -> Configuration {
let mut config = Configuration {
log_level: Some("off".to_owned()),
..Default::default()
};

// Ephemeral socket address
let port = ephemeral_random_port();
config.http_api.bind_address = format!("127.0.0.1:{}", &port);

// Ephemeral database
let temp_directory = env::temp_dir();
let temp_file = temp_directory.join(format!("data_{}.db", &port));
config.db_path = temp_file.to_str().unwrap().to_owned();

config
}

fn ephemeral_random_port() -> u16 {
// todo: this may produce random test failures because two tests can try to bind the same port.
// We could create a pool of available ports (with read/write lock)
let mut rng = thread_rng();
rng.gen_range(49152..65535)
ephemeral_configuration()
}

fn initialized_public_tracker() -> Arc<tracker::Tracker> {
Expand Down
20 changes: 2 additions & 18 deletions tests/api/server.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use core::panic;
use std::env;
use std::sync::Arc;

use torrust_tracker::config::Configuration;
use torrust_tracker::config::{ephemeral_configuration, Configuration};
use torrust_tracker::jobs::{tracker_api, tracker_apis};
use torrust_tracker::protocol::info_hash::InfoHash;
use torrust_tracker::tracker::peer::Peer;
Expand All @@ -11,24 +10,9 @@ use torrust_tracker::{ephemeral_instance_keys, logging, static_time, tracker};

use super::connection_info::ConnectionInfo;
use super::Version;
use crate::common::ephemeral_random_port;

pub fn tracker_configuration() -> Arc<Configuration> {
let mut config = Configuration {
log_level: Some("off".to_owned()),
..Default::default()
};

// Ephemeral socket address
let port = ephemeral_random_port();
config.http_api.bind_address = format!("127.0.0.1:{}", &port);

// Ephemeral database
let temp_directory = env::temp_dir();
let temp_file = temp_directory.join(format!("data_{}.db", &port));
config.db_path = temp_file.to_str().unwrap().to_owned();

Arc::new(config)
Arc::new(ephemeral_configuration())
}

pub async fn start_default_api(version: &Version) -> Server {
Expand Down
8 changes: 0 additions & 8 deletions tests/common/mod.rs

This file was deleted.

1 change: 0 additions & 1 deletion tests/tracker_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
extern crate rand;

mod api;
mod common;

mod tracker_api {

Expand Down
31 changes: 10 additions & 21 deletions tests/udp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,8 @@
/// cargo test `udp_tracker_server` -- --nocapture
extern crate rand;

mod common;

mod udp_tracker_server {
use core::panic;
use std::env;
use std::io::Cursor;
use std::net::Ipv4Addr;
use std::sync::atomic::{AtomicBool, Ordering};
Expand All @@ -17,32 +14,24 @@ mod udp_tracker_server {
AnnounceEvent, AnnounceRequest, ConnectRequest, ConnectionId, InfoHash, NumberOfBytes, NumberOfPeers, PeerId, PeerKey,
Port, Request, Response, ScrapeRequest, TransactionId,
};
use rand::{thread_rng, Rng};
use tokio::net::UdpSocket;
use tokio::task::JoinHandle;
use torrust_tracker::config::Configuration;
use torrust_tracker::config::{ephemeral_configuration, Configuration};
use torrust_tracker::jobs::udp_tracker;
use torrust_tracker::tracker::statistics::Keeper;
use torrust_tracker::udp::MAX_PACKET_SIZE;
use torrust_tracker::{ephemeral_instance_keys, logging, static_time, tracker};

use crate::common::ephemeral_random_port;

fn tracker_configuration() -> Arc<Configuration> {
let mut config = Configuration {
log_level: Some("off".to_owned()),
..Default::default()
};

// Ephemeral socket address
let port = ephemeral_random_port();
config.udp_trackers[0].bind_address = format!("127.0.0.1:{}", &port);

// Ephemeral database
let temp_directory = env::temp_dir();
let temp_file = temp_directory.join(format!("data_{}.db", &port));
config.db_path = temp_file.to_str().unwrap().to_owned();
Arc::new(ephemeral_configuration())
}

Arc::new(config)
pub fn ephemeral_random_client_port() -> u16 {
// todo: this may produce random test failures because two tests can try to bind the same port.
// We could create a pool of available ports (with read/write lock)
let mut rng = thread_rng();
rng.gen_range(49152..65535)
}

pub struct UdpServer {
Expand Down Expand Up @@ -129,7 +118,7 @@ mod udp_tracker_server {

/// Creates a new `UdpClient` connected to a Udp server
async fn new_connected_udp_client(remote_address: &str) -> UdpClient {
let client = UdpClient::bind(&source_address(ephemeral_random_port())).await;
let client = UdpClient::bind(&source_address(ephemeral_random_client_port())).await;
client.connect(remote_address).await;
client
}
Expand Down

0 comments on commit 0f99f7b

Please sign in to comment.