Skip to content

Commit

Permalink
feat: [#655] remove tracker mode in config
Browse files Browse the repository at this point in the history
Update the tracker configuration section to follow [changes in the tracker configuration](torrust/torrust-tracker#932).

```toml
[tracker]
mode = "public"
```

```toml
[tracker]
private = false
listed = false
```
  • Loading branch information
josecelano committed Jul 3, 2024
1 parent 425550b commit 6104103
Show file tree
Hide file tree
Showing 10 changed files with 57 additions and 109 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ threshold = "info"

[tracker]
api_url = "http://tracker:1212"
mode = "private"
listed = false
private = true
url = "http://tracker:7070"

[database]
Expand Down
85 changes: 12 additions & 73 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@
pub mod v2;
pub mod validator;

use std::str::FromStr;
use std::env;
use std::sync::Arc;
use std::{env, fmt};

use camino::Utf8PathBuf;
use derive_more::Display;
Expand Down Expand Up @@ -200,70 +199,6 @@ impl From<figment::Error> for Error {
}
}

/// The mode the tracker is running in.
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]
pub enum TrackerMode {
/// Will track every new info hash and serve every peer.
#[serde(rename = "public")]
Public,

/// Will only track whitelisted info hashes.
#[serde(rename = "listed")]
Listed,

/// Will only serve authenticated peers
#[serde(rename = "private")]
Private,

/// Will only track whitelisted info hashes and serve authenticated peers
#[serde(rename = "private_listed")]
PrivateListed,
}

impl Default for TrackerMode {
fn default() -> Self {
Self::Public
}
}

impl fmt::Display for TrackerMode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let display_str = match self {
TrackerMode::Public => "public",
TrackerMode::Listed => "listed",
TrackerMode::Private => "private",
TrackerMode::PrivateListed => "private_listed",
};
write!(f, "{display_str}")
}
}

impl FromStr for TrackerMode {
type Err = String;

fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"public" => Ok(TrackerMode::Public),
"listed" => Ok(TrackerMode::Listed),
"private" => Ok(TrackerMode::Private),
"private_listed" => Ok(TrackerMode::PrivateListed),
_ => Err(format!("Unknown tracker mode: {s}")),
}
}
}

impl TrackerMode {
#[must_use]
pub fn is_open(&self) -> bool {
matches!(self, TrackerMode::Public | TrackerMode::Listed)
}

#[must_use]
pub fn is_close(&self) -> bool {
!self.is_open()
}
}

/// Port number representing that the OS will choose one randomly from the available ports.
///
/// It's the port number `0`
Expand Down Expand Up @@ -369,7 +304,8 @@ impl Configuration {
ConfigurationPublic {
website_name: settings_lock.website.name.clone(),
tracker_url: settings_lock.tracker.url.clone(),
tracker_mode: settings_lock.tracker.mode.clone(),
tracker_listed: settings_lock.tracker.listed,
tracker_private: settings_lock.tracker.private,
email_on_signup: settings_lock.auth.email_on_signup.clone(),
}
}
Expand All @@ -392,7 +328,8 @@ impl Configuration {
pub struct ConfigurationPublic {
website_name: String,
tracker_url: Url,
tracker_mode: TrackerMode,
tracker_listed: bool,
tracker_private: bool,
email_on_signup: EmailOnSignup,
}

Expand All @@ -415,7 +352,8 @@ mod tests {
[tracker]
api_url = "http://localhost:1212/"
mode = "public"
listed = false
private = false
token = "MyAccessToken"
token_valid_seconds = 7257600
url = "udp://localhost:6969"
Expand Down Expand Up @@ -497,7 +435,8 @@ mod tests {
ConfigurationPublic {
website_name: all_settings.website.name,
tracker_url: all_settings.tracker.url,
tracker_mode: all_settings.tracker.mode,
tracker_listed: all_settings.tracker.listed,
tracker_private: all_settings.tracker.private,
email_on_signup: all_settings.auth.email_on_signup,
}
);
Expand Down Expand Up @@ -586,14 +525,14 @@ mod tests {
use url::Url;

use crate::config::validator::Validator;
use crate::config::{Configuration, TrackerMode};
use crate::config::Configuration;

#[tokio::test]
async fn udp_trackers_in_close_mode_are_not_supported() {
async fn udp_trackers_in_private_mode_are_not_supported() {
let configuration = Configuration::default();

let mut settings_lock = configuration.settings.write().await;
settings_lock.tracker.mode = TrackerMode::Private;
settings_lock.tracker.private = true;
settings_lock.tracker.url = Url::parse("udp://localhost:6969").unwrap();

assert!(settings_lock.validate().is_err());
Expand Down
27 changes: 16 additions & 11 deletions src/config/v2/tracker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use serde::{Deserialize, Serialize};
use url::Url;

use super::{ValidationError, Validator};
use crate::config::TrackerMode;

/// Configuration for the associated tracker.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
Expand All @@ -13,9 +12,13 @@ pub struct Tracker {
#[serde(default = "Tracker::default_api_url")]
pub api_url: Url,

/// The mode the tracker is running in.
#[serde(default = "Tracker::default_mode")]
pub mode: TrackerMode,
/// Whether the tracker is running in listed mode or not.
#[serde(default = "Tracker::default_listed")]
pub listed: bool,

/// Whether the tracker is running in private mode or not.
#[serde(default = "Tracker::default_private")]
pub private: bool,

/// The token used to authenticate with the tracker API.
#[serde(default = "Tracker::default_token")]
Expand All @@ -32,10 +35,7 @@ pub struct Tracker {

impl Validator for Tracker {
fn validate(&self) -> Result<(), ValidationError> {
let tracker_mode = self.mode.clone();
let tracker_url = self.url.clone();

if tracker_mode.is_close() && (tracker_url.scheme() != "http" && tracker_url.scheme() != "https") {
if self.private && (self.url.scheme() != "http" && self.url.scheme() != "https") {
return Err(ValidationError::UdpTrackersInPrivateModeNotSupported);
}

Expand All @@ -47,7 +47,8 @@ impl Default for Tracker {
fn default() -> Self {
Self {
url: Self::default_url(),
mode: Self::default_mode(),
listed: Self::default_listed(),
private: Self::default_private(),
api_url: Self::default_api_url(),
token: Self::default_token(),
token_valid_seconds: Self::default_token_valid_seconds(),
Expand All @@ -64,8 +65,12 @@ impl Tracker {
Url::parse("udp://localhost:6969").unwrap()
}

fn default_mode() -> TrackerMode {
TrackerMode::default()
fn default_listed() -> bool {
false
}

fn default_private() -> bool {
false
}

fn default_api_url() -> Url {
Expand Down
7 changes: 4 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
//! ```toml
//! [tracker]
//! url = "udp://localhost:6969"
//! mode = "public"
//!
//! api_url = "http://localhost:1212/"
//! token = "MyAccessToken"
//! token_valid_seconds = 7257600
Expand Down Expand Up @@ -170,11 +170,12 @@
//! name = "Torrust"
//!
//! [tracker]
//! url = "udp://localhost:6969"
//! mode = "public"
//! api_url = "http://localhost:1212/"
//! listed = false
//! private = false
//! token = "MyAccessToken"
//! token_valid_seconds = 7257600
//! url = "udp://localhost:6969"
//!
//! [net]
//! bind_address = "0.0.0.0:3001"
Expand Down
19 changes: 9 additions & 10 deletions src/services/torrent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use tracing::debug;
use url::Url;

use super::category::DbCategoryRepository;
use crate::config::{Configuration, TrackerMode};
use crate::config::Configuration;
use crate::databases::database::{Database, Error, Sorting};
use crate::errors::ServiceError;
use crate::models::category::CategoryId;
Expand Down Expand Up @@ -261,12 +261,12 @@ impl Index {
let mut torrent = self.torrent_repository.get_by_info_hash(info_hash).await?;

let tracker_url = self.get_tracker_url().await;
let tracker_mode = self.get_tracker_mode().await;
let tracker_is_private = self.tracker_is_private().await;

// code-review: should we remove all tracker URLs in the `announce_list`
// when the tracker is not open?
// when the tracker is private?

if tracker_mode.is_open() {
if !tracker_is_private {
torrent.include_url_as_main_tracker(&tracker_url);
} else if let Some(authenticated_user_id) = opt_user_id {
let personal_announce_url = self.tracker_service.get_personal_announce_url(authenticated_user_id).await?;
Expand Down Expand Up @@ -438,9 +438,9 @@ impl Index {
settings.tracker.url.clone()
}

async fn get_tracker_mode(&self) -> TrackerMode {
async fn tracker_is_private(&self) -> bool {
let settings = self.configuration.settings.read().await;
settings.tracker.mode.clone()
settings.tracker.private
}

async fn build_short_torrent_response(
Expand Down Expand Up @@ -497,11 +497,8 @@ impl Index {
torrent_response.trackers = self.torrent_announce_url_repository.get_by_torrent_id(&torrent_id).await?;

let tracker_url = self.get_tracker_url().await;
let tracker_mode = self.get_tracker_mode().await;

if tracker_mode.is_open() {
torrent_response.include_url_as_main_tracker(&tracker_url);
} else {
if self.tracker_is_private().await {
// Add main tracker URL
match opt_user_id {
Some(user_id) => {
Expand All @@ -513,6 +510,8 @@ impl Index {
torrent_response.include_url_as_main_tracker(&tracker_url);
}
}
} else {
torrent_response.include_url_as_main_tracker(&tracker_url);
}

// Add magnet link
Expand Down
6 changes: 4 additions & 2 deletions src/web/api/client/v1/contexts/settings/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ pub struct Website {
#[derive(Deserialize, Serialize, PartialEq, Debug, Clone)]
pub struct Tracker {
pub url: Url,
pub mode: String,
pub listed: bool,
pub private: bool,
pub api_url: Url,
pub token: ApiToken,
pub token_valid_seconds: u64,
Expand Down Expand Up @@ -132,7 +133,8 @@ impl From<DomainTracker> for Tracker {
fn from(tracker: DomainTracker) -> Self {
Self {
url: tracker.url,
mode: format!("{:?}", tracker.mode),
listed: tracker.listed,
private: tracker.private,
api_url: tracker.api_url,
token: tracker.token,
token_valid_seconds: tracker.token_valid_seconds,
Expand Down
6 changes: 4 additions & 2 deletions tests/common/contexts/settings/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ pub struct Website {
#[derive(Deserialize, Serialize, PartialEq, Debug, Clone)]
pub struct Tracker {
pub url: Url,
pub mode: String,
pub listed: bool,
pub private: bool,
pub api_url: Url,
pub token: ApiToken,
pub token_valid_seconds: u64,
Expand Down Expand Up @@ -145,7 +146,8 @@ impl From<DomainTracker> for Tracker {
fn from(tracker: DomainTracker) -> Self {
Self {
url: tracker.url,
mode: tracker.mode.to_string(),
listed: tracker.listed,
private: tracker.private,
api_url: tracker.api_url,
token: tracker.token,
token_valid_seconds: tracker.token_valid_seconds,
Expand Down
3 changes: 2 additions & 1 deletion tests/common/contexts/settings/responses.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ pub struct PublicSettingsResponse {
pub struct Public {
pub website_name: String,
pub tracker_url: Url,
pub tracker_mode: String,
pub tracker_listed: bool,
pub tracker_private: bool,
pub email_on_signup: String,
}

Expand Down
7 changes: 2 additions & 5 deletions tests/e2e/environment.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use std::env;
use std::str::FromStr;

use torrust_index::config::{ApiToken, TrackerMode};
use torrust_index::config::ApiToken;
use torrust_index::web::api::Version;
use url::Url;

Expand Down Expand Up @@ -88,9 +87,7 @@ impl TestEnv {
};

match self.server_settings() {
Some(settings) => {
TrackerMode::from_str(&settings.tracker.mode).expect("it should be a valid tracker mode") == TrackerMode::Private
}
Some(settings) => settings.tracker.private,
None => false,
}
}
Expand Down
3 changes: 2 additions & 1 deletion tests/e2e/web/api/v1/contexts/settings/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ async fn it_should_allow_guests_to_get_the_public_settings() {
Public {
website_name: env.server_settings().unwrap().website.name,
tracker_url: env.server_settings().unwrap().tracker.url,
tracker_mode: env.server_settings().unwrap().tracker.mode,
tracker_listed: env.server_settings().unwrap().tracker.listed,
tracker_private: env.server_settings().unwrap().tracker.private,
email_on_signup: env.server_settings().unwrap().auth.email_on_signup,
}
);
Expand Down

0 comments on commit 6104103

Please sign in to comment.